lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
|---|---|---|---|---|---|---|---|---|---|---|---|
Java
|
apache-2.0
|
d77f7e305687fbd060afa6c75541e2cd2420a46c
| 0
|
OpenHFT/Chronicle-Bytes
|
/*
* Copyright 2016-2020 Chronicle Software
*
* https://chronicle.software
*
* 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 net.openhft.chronicle.bytes;
import net.openhft.chronicle.core.io.Closeable;
import java.util.function.Supplier;
public interface MethodWriterBuilder<T> extends Supplier<T> {
@Deprecated(/* use methodWriterInterceptorReturns */)
MethodWriterBuilder<T> methodWriterListener(MethodWriterListener methodWriterListener);
MethodWriterBuilder<T> genericEvent(String genericEvent);
default MethodWriterBuilder<T> metaData(boolean metaData) {
return this;
}
MethodWriterBuilder<T> useMethodIds(boolean useMethodIds);
MethodWriterBuilder<T> onClose(Closeable closeable);
// sourceId enables this, this isn't useful unless it's set.
@Deprecated
MethodWriterBuilder<T> recordHistory(boolean recordHistory);
MethodWriterBuilder<T> methodWriterInterceptorReturns(MethodWriterInterceptorReturns writeInterceptor);
default T build() {
return get();
}
}
|
src/main/java/net/openhft/chronicle/bytes/MethodWriterBuilder.java
|
/*
* Copyright 2016-2020 Chronicle Software
*
* https://chronicle.software
*
* 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 net.openhft.chronicle.bytes;
import net.openhft.chronicle.core.io.Closeable;
import java.util.function.Supplier;
public interface MethodWriterBuilder<T> extends Supplier<T> {
@Deprecated(/* use methodWriterInterceptorReturns */)
MethodWriterBuilder<T> methodWriterListener(MethodWriterListener methodWriterListener);
MethodWriterBuilder<T> genericEvent(String genericEvent);
default MethodWriterBuilder<T> metaData(boolean metaData) {
return this;
}
MethodWriterBuilder<T> useMethodIds(boolean useMethodIds);
MethodWriterBuilder<T> onClose(Closeable closeable);
MethodWriterBuilder<T> recordHistory(boolean recordHistory);
MethodWriterBuilder<T> methodWriterInterceptorReturns(MethodWriterInterceptorReturns writeInterceptor);
default T build() {
return get();
}
}
|
Should be 2 entries not 1.
|
src/main/java/net/openhft/chronicle/bytes/MethodWriterBuilder.java
|
Should be 2 entries not 1.
|
|
Java
|
apache-2.0
|
78d1333a31e594366c88e7f85371de5a2f03170c
| 0
|
npryce/worktorule,npryce/worktorule
|
package com.natpryce.worktorule.issues.github;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class GitHubIssuesTest {
GitHubIssues issues = new GitHubIssues("npryce", "worktorule");
@Test
public void closedIssue() throws IOException {
assertFalse(issues.isOpen("1"));
}
@Test
public void openIssue() throws IOException {
assertTrue(issues.isOpen("2"));
}
}
|
src/test/java/com/natpryce/worktorule/issues/github/GitHubIssuesTest.java
|
package com.natpryce.worktorule.issues.github;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertFalse;
public class GitHubIssuesTest {
GitHubIssues issues = new GitHubIssues("npryce", "worktorule");
@Test
public void closedIssue() throws IOException {
assertFalse(issues.isOpen("1"));
}
}
|
Test for open github issue
|
src/test/java/com/natpryce/worktorule/issues/github/GitHubIssuesTest.java
|
Test for open github issue
|
|
Java
|
apache-2.0
|
934883648bb982c4220fb891360d6cae9cef8a49
| 0
|
macrozheng/mall,macrozheng/mall
|
package com.macro.mall.demo.config;
import com.macro.mall.demo.bo.AdminUserDetails;
import com.macro.mall.mapper.UmsAdminMapper;
import com.macro.mall.model.UmsAdmin;
import com.macro.mall.model.UmsAdminExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.util.List;
/**
* SpringSecurity的配置
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UmsAdminMapper umsAdminMapper;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()//配置权限
// .antMatchers("/").access("hasRole('TEST')")//该路径需要TEST角色
// .antMatchers("/brand/list").hasAuthority("TEST")//该路径需要TEST权限
.antMatchers("/**").permitAll()
.and()//启用基于http的认证
.httpBasic()
.realmName("/")
.and()//配置登录页面
.formLogin()
.loginPage("/login")
.failureUrl("/login?error=true")
.and()//配置退出路径
.logout()
.logoutSuccessUrl("/")
// .and()//记住密码功能
// .rememberMe()
// .tokenValiditySeconds(60*60*24)
// .key("rememberMeKey")
.and()//关闭跨域伪造
.csrf()
.disable()
.headers()//去除X-Frame-Options
.frameOptions()
.disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
}
@Bean
public UserDetailsService userDetailsService() {
//获取登录用户信息
return new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UmsAdminExample example = new UmsAdminExample();
example.createCriteria().andUsernameEqualTo(username);
List<UmsAdmin> umsAdminList = umsAdminMapper.selectByExample(example);
if (umsAdminList != null && umsAdminList.size() > 0) {
return new AdminUserDetails(umsAdminList.get(0));
}
throw new UsernameNotFoundException("用户名或密码错误");
}
};
}
}
|
mall-demo/src/main/java/com/macro/mall/demo/config/SecurityConfig.java
|
package com.macro.mall.demo.config;
import com.macro.mall.demo.bo.AdminUserDetails;
import com.macro.mall.mapper.UmsAdminMapper;
import com.macro.mall.model.UmsAdmin;
import com.macro.mall.model.UmsAdminExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.util.List;
/**
* SpringSecurity的配置
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UmsAdminMapper umsAdminMapper;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()//配置权限
// .antMatchers("/").access("hasRole('TEST')")//该路径需要TEST角色
.antMatchers("/").authenticated()//该路径需要登录认证
// .antMatchers("/brand/list").hasAuthority("TEST")//该路径需要TEST权限
.antMatchers("/**").permitAll()
.and()//启用基于http的认证
.httpBasic()
.realmName("/")
.and()//配置登录页面
.formLogin()
.loginPage("/login")
.failureUrl("/login?error=true")
.and()//配置退出路径
.logout()
.logoutSuccessUrl("/")
// .and()//记住密码功能
// .rememberMe()
// .tokenValiditySeconds(60*60*24)
// .key("rememberMeKey")
.and()//关闭跨域伪造
.csrf()
.disable()
.headers()//去除X-Frame-Options
.frameOptions()
.disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
}
@Bean
public UserDetailsService userDetailsService() {
//获取登录用户信息
return new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UmsAdminExample example = new UmsAdminExample();
example.createCriteria().andUsernameEqualTo(username);
List<UmsAdmin> umsAdminList = umsAdminMapper.selectByExample(example);
if (umsAdminList != null && umsAdminList.size() > 0) {
return new AdminUserDetails(umsAdminList.get(0));
}
throw new UsernameNotFoundException("用户名或密码错误");
}
};
}
}
|
Update SecurityConfig.java
|
mall-demo/src/main/java/com/macro/mall/demo/config/SecurityConfig.java
|
Update SecurityConfig.java
|
|
Java
|
apache-2.0
|
4989ecf15a168deb5bfbff8227076abd9051d867
| 0
|
reddcoin-project/reddcoinj-pow,cpacia/bitcoinj,VegasCoin/vegascoinj,paulminer/bitcoinj,Coinomi/bitcoinj,hank/litecoinj-new,schildbach/bitcoinj,stafur/trustpluscoinj,HashEngineering/mobilecashj,HashEngineering/digitalcoinj-mb,tangyves/bitcoinj,rnicoll/libdohj,HashEngineering/quarkcoinj,HashEngineering/myriadcoinj,patricklodder/libdohj,cannabiscoindev/cannabiscoinj,HashEngineering/frankoj,fsb4000/bitcoinj,meeh420/anoncoinj,HashEngineering/megacoinj,ohac/sha1coinj,sserrano44/bitcoinj-watcher-service,HashEngineering/digitalcoinj,yenliangl/bitcoinj,stafur/trustpluscoinj,Kefkius/groestlcoinj,natzei/bitcoinj,kurtwalker/bitcoinj,therightwaystudio/fork_bitcoinj,dexX7/bitcoinj,HashEngineering/megacoinj,TheBlueMatt/bitcoinj,HashEngineering/unobtaniumj,jdojff/bitcoinj,jife94/bitcoinj,devrandom/bitcoinj,HashEngineering/groestlcoinj,habibmasuro/smileycoinj,langerhans/dogecoinj-new,cannabiscoindev/cannabiscoinj,HashEngineering/maxcoinj,bitsquare/bitcoinj,bitcoinj/bitcoinj,habibmasuro/smileycoinj,TrustPlus/trustpluscoinj,habibmasuro/smileycoinj,HashEngineering/namecoinj,GroestlCoin/groestlcoinj,rnicoll/altcoinj,Qw0kka/creditsj,marctrem/bitcoinj,RaviAjaibSingh/bitcoinj,Rimbit/rimbitj,devrandom/bitcoinj,bitbandi/spreadcoinj,veritaseum/bitcoinj,Enigmachine/btcjwork2,TrustPlus/trustpluscoinj,HashEngineering/groestlcoinj,tangyves/bitcoinj,bitcoin-solutions/bitcoinj-alice,wpstudio/blazecoinj,akonring/bitcoinj_generous,Coinomi/bitcoinj,kurtwalker/bitcoinj,patricklodder/bitcoinj,patricklodder/libdohj,ahmedbodi/anycoinj,FTraian/bitcoinj-uc,MonetaryUnit/monetaryunitj,natzei/bitcoinj,VegasCoin/vegascoinj,ahmedbodi/anycoinj,MikeHuntington/blackcoinj-new,praus/multicoinj,blockchain/bitcoinj,TheBlueMatt/bitcoinj,cpacia/bitcoinj,kris-davison/non-working-darkcoinj-fork,TrustPlus/trustpluscoinj,habibmasuro/litecoinj,jdojff/bitcoinj,GroestlCoin/groestlcoinj,dalbelap/bitcoinj,MintcoinCommunity/mintcoinj,HashEngineering/mobilecashj,AugieMillares/bitcoinj,MrDunne/bitcoinj,peacekeeper/bitcoinj,rootstock/bitcoinj,janko33bd/bitcoinj,VishalRao/bitcoinj,reddcoin-project/reddcoinj-pow,hank/litecoinj,peterdettman/bitcoinj,haxwell/bitcoinj,Kefkius/groestlcoinj,hank/feathercoinj,cbeams/bitcoinj,devrandom/bitcoinj,FTraian/bitcoinj-uc,tjth/bitcoinj-lotterycoin,HashEngineering/quarkcoinj,bankonme/monetaryunitj,stonecoldpat/bitcoinj,yezune/darkcoinj,Kefkius/groestlcoinj,GroestlCoin/groestlcoinj,cannabiscoindev/cannabiscoinj,TheBlueMatt/bitcoinj,schildbach/bitcoinj,dldinternet/bitcoinj,pelle/bitcoinj,danielmcclure/bitcoinj,MonetaryUnit/monetaryunitj,MintcoinCommunity/mintcoinj,DigiByte-Team/digibytej-alice,framewr/bitcoinj,techsubodh/admin_tracker,techsubodh/admin_tracker,yezune/darkcoinj,Crypto-Expert/digitalcoinj,bankonme/monetaryunitj,bankonme/monetaryunitj,DynamicCoinOrg/dmcJ,ligi/bitcoinj,HashEngineering/maxcoinj,bitbandi/spreadcoinj,patricklodder/bitcoinj,HashEngineering/dimecoinj,yezune/darkcoinj,HashEngineering/maxcoinj,paulmadore/woodcoinj,HashEngineering/darkcoinj,imzhuli/bitcoinj,HashEngineering/dashj,nikileshsa/bitcoinj,stafur/trustpluscoinj,greenaddress/bitcoinj,HashEngineering/groestlcoinj,tjth/bitcoinj-lotterycoin,cannabiscoindev/cannabiscoinj,fsb4000/bitcoinj,DigiByte-Team/digibytej-alice,HashEngineering/darkcoinj,UberPay/bitcoinj,stonecoldpat/bitcoinj,kmels/bitcoinj,HashEngineering/maxcoinj,ahmedbodi/anycoinj,HashEngineering/mobilecashj,jife94/bitcoinj,bitcoin-solutions/bitcoinj-alice,stafur/trustpluscoinj,fsb4000/bitcoinj,Coinomi/bitcoinj,bitbandi/spreadcoinj,HashEngineering/infinitecoinj,oscarguindzberg/bitcoinj,veritaseum/bitcoinj,jjculber/defcoinj,stonecoldpat/bitcoinj,HashEngineering/quarkcoinj,langerhans/dogecoinj-alice,cpacia/bitcoinj,mrosseel/bitcoinj-old,troggy/bitcoinj,techsubodh/admin_tracker,FTraian/bitcoinj-uc,yenliangl/bitcoinj,DigiByte-Team/digibytej-alice,jdojff/bitcoinj,keremhd/mintcoinj,HashEngineering/unobtaniumj,Kefkius/groestlcoinj,dogecoin/libdohj,patricklodder/libdohj,HashEngineering/namecoinj,HashEngineering/dashj,tangyves/bitcoinj,bitcoin-solutions/bitcoinj-alice,monapu/monacoinj-multibit,HashEngineering/unobtaniumj,HashEngineering/namecoinj,HashEngineering/myriadcoinj,PeterNSteinmetz/peternsteinmetz-bitcoinj,lavajumper/bitcoinj-scrypt,MintcoinCommunity/mintcoinj,kris-davison/non-working-darkcoinj-fork,you21979/bitcoinj,veritaseum/bitcoinj,peterdettman/bitcoinj,imsaguy/bitcoinj,tjth/bitcoinj-lotterycoin,kurtwalker/bitcoinj,HashEngineering/dimecoinj,HashEngineering/darkcoinj,funkshelper/bitcoinj,HashEngineering/maxcoinj,strawpay/bitcoinj,HashEngineering/megacoinj,HashEngineering/digitalcoinj,you21979/bitcoinj,reddcoin-project/reddcoinj-pow,HashEngineering/dashj,bitbandi/spreadcoinj,lavajumper/bitcoinj-scrypt,VegasCoin/vegascoinj,HashEngineering/dimecoinj,HashEngineering/anycoinj,Kefkius/groestlcoinj,rnicoll/bitcoinj,haxwell/bitcoinj,novitski/bitcoinj,MonetaryUnit/monetaryunitj,hughneale/bitcoinj,oscarguindzberg/bitcoinj,jife94/bitcoinj,HashEngineering/frankoj,dcw312/bitcoinj,yezune/darkcoinj,HashEngineering/myriadcoinj,designsters/android-fork-bitcoinj,kmels/bitcoinj,janko33bd/bitcoinj,HashEngineering/digitalcoinj,bitcoinj/bitcoinj,langerhans/bitcoinj-alice-hd,kris-davison/non-working-darkcoinj-fork,HashEngineering/dashj,you21979/bitcoinj,patricklodder/bitcoinj,HashEngineering/frankoj,coinspark/sparkbit-bitcoinj,Kangmo/bitcoinj,szdx/bitcoinj,bitbandi/spreadcoinj,haxwell/bitcoinj,lavajumper/bitcoinj-scrypt
|
/**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.core;
import org.spongycastle.util.encoders.Hex;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import static com.google.bitcoin.core.Utils.COIN;
import static com.google.common.base.Preconditions.checkState;
// TODO: Refactor this after we stop supporting serialization compatibility to use subclasses and singletons.
/**
* NetworkParameters contains the data needed for working with an instantiation of a Bitcoin chain.<p>
*
* Currently there are only two, the production chain and the test chain. But in future as Bitcoin
* evolves there may be more. You can create your own as long as they don't conflict.
*/
public class NetworkParameters implements Serializable {
private static final long serialVersionUID = 3L;
/**
* The protocol version this library implements.
*/
public static final int PROTOCOL_VERSION = 60001;
/**
* The alert signing key originally owned by Satoshi, and now passed on to Gavin along with a few others.
*/
public static final byte[] SATOSHI_KEY = Hex.decode("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284");
/**
* The string returned by getId() for the main, production network where people trade things.
*/
public static final String ID_PRODNET = "org.bitcoin.production";
/**
* The string returned by getId() for the testnet.
*/
public static final String ID_TESTNET = "org.bitcoin.test";
// TODO: Seed nodes should be here as well.
/**
* Genesis block for this chain.<p>
*
* The first block in every chain is a well known constant shared between all BitCoin implemenetations. For a
* block to be valid, it must be eventually possible to work backwards to the genesis block by following the
* prevBlockHash pointers in the block headers.<p>
*
* The genesis blocks for both test and prod networks contain the timestamp of when they were created,
* and a message in the coinbase transaction. It says, <i>"The Times 03/Jan/2009 Chancellor on brink of second
* bailout for banks"</i>.
*/
public Block genesisBlock;
/** What the easiest allowable proof of work should be. */
public BigInteger proofOfWorkLimit;
/** Default TCP port on which to connect to nodes. */
public int port;
/** The header bytes that identify the start of a packet on this network. */
public long packetMagic;
/**
* First byte of a base58 encoded address. See {@link Address}. This is the same as acceptableAddressCodes[0] and
* is the one used for "normal" addresses. Other types of address may be encountered with version codes found in
* the acceptableAddressCodes array.
*/
public int addressHeader;
/** First byte of a base58 encoded dumped private key. See {@link DumpedPrivateKey}. */
public int dumpedPrivateKeyHeader;
/** How many blocks pass between difficulty adjustment periods. BitCoin standardises this to be 2015. */
public int interval;
/**
* How much time in seconds is supposed to pass between "interval" blocks. If the actual elapsed time is
* significantly different from this value, the network difficulty formula will produce a different value. Both
* test and production Bitcoin networks use 2 weeks (1209600 seconds).
*/
public int targetTimespan;
/**
* The key used to sign {@link AlertMessage}s. You can use {@link ECKey#verify(byte[], byte[], byte[])} to verify
* signatures using it.
*/
public byte[] alertSigningKey;
/**
* See getId(). This may be null for old deserialized wallets. In that case we derive it heuristically
* by looking at the port number.
*/
private String id;
/**
* The depth of blocks required for a coinbase transaction to be spendable.
*/
private int spendableCoinbaseDepth;
/**
* Returns the number of blocks between subsidy decreases
*/
private int subsidyDecreaseBlockCount;
/**
* If we are running in testnet-in-a-box mode, we allow connections to nodes with 0 non-genesis blocks
*/
boolean allowEmptyPeerChains;
/**
* The version codes that prefix addresses which are acceptable on this network. Although Satoshi intended these to
* be used for "versioning", in fact they are today used to discriminate what kind of data is contained in the
* address and to prevent accidentally sending coins across chains which would destroy them.
*/
public int[] acceptableAddressCodes;
/**
* Block checkpoints are a safety mechanism that hard-codes the hashes of blocks at particular heights. Re-orgs
* beyond this point will never be accepted. This field should be accessed using
* {@link NetworkParameters#passesCheckpoint(int, Sha256Hash)} and {@link NetworkParameters#isCheckpoint(int)}.
*/
public Map<Integer, Sha256Hash> checkpoints = new HashMap<Integer, Sha256Hash>();
private static Block createGenesis(NetworkParameters n) {
Block genesisBlock = new Block(n);
Transaction t = new Transaction(n);
try {
// A script containing the difficulty bits and the following message:
//
// "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"
byte[] bytes = Hex.decode
("04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73");
t.addInput(new TransactionInput(n, t, bytes));
ByteArrayOutputStream scriptPubKeyBytes = new ByteArrayOutputStream();
Script.writeBytes(scriptPubKeyBytes, Hex.decode
("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"));
scriptPubKeyBytes.write(Script.OP_CHECKSIG);
t.addOutput(new TransactionOutput(n, t, Utils.toNanoCoins(50, 0), scriptPubKeyBytes.toByteArray()));
} catch (Exception e) {
// Cannot happen.
throw new RuntimeException(e);
}
genesisBlock.addTransaction(t);
return genesisBlock;
}
public static final int TARGET_TIMESPAN = 14 * 24 * 60 * 60; // 2 weeks per difficulty cycle, on average.
public static final int TARGET_SPACING = 10 * 60; // 10 minutes per block.
public static final int INTERVAL = TARGET_TIMESPAN / TARGET_SPACING;
/**
* Blocks with a timestamp after this should enforce BIP 16, aka "Pay to script hash". This BIP changed the
* network rules in a soft-forking manner, that is, blocks that don't follow the rules are accepted but not
* mined upon and thus will be quickly re-orged out as long as the majority are enforcing the rule.
*/
public final int BIP16_ENFORCE_TIME = 1333238400;
/**
* The maximum money to be generated
*/
public final BigInteger MAX_MONEY = new BigInteger("21000000", 10).multiply(COIN);
/** Sets up the given Networkparemets with testnet3 values. */
private static NetworkParameters createTestNet3(NetworkParameters n) {
// Genesis hash is 000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943
n.proofOfWorkLimit = Utils.decodeCompactBits(0x1d00ffffL);
n.packetMagic = 0x0b110907;
n.port = 18333;
n.addressHeader = 111;
n.acceptableAddressCodes = new int[] { 111 };
n.dumpedPrivateKeyHeader = 239;
n.interval = INTERVAL;
n.targetTimespan = TARGET_TIMESPAN;
n.alertSigningKey = SATOSHI_KEY;
n.genesisBlock = createGenesis(n);
n.genesisBlock.setTime(1296688602L);
n.genesisBlock.setDifficultyTarget(0x1d00ffffL);
n.genesisBlock.setNonce(414098458);
n.setSpendableCoinbaseDepth(100);
n.setSubsidyDecreaseBlockCount(210000);
n.id = ID_TESTNET;
String genesisHash = n.genesisBlock.getHashAsString();
checkState(genesisHash.equals("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943"),
genesisHash);
return n;
}
/** Sets up the given NetworkParameters with testnet values. */
private static NetworkParameters createTestNet(NetworkParameters n) {
// Genesis hash is 0000000224b1593e3ff16a0e3b61285bbc393a39f78c8aa48c456142671f7110
n.proofOfWorkLimit = Utils.decodeCompactBits(0x1d0fffffL);
n.packetMagic = 0xfabfb5daL;
n.port = 18333;
n.addressHeader = 111;
n.acceptableAddressCodes = new int[] { 111 };
n.dumpedPrivateKeyHeader = 239;
n.interval = INTERVAL;
n.targetTimespan = TARGET_TIMESPAN;
n.alertSigningKey = SATOSHI_KEY;
n.genesisBlock = createGenesis(n);
n.genesisBlock.setTime(1296688602L);
n.genesisBlock.setDifficultyTarget(0x1d07fff8L);
n.genesisBlock.setNonce(384568319);
n.setSpendableCoinbaseDepth(100);
n.setSubsidyDecreaseBlockCount(210000);
n.id = ID_TESTNET;
n.allowEmptyPeerChains = false;
String genesisHash = n.genesisBlock.getHashAsString();
checkState(genesisHash.equals("00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008"),
genesisHash);
return n;
}
/** The test chain created by Gavin. */
public static NetworkParameters testNet() {
NetworkParameters n = new NetworkParameters();
return createTestNet(n);
}
/** The testnet3 chain created by Gavin, included in Bitcoin 0.7. */
public static NetworkParameters testNet3() {
NetworkParameters n = new NetworkParameters();
return createTestNet3(n);
}
/** The primary BitCoin chain created by Satoshi. */
public static NetworkParameters prodNet() {
NetworkParameters n = new NetworkParameters();
n.proofOfWorkLimit = Utils.decodeCompactBits(0x1d00ffffL);
n.port = 8333;
n.packetMagic = 0xf9beb4d9L;
n.addressHeader = 0;
n.acceptableAddressCodes = new int[] { 0 };
n.dumpedPrivateKeyHeader = 128;
n.interval = INTERVAL;
n.targetTimespan = TARGET_TIMESPAN;
n.alertSigningKey = SATOSHI_KEY;
n.genesisBlock = createGenesis(n);
n.genesisBlock.setDifficultyTarget(0x1d00ffffL);
n.genesisBlock.setTime(1231006505L);
n.genesisBlock.setNonce(2083236893);
n.setSpendableCoinbaseDepth(100);
n.setSubsidyDecreaseBlockCount(210000);
n.id = ID_PRODNET;
n.allowEmptyPeerChains = false;
String genesisHash = n.genesisBlock.getHashAsString();
checkState(genesisHash.equals("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"),
genesisHash);
// This contains (at a minimum) the blocks which are not BIP30 compliant. BIP30 changed how duplicate
// transactions are handled. Duplicated transactions could occur in the case where a coinbase had the same
// extraNonce and the same outputs but appeared at different heights, and greatly complicated re-org handling.
// Having these here simplifies block connection logic considerably.
n.checkpoints.put(new Integer(91722), new Sha256Hash("00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"));
n.checkpoints.put(new Integer(91812), new Sha256Hash("00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"));
n.checkpoints.put(new Integer(91842), new Sha256Hash("00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec"));
n.checkpoints.put(new Integer(91880), new Sha256Hash("00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721"));
n.checkpoints.put(new Integer(200000), new Sha256Hash("000000000000034a7dedef4a161fa058a2d67a173a90155f3a2fe6fc132e0ebf"));
return n;
}
/** Returns a testnet params modified to allow any difficulty target. */
public static NetworkParameters unitTests() {
NetworkParameters n = new NetworkParameters();
n = createTestNet(n);
n.proofOfWorkLimit = new BigInteger("00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16);
n.genesisBlock.setTime(System.currentTimeMillis() / 1000);
n.genesisBlock.setDifficultyTarget(Block.EASIEST_DIFFICULTY_TARGET);
n.genesisBlock.solve();
n.interval = 10;
n.targetTimespan = 200000000; // 6 years. Just a very big number.
n.setSpendableCoinbaseDepth(5);
n.setSubsidyDecreaseBlockCount(100);
n.id = "com.google.bitcoin.unittest";
return n;
}
/**
* A java package style string acting as unique ID for these parameters
*/
public String getId() {
if (id == null) {
// Migrate from old serialized wallets which lack the ID field. This code can eventually be deleted.
if (port == 8333) {
id = ID_PRODNET;
} else if (port == 18333) {
id = ID_TESTNET;
}
}
return id;
}
public boolean equals(Object other) {
if (!(other instanceof NetworkParameters)) return false;
NetworkParameters o = (NetworkParameters) other;
return o.getId().equals(getId());
}
/** Returns the network parameters for the given string ID or NULL if not recognized. */
public static NetworkParameters fromID(String id) {
if (id.equals(ID_PRODNET)) {
return prodNet();
} else if (id.equals(ID_TESTNET)) {
return testNet();
} else {
return null;
}
}
public int getSpendableCoinbaseDepth() {
return spendableCoinbaseDepth;
}
public void setSpendableCoinbaseDepth(int coinbaseDepth) {
this.spendableCoinbaseDepth = coinbaseDepth;
}
/**
* Returns true if the block height is either not a checkpoint, or is a checkpoint and the hash matches.
*/
public boolean passesCheckpoint(int height, Sha256Hash hash) {
Sha256Hash checkpointHash = checkpoints.get(new Integer(height));
if (checkpointHash != null)
return checkpointHash.equals(hash);
return true;
}
/**
* Returns true if the given height has a recorded checkpoint.
* @param height
* @return
*/
public boolean isCheckpoint(int height) {
Sha256Hash checkpointHash = checkpoints.get(new Integer(height));
if (checkpointHash != null)
return true;
return false;
}
public void setSubsidyDecreaseBlockCount(int subsidyDecreaseBlockCount) {
this.subsidyDecreaseBlockCount = subsidyDecreaseBlockCount;
}
public int getSubsidyDecreaseBlockCount() {
return subsidyDecreaseBlockCount;
}
}
|
core/src/main/java/com/google/bitcoin/core/NetworkParameters.java
|
/**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.core;
import org.spongycastle.util.encoders.Hex;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import static com.google.bitcoin.core.Utils.COIN;
import static com.google.common.base.Preconditions.checkState;
// TODO: Refactor this after we stop supporting serialization compatibility to use subclasses and singletons.
/**
* NetworkParameters contains the data needed for working with an instantiation of a Bitcoin chain.<p>
*
* Currently there are only two, the production chain and the test chain. But in future as Bitcoin
* evolves there may be more. You can create your own as long as they don't conflict.
*/
public class NetworkParameters implements Serializable {
private static final long serialVersionUID = 3L;
/**
* The protocol version this library implements.
*/
public static final int PROTOCOL_VERSION = 60001;
/**
* The alert signing key originally owned by Satoshi, and now passed on to Gavin along with a few others.
*/
public static final byte[] SATOSHI_KEY = Hex.decode("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284");
/**
* The string returned by getId() for the main, production network where people trade things.
*/
public static final String ID_PRODNET = "org.bitcoin.production";
/**
* The string returned by getId() for the testnet.
*/
public static final String ID_TESTNET = "org.bitcoin.test";
// TODO: Seed nodes should be here as well.
/**
* Genesis block for this chain.<p>
*
* The first block in every chain is a well known constant shared between all BitCoin implemenetations. For a
* block to be valid, it must be eventually possible to work backwards to the genesis block by following the
* prevBlockHash pointers in the block headers.<p>
*
* The genesis blocks for both test and prod networks contain the timestamp of when they were created,
* and a message in the coinbase transaction. It says, <i>"The Times 03/Jan/2009 Chancellor on brink of second
* bailout for banks"</i>.
*/
public Block genesisBlock;
/** What the easiest allowable proof of work should be. */
public BigInteger proofOfWorkLimit;
/** Default TCP port on which to connect to nodes. */
public int port;
/** The header bytes that identify the start of a packet on this network. */
public long packetMagic;
/**
* First byte of a base58 encoded address. See {@link Address}. This is the same as acceptableAddressCodes[0] and
* is the one used for "normal" addresses. Other types of address may be encountered with version codes found in
* the acceptableAddressCodes array.
*/
public int addressHeader;
/** First byte of a base58 encoded dumped private key. See {@link DumpedPrivateKey}. */
public int dumpedPrivateKeyHeader;
/** How many blocks pass between difficulty adjustment periods. BitCoin standardises this to be 2015. */
public int interval;
/**
* How much time in seconds is supposed to pass between "interval" blocks. If the actual elapsed time is
* significantly different from this value, the network difficulty formula will produce a different value. Both
* test and production Bitcoin networks use 2 weeks (1209600 seconds).
*/
public int targetTimespan;
/**
* The key used to sign {@link AlertMessage}s. You can use {@link ECKey#verify(byte[], byte[], byte[])} to verify
* signatures using it.
*/
public byte[] alertSigningKey;
/**
* See getId(). This may be null for old deserialized wallets. In that case we derive it heuristically
* by looking at the port number.
*/
private String id;
/**
* The depth of blocks required for a coinbase transaction to be spendable.
*/
private int spendableCoinbaseDepth;
/**
* Returns the number of blocks between subsidy decreases
*/
private int subsidyDecreaseBlockCount;
/**
* If we are running in testnet-in-a-box mode, we allow connections to nodes with 0 non-genesis blocks
*/
boolean allowEmptyPeerChains;
/**
* The version codes that prefix addresses which are acceptable on this network. Although Satoshi intended these to
* be used for "versioning", in fact they are today used to discriminate what kind of data is contained in the
* address and to prevent accidentally sending coins across chains which would destroy them.
*/
public int[] acceptableAddressCodes;
/**
* Block checkpoints are a safety mechanism that hard-codes the hashes of blocks at particular heights. Re-orgs
* beyond this point will never be accepted. This field should be accessed using
* {@link NetworkParameters#passesCheckpoint(int, Sha256Hash)} and {@link NetworkParameters#isCheckpoint(int)}.
*/
public Map<Integer, Sha256Hash> checkpoints = new HashMap<Integer, Sha256Hash>();
private static Block createGenesis(NetworkParameters n) {
Block genesisBlock = new Block(n);
Transaction t = new Transaction(n);
try {
// A script containing the difficulty bits and the following message:
//
// "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"
byte[] bytes = Hex.decode
("04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73");
t.addInput(new TransactionInput(n, t, bytes));
ByteArrayOutputStream scriptPubKeyBytes = new ByteArrayOutputStream();
Script.writeBytes(scriptPubKeyBytes, Hex.decode
("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"));
scriptPubKeyBytes.write(Script.OP_CHECKSIG);
t.addOutput(new TransactionOutput(n, t, Utils.toNanoCoins(50, 0), scriptPubKeyBytes.toByteArray()));
} catch (Exception e) {
// Cannot happen.
throw new RuntimeException(e);
}
genesisBlock.addTransaction(t);
return genesisBlock;
}
public static final int TARGET_TIMESPAN = 14 * 24 * 60 * 60; // 2 weeks per difficulty cycle, on average.
public static final int TARGET_SPACING = 10 * 60; // 10 minutes per block.
public static final int INTERVAL = TARGET_TIMESPAN / TARGET_SPACING;
/**
* Blocks with a timestamp after this should enforce BIP 16, aka "Pay to script hash". This BIP changed the
* network rules in a soft-forking manner, that is, blocks that don't follow the rules are accepted but not
* mined upon and thus will be quickly re-orged out as long as the majority are enforcing the rule.
*/
public final int BIP16_ENFORCE_TIME = 1333238400;
/**
* The maximum money to be generated
*/
public final BigInteger MAX_MONEY = new BigInteger("21000000", 10).multiply(COIN);
/** Sets up the given Networkparemets with testnet3 values. */
private static NetworkParameters createTestNet3(NetworkParameters n) {
// Genesis hash is 000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943
n.proofOfWorkLimit = Utils.decodeCompactBits(0x1d00ffffL);
n.packetMagic = 0x0b110907;
n.port = 18333;
n.addressHeader = 111;
n.acceptableAddressCodes = new int[] { 111 };
n.dumpedPrivateKeyHeader = 239;
n.interval = INTERVAL;
n.targetTimespan = TARGET_TIMESPAN;
n.alertSigningKey = SATOSHI_KEY;
n.genesisBlock = createGenesis(n);
n.genesisBlock.setTime(1296688602L);
n.genesisBlock.setDifficultyTarget(0x1d00ffffL);
n.genesisBlock.setNonce(414098458);
n.setSpendableCoinbaseDepth(100);
n.id = ID_TESTNET;
String genesisHash = n.genesisBlock.getHashAsString();
checkState(genesisHash.equals("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943"),
genesisHash);
return n;
}
/** Sets up the given NetworkParameters with testnet values. */
private static NetworkParameters createTestNet(NetworkParameters n) {
// Genesis hash is 0000000224b1593e3ff16a0e3b61285bbc393a39f78c8aa48c456142671f7110
n.proofOfWorkLimit = Utils.decodeCompactBits(0x1d0fffffL);
n.packetMagic = 0xfabfb5daL;
n.port = 18333;
n.addressHeader = 111;
n.acceptableAddressCodes = new int[] { 111 };
n.dumpedPrivateKeyHeader = 239;
n.interval = INTERVAL;
n.targetTimespan = TARGET_TIMESPAN;
n.alertSigningKey = SATOSHI_KEY;
n.genesisBlock = createGenesis(n);
n.genesisBlock.setTime(1296688602L);
n.genesisBlock.setDifficultyTarget(0x1d07fff8L);
n.genesisBlock.setNonce(384568319);
n.setSpendableCoinbaseDepth(100);
n.setSubsidyDecreaseBlockCount(210000);
n.id = ID_TESTNET;
n.allowEmptyPeerChains = false;
String genesisHash = n.genesisBlock.getHashAsString();
checkState(genesisHash.equals("00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008"),
genesisHash);
return n;
}
/** The test chain created by Gavin. */
public static NetworkParameters testNet() {
NetworkParameters n = new NetworkParameters();
return createTestNet(n);
}
/** The testnet3 chain created by Gavin, included in Bitcoin 0.7. */
public static NetworkParameters testNet3() {
NetworkParameters n = new NetworkParameters();
return createTestNet3(n);
}
/** The primary BitCoin chain created by Satoshi. */
public static NetworkParameters prodNet() {
NetworkParameters n = new NetworkParameters();
n.proofOfWorkLimit = Utils.decodeCompactBits(0x1d00ffffL);
n.port = 8333;
n.packetMagic = 0xf9beb4d9L;
n.addressHeader = 0;
n.acceptableAddressCodes = new int[] { 0 };
n.dumpedPrivateKeyHeader = 128;
n.interval = INTERVAL;
n.targetTimespan = TARGET_TIMESPAN;
n.alertSigningKey = SATOSHI_KEY;
n.genesisBlock = createGenesis(n);
n.genesisBlock.setDifficultyTarget(0x1d00ffffL);
n.genesisBlock.setTime(1231006505L);
n.genesisBlock.setNonce(2083236893);
n.setSpendableCoinbaseDepth(100);
n.setSubsidyDecreaseBlockCount(210000);
n.id = ID_PRODNET;
n.allowEmptyPeerChains = false;
String genesisHash = n.genesisBlock.getHashAsString();
checkState(genesisHash.equals("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"),
genesisHash);
// This contains (at a minimum) the blocks which are not BIP30 compliant. BIP30 changed how duplicate
// transactions are handled. Duplicated transactions could occur in the case where a coinbase had the same
// extraNonce and the same outputs but appeared at different heights, and greatly complicated re-org handling.
// Having these here simplifies block connection logic considerably.
n.checkpoints.put(new Integer(91722), new Sha256Hash("00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e"));
n.checkpoints.put(new Integer(91812), new Sha256Hash("00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f"));
n.checkpoints.put(new Integer(91842), new Sha256Hash("00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec"));
n.checkpoints.put(new Integer(91880), new Sha256Hash("00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721"));
n.checkpoints.put(new Integer(200000), new Sha256Hash("000000000000034a7dedef4a161fa058a2d67a173a90155f3a2fe6fc132e0ebf"));
return n;
}
/** Returns a testnet params modified to allow any difficulty target. */
public static NetworkParameters unitTests() {
NetworkParameters n = new NetworkParameters();
n = createTestNet(n);
n.proofOfWorkLimit = new BigInteger("00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16);
n.genesisBlock.setTime(System.currentTimeMillis() / 1000);
n.genesisBlock.setDifficultyTarget(Block.EASIEST_DIFFICULTY_TARGET);
n.genesisBlock.solve();
n.interval = 10;
n.targetTimespan = 200000000; // 6 years. Just a very big number.
n.setSpendableCoinbaseDepth(5);
n.setSubsidyDecreaseBlockCount(100);
n.id = "com.google.bitcoin.unittest";
return n;
}
/**
* A java package style string acting as unique ID for these parameters
*/
public String getId() {
if (id == null) {
// Migrate from old serialized wallets which lack the ID field. This code can eventually be deleted.
if (port == 8333) {
id = ID_PRODNET;
} else if (port == 18333) {
id = ID_TESTNET;
}
}
return id;
}
public boolean equals(Object other) {
if (!(other instanceof NetworkParameters)) return false;
NetworkParameters o = (NetworkParameters) other;
return o.getId().equals(getId());
}
/** Returns the network parameters for the given string ID or NULL if not recognized. */
public static NetworkParameters fromID(String id) {
if (id.equals(ID_PRODNET)) {
return prodNet();
} else if (id.equals(ID_TESTNET)) {
return testNet();
} else {
return null;
}
}
public int getSpendableCoinbaseDepth() {
return spendableCoinbaseDepth;
}
public void setSpendableCoinbaseDepth(int coinbaseDepth) {
this.spendableCoinbaseDepth = coinbaseDepth;
}
/**
* Returns true if the block height is either not a checkpoint, or is a checkpoint and the hash matches.
*/
public boolean passesCheckpoint(int height, Sha256Hash hash) {
Sha256Hash checkpointHash = checkpoints.get(new Integer(height));
if (checkpointHash != null)
return checkpointHash.equals(hash);
return true;
}
/**
* Returns true if the given height has a recorded checkpoint.
* @param height
* @return
*/
public boolean isCheckpoint(int height) {
Sha256Hash checkpointHash = checkpoints.get(new Integer(height));
if (checkpointHash != null)
return true;
return false;
}
public void setSubsidyDecreaseBlockCount(int subsidyDecreaseBlockCount) {
this.subsidyDecreaseBlockCount = subsidyDecreaseBlockCount;
}
public int getSubsidyDecreaseBlockCount() {
return subsidyDecreaseBlockCount;
}
}
|
Fix testnet3 NetworkParameters SubsidyDecreaseBlockCount
|
core/src/main/java/com/google/bitcoin/core/NetworkParameters.java
|
Fix testnet3 NetworkParameters SubsidyDecreaseBlockCount
|
|
Java
|
apache-2.0
|
d55e50d9930fa1dfb40da99510d29387130e0d79
| 0
|
emptyflash/hbc,atomicjets/hbc,twitter/hbc,sakshamgangwar/hbc,saifrahmed/hbc,SoftwareWarlock/hbc
|
/**
* Copyright 2013 Twitter, 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.twitter.hbc.twitter4j;
import com.twitter.hbc.core.Client;
import com.twitter.hbc.core.Client;
public interface Twitter4jClient extends Client {
public void process();
}
|
hbc-twitter4j/src/main/java/com/twitter/hbc/twitter4j/Twitter4jClient.java
|
/**
* Copyright 2013 Twitter, 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.twitter.hbc.twitter4j;
import com.twitter.hbc.core.Client;
import com.twitter.hbc.core.Client;
interface Twitter4jClient extends Client {
public void process();
}
|
Update Twitter4JClient interface to be public
See #135 for context
|
hbc-twitter4j/src/main/java/com/twitter/hbc/twitter4j/Twitter4jClient.java
|
Update Twitter4JClient interface to be public
|
|
Java
|
apache-2.0
|
4c5c930ac6efca878e1ee7fb8700cb049c831956
| 0
|
ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma
|
/*
* The Gemma project
*
* Copyright (c) 2005 Columbia University
*
* 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 edu.columbia.gemma.expression.arrayDesign;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ResourceBundle;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import edu.columbia.gemma.BaseServiceTestCase;
import edu.columbia.gemma.common.auditAndSecurity.Contact;
import edu.columbia.gemma.expression.designElement.CompositeSequence;
import edu.columbia.gemma.expression.designElement.CompositeSequenceService;
import edu.columbia.gemma.expression.designElement.DesignElement;
import edu.columbia.gemma.security.ui.ManualAuthenticationProcessing;
/**
* Use this to test the acegi functionality. Namely, this is a good test to illustrate how getting This test class
* represents an integration style test.
* <hr>
* <p>
* Copyright (c) 2004 Columbia University
*
* @author pavlidis
* @author keshav
* @version $Id$
*/
public class ArrayDesignServiceImplIntegrationTest extends BaseServiceTestCase {
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test removing an arrayDesign without having the correct authorization privileges. You should get an
* unsuccessfulAuthentication. Does not use mock objects because I need the data from the database. This test does
* not use SpringContextUtil because I wanted to test the acegi implementation and SpringContextUtil grants
* authorization for all users.
*
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void testRemoveArrayDesignWithoutAuthorizationWithoutMock() throws Exception {
ResourceBundle db = ResourceBundle.getBundle( "Gemma" );
String daoType = db.getString( "dao.type" );
String servletContext = db.getString( "servlet.name.0" );
String[] paths = { "applicationContext-localDataSource.xml", "applicationContext-" + daoType + ".xml",
"applicationContext-security.xml", servletContext + "-servlet.xml", "applicationContext-validation.xml" };
BeanFactory cpCtx = new ClassPathXmlApplicationContext( paths );
/* Manual Authentication */
ManualAuthenticationProcessing manAuthentication = ( ManualAuthenticationProcessing ) cpCtx
.getBean( "manualAuthenticationProcessing" );
manAuthentication.validateRequest( "keshav", "pavlab" );
ArrayDesignService ads = ( ArrayDesignService ) ctx.getBean( "arrayDesignService" );
Collection<ArrayDesign> col = ads.getAllArrayDesigns();
if ( col.size() == 0 )
log.info( "There are no arrayDesigns in database" );
else {
Iterator iter = col.iterator();
ArrayDesign ad = ( ArrayDesign ) iter.next();
ads.remove( ad );
}
assertNull( null, null );
}
/**
* Test removing an arrayDesign with correct authorization. The security interceptor should be called on this
* method, as should the AddOrRemoveFromACLInterceptor. Does not use mock objects because I need to remove an
* element from a live database. This test does not use SpringContextUtil because I wanted to test the acegi
* implementation and SpringContextUtil grants authorization for all users.
*
* @throws Exception
*/
public void testRemoveArrayDesignWithoutMock() throws Exception {
/*
* Use this or your ManualAuthenticationProcessing solution. The authentication from a non-http client here
* comes from Fish du jour - See SpringContextUtil BeanFactory ctx = SpringContextUtil.getApplicationContext(
* false );
*/
ResourceBundle db = ResourceBundle.getBundle( "Gemma" );
String daoType = db.getString( "dao.type" );
String servletContext = db.getString( "servlet.name.0" );
String[] paths = { "applicationContext-localDataSource.xml", "applicationContext-" + daoType + ".xml",
"applicationContext-security.xml", servletContext + "-servlet.xml", "applicationContext-validation.xml" };
BeanFactory cpCtx = new ClassPathXmlApplicationContext( paths );
/* Manual Authentication */
ManualAuthenticationProcessing manAuthentication = ( ManualAuthenticationProcessing ) cpCtx
.getBean( "manualAuthenticationProcessing" );
manAuthentication.validateRequest( "keshav", "pavlab" );
/* get bean and invoke methods. */
ArrayDesignService ads = ( ArrayDesignService ) cpCtx.getBean( "arrayDesignService" );
ArrayDesign ad = ads.findArrayDesignByName( "AD Foo" );
if ( ad == null )
log.info( "ArrayDesign does not exist" );
else {
ads.remove( ad );
}
}
/**
* Save an array design
*
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void testSaveArrayDesignWithoutMock() {
ResourceBundle db = ResourceBundle.getBundle( "Gemma" );
String daoType = db.getString( "dao.type" );
String servletContext = db.getString( "servlet.name.0" );
String[] paths = { "applicationContext-localDataSource.xml", "applicationContext-" + daoType + ".xml",
"applicationContext-security.xml", servletContext + "-servlet.xml", "applicationContext-validation.xml" };
BeanFactory cpCtx = new ClassPathXmlApplicationContext( paths );
/* Manual Authentication */
ManualAuthenticationProcessing manAuthentication = ( ManualAuthenticationProcessing ) cpCtx
.getBean( "manualAuthenticationProcessing" );
manAuthentication.validateRequest( "keshav", "pavlab" );
ArrayDesignService ads = ( ArrayDesignService ) ctx.getBean( "arrayDesignService" );
ArrayDesign arrayDesign = ArrayDesign.Factory.newInstance();
arrayDesign.setName( "AD Foo" );
arrayDesign.setDescription( "a test ArrayDesign" );
Contact c = Contact.Factory.newInstance();
c.setName( "\' Design Provider Name\'" );
arrayDesign.setDesignProvider( c );
CompositeSequence cs1 = CompositeSequence.Factory.newInstance();
cs1.setName( "DE Bar1" );
CompositeSequence cs2 = CompositeSequence.Factory.newInstance();
cs2.setName( "DE Bar2" );
Collection<DesignElement> col = new HashSet();
col.add( cs1 );
col.add( cs2 );
/*
* Note this sequence. Remember, inverse="true" if using this. If you do not make an explicit call to
* cs1(2).setArrayDesign(arrayDesign), then inverse="false" must be set.
*/
cs1.setArrayDesign( arrayDesign );
cs2.setArrayDesign( arrayDesign );
arrayDesign.setDesignElements( col );
ads.findOrCreate( arrayDesign );
}
/**
* Tests getting all design elements given authorization on an array design (ie. tests getting the 'owned objects'
* given the authorization on the owner). This test was used to test the Acegi Security functionality. Mock objects
* not used because I need the objects from the database.
*
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void testGetAllDesignElementsFromArrayDesignsWithoutMock() {
ResourceBundle db = ResourceBundle.getBundle( "Gemma" );
String daoType = db.getString( "dao.type" );
String servletContext = db.getString( "servlet.name.0" );
String[] paths = { "applicationContext-localDataSource.xml", "applicationContext-" + daoType + ".xml",
"applicationContext-security.xml", servletContext + "-servlet.xml", "applicationContext-validation.xml" };
BeanFactory cpCtx = new ClassPathXmlApplicationContext( paths );
/* Manual Authentication */
ManualAuthenticationProcessing manAuthentication = ( ManualAuthenticationProcessing ) cpCtx
.getBean( "manualAuthenticationProcessing" );
manAuthentication.validateRequest( "keshav", "pavlab" );
CompositeSequenceService css = ( CompositeSequenceService ) ctx.getBean( "compositeSequenceService" );
Collection<CompositeSequence> col = css.getAllCompositeSequences();
for ( CompositeSequence cs : col ) {
log.debug( cs );
}
if ( col.size() == 0 ) fail( "User not authorized for to access at least one of the objects in the graph" );
}
}
|
test/edu/columbia/gemma/expression/arrayDesign/ArrayDesignServiceImplIntegrationTest.java
|
/*
* The Gemma project
*
* Copyright (c) 2005 Columbia University
*
* 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 edu.columbia.gemma.expression.arrayDesign;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ResourceBundle;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import edu.columbia.gemma.BaseServiceTestCase;
import edu.columbia.gemma.common.auditAndSecurity.Contact;
import edu.columbia.gemma.expression.designElement.CompositeSequence;
import edu.columbia.gemma.expression.designElement.CompositeSequenceService;
import edu.columbia.gemma.expression.designElement.DesignElement;
import edu.columbia.gemma.security.ui.ManualAuthenticationProcessing;
/**
* Use this to test the acegi functionality. Namely, this is a good test to illustrate how getting This test class
* represents an integration style test.
* <hr>
* <p>
* Copyright (c) 2004 Columbia University
*
* @author pavlidis
* @author keshav
* @version $Id$
*/
public class ArrayDesignServiceImplIntegrationTest extends BaseServiceTestCase {
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test removing an arrayDesign without having the correct authorization privileges. You should get an
* unsuccessfulAuthentication. Does not use mock objects because I need the data from the database. This test does
* not use SpringContextUtil because I wanted to test the acegi implementation and SpringContextUtil grants
* authorization for all users.
*
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void testRemoveArrayDesignWithoutAuthorizationWithoutMock() throws Exception {
ResourceBundle db = ResourceBundle.getBundle( "Gemma" );
String daoType = db.getString( "dao.type" );
String servletContext = db.getString( "servlet.name.0" );
String[] paths = { "applicationContext-localDataSource.xml", "applicationContext-" + daoType + ".xml",
"applicationContext-security.xml", servletContext + "-servlet.xml", "applicationContext-validation.xml" };
BeanFactory cpCtx = new ClassPathXmlApplicationContext( paths );
/* Manual Authentication */
ManualAuthenticationProcessing manAuthentication = ( ManualAuthenticationProcessing ) cpCtx
.getBean( "manualAuthenticationProcessing" );
manAuthentication.validateRequest( "keshav", "pavlab" );
ArrayDesignService ads = ( ArrayDesignService ) ctx.getBean( "arrayDesignService" );
Collection<ArrayDesign> col = ads.getAllArrayDesigns();
if ( col.size() == 0 )
log.info( "There are no arrayDesigns in database" );
else {
Iterator iter = col.iterator();
ArrayDesign ad = ( ArrayDesign ) iter.next();
ads.remove( ad );
}
assertNull( null, null );
}
/**
* Test removing an arrayDesign with correct authorization. The security interceptor should be called on this
* method, as should the AddOrRemoveFromACLInterceptor. Does not use mock objects because I need to remove an
* element from a live database. This test does not use SpringContextUtil because I wanted to test the acegi
* implementation and SpringContextUtil grants authorization for all users.
*
* @throws Exception
*/
public void testRemoveArrayDesignWithoutMock() throws Exception {
/*
* Use this or your ManualAuthenticationProcessing solution. The authentication from a non-http client here
* comes from Fish du jour - See SpringContextUtil BeanFactory ctx = SpringContextUtil.getApplicationContext(
* false );
*/
ResourceBundle db = ResourceBundle.getBundle( "Gemma" );
String daoType = db.getString( "dao.type" );
String servletContext = db.getString( "servlet.name.0" );
String[] paths = { "applicationContext-localDataSource.xml", "applicationContext-" + daoType + ".xml",
"applicationContext-security.xml", servletContext + "-servlet.xml", "applicationContext-validation.xml" };
BeanFactory cpCtx = new ClassPathXmlApplicationContext( paths );
/* Manual Authentication */
ManualAuthenticationProcessing manAuthentication = ( ManualAuthenticationProcessing ) cpCtx
.getBean( "manualAuthenticationProcessing" );
manAuthentication.validateRequest( "keshav", "pavlab" );
/* get bean and invoke methods. */
ArrayDesignService ads = ( ArrayDesignService ) cpCtx.getBean( "arrayDesignService" );
ArrayDesign ad = ads.findArrayDesignByName( "AD Foo" );
if ( ad == null )
log.info( "ArrayDesign does not exist" );
else {
ads.remove( ad );
}
}
/**
* Save an array design
*
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void testSaveArrayDesignWithoutMock() {
ResourceBundle db = ResourceBundle.getBundle( "Gemma" );
String daoType = db.getString( "dao.type" );
String servletContext = db.getString( "servlet.name.0" );
String[] paths = { "applicationContext-localDataSource.xml", "applicationContext-" + daoType + ".xml",
"applicationContext-security.xml", servletContext + "-servlet.xml", "applicationContext-validation.xml" };
BeanFactory cpCtx = new ClassPathXmlApplicationContext( paths );
/* Manual Authentication */
ManualAuthenticationProcessing manAuthentication = ( ManualAuthenticationProcessing ) cpCtx
.getBean( "manualAuthenticationProcessing" );
manAuthentication.validateRequest( "keshav", "pavlab" );
ArrayDesignService ads = ( ArrayDesignService ) ctx.getBean( "arrayDesignService" );
ArrayDesign arrayDesign = ArrayDesign.Factory.newInstance();
arrayDesign.setName( "AD Foo" );
arrayDesign.setDescription( "a test ArrayDesign" );
Contact c = Contact.Factory.newInstance();
c.setName( "\' Design Provder Name\'" );
arrayDesign.setDesignProvider( c );
CompositeSequence cs1 = CompositeSequence.Factory.newInstance();
cs1.setName( "DE Bar1" );
CompositeSequence cs2 = CompositeSequence.Factory.newInstance();
cs2.setName( "DE Bar2" );
Collection<DesignElement> col = new HashSet();
col.add( cs1 );
col.add( cs2 );
/*
* Note this sequence. Remember, inverse="true" if using this. If you do not make an explicit call to
* cs1(2).setArrayDesign(arrayDesign), then inverse="false" must be set.
*/
cs1.setArrayDesign( arrayDesign );
cs2.setArrayDesign( arrayDesign );
arrayDesign.setDesignElements( col );
ads.findOrCreate( arrayDesign );
}
/**
* Tests getting all design elements given authorization on an array design (ie. tests getting the 'owned objects'
* given the authorization on the owner). This test was used to test the Acegi Security functionality. Mock objects
* not used because I need the objects from the database.
*
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void testGetAllDesignElementsFromArrayDesignsWithoutMock() {
ResourceBundle db = ResourceBundle.getBundle( "Gemma" );
String daoType = db.getString( "dao.type" );
String servletContext = db.getString( "servlet.name.0" );
String[] paths = { "applicationContext-localDataSource.xml", "applicationContext-" + daoType + ".xml",
"applicationContext-security.xml", servletContext + "-servlet.xml", "applicationContext-validation.xml" };
BeanFactory cpCtx = new ClassPathXmlApplicationContext( paths );
/* Manual Authentication */
ManualAuthenticationProcessing manAuthentication = ( ManualAuthenticationProcessing ) cpCtx
.getBean( "manualAuthenticationProcessing" );
manAuthentication.validateRequest( "keshav", "pavlab" );
CompositeSequenceService css = ( CompositeSequenceService ) ctx.getBean( "compositeSequenceService" );
Collection<CompositeSequence> col = css.getAllCompositeSequences();
for ( CompositeSequence cs : col ) {
log.debug( cs );
}
if ( col.size() == 0 ) fail( "User not authorized for to access at least one of the objects in the graph" );
}
}
|
*** empty log message ***
|
test/edu/columbia/gemma/expression/arrayDesign/ArrayDesignServiceImplIntegrationTest.java
|
*** empty log message ***
|
|
Java
|
apache-2.0
|
b8986ed0c5fcc5a2297d35cc19142f547cc71df6
| 0
|
amberarrow/incubator-apex-core,devtagare/incubator-apex-core,simplifi-it/otterx,chinmaykolhatkar/incubator-apex-core,vrozov/apex-core,vrozov/apex-core,deepak-narkhede/apex-core,klynchDS/incubator-apex-core,sandeshh/apex-core,PramodSSImmaneni/incubator-apex-core,mattqzhang/apex-core,mt0803/incubator-apex-core,sandeshh/incubator-apex-core,vrozov/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,simplifi-it/otterx,MalharJenkins/incubator-apex-core,deepak-narkhede/apex-core,tushargosavi/incubator-apex-core,ishark/incubator-apex-core,tushargosavi/apex-core,tushargosavi/incubator-apex-core,mattqzhang/apex-core,simplifi-it/otterx,brightchen/apex-core,apache/incubator-apex-core,devtagare/incubator-apex-core,aniruddhas/incubator-apex-core,sandeshh/incubator-apex-core,apache/incubator-apex-core,vrozov/incubator-apex-core,tweise/incubator-apex-core,brightchen/apex-core,brightchen/incubator-apex-core,brightchen/incubator-apex-core,PramodSSImmaneni/incubator-apex-core,devtagare/incubator-apex-core,tushargosavi/apex-core,sandeshh/incubator-apex-core,PramodSSImmaneni/apex-core,ishark/incubator-apex-core,apache/incubator-apex-core,aniruddhas/incubator-apex-core,tweise/apex-core,vrozov/incubator-apex-core,MalharJenkins/incubator-apex-core,andyperlitch/incubator-apex-core,mattqzhang/apex-core,PramodSSImmaneni/apex-core,ishark/incubator-apex-core,PramodSSImmaneni/incubator-apex-core,tweise/apex-core,brightchen/apex-core,mt0803/incubator-apex-core,tushargosavi/incubator-apex-core,PramodSSImmaneni/apex-core,klynchDS/incubator-apex-core,sandeshh/apex-core,tweise/incubator-apex-core,amberarrow/incubator-apex-core,sandeshh/apex-core,vrozov/apex-core,tushargosavi/apex-core,deepak-narkhede/apex-core,tweise/apex-core,tweise/incubator-apex-core,andyperlitch/incubator-apex-core
|
/**
* Copyright (C) 2015 DataTorrent, 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.datatorrent.stram.cli;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.security.PrivilegedExceptionAction;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import javax.validation.constraints.NotNull;
import javax.ws.rs.core.MediaType;
import jline.console.ConsoleReader;
import jline.console.completer.*;
import jline.console.history.FileHistory;
import jline.console.history.History;
import jline.console.history.MemoryHistory;
import org.apache.commons.cli.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.YarnApplicationState;
import org.apache.hadoop.yarn.client.api.YarnClient;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.tools.ant.DirectoryScanner;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Signal;
import sun.misc.SignalHandler;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
import com.sun.jersey.api.client.WebResource;
import com.datatorrent.api.Context;
import com.datatorrent.api.Operator;
import com.datatorrent.api.StreamingApplication;
import com.datatorrent.stram.StramClient;
import com.datatorrent.stram.client.*;
import com.datatorrent.stram.client.AppPackage.AppInfo;
import com.datatorrent.stram.client.DTConfiguration.Scope;
import com.datatorrent.stram.client.RecordingsAgent.RecordingInfo;
import com.datatorrent.stram.client.StramAppLauncher.AppFactory;
import com.datatorrent.stram.client.StramClientUtils.ClientRMHelper;
import com.datatorrent.stram.codec.LogicalPlanSerializer;
import com.datatorrent.stram.plan.logical.LogicalPlan;
import com.datatorrent.stram.plan.logical.requests.*;
import com.datatorrent.stram.security.StramUserLogin;
import com.datatorrent.stram.util.JSONSerializationProvider;
import com.datatorrent.stram.util.ObjectMapperFactory;
import com.datatorrent.stram.util.VersionInfo;
import com.datatorrent.stram.util.WebServicesClient;
import com.datatorrent.stram.webapp.OperatorDiscoverer;
import com.datatorrent.stram.webapp.StramWebServices;
import com.datatorrent.stram.webapp.TypeDiscoverer;
import net.lingala.zip4j.exception.ZipException;
/**
* Provides command line interface for a streaming application on hadoop (yarn)
* <p>
*
* @since 0.3.2
*/
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public class DTCli
{
private static final Logger LOG = LoggerFactory.getLogger(DTCli.class);
private Configuration conf;
private FileSystem fs;
private StramAgent stramAgent;
private final YarnClient yarnClient = YarnClient.createYarnClient();
private ApplicationReport currentApp = null;
private boolean consolePresent;
private String[] commandsToExecute;
private final Map<String, CommandSpec> globalCommands = new TreeMap<String, CommandSpec>();
private final Map<String, CommandSpec> connectedCommands = new TreeMap<String, CommandSpec>();
private final Map<String, CommandSpec> logicalPlanChangeCommands = new TreeMap<String, CommandSpec>();
private final Map<String, String> aliases = new HashMap<String, String>();
private final Map<String, List<String>> macros = new HashMap<String, List<String>>();
private boolean changingLogicalPlan = false;
private final List<LogicalPlanRequest> logicalPlanRequestQueue = new ArrayList<LogicalPlanRequest>();
private FileHistory topLevelHistory;
private FileHistory changingLogicalPlanHistory;
private String jsonp;
private boolean raw = false;
private RecordingsAgent recordingsAgent;
private final ObjectMapper mapper = new JSONSerializationProvider().getContext(null);
private String pagerCommand;
private Process pagerProcess;
private int verboseLevel = 0;
private final Tokenizer tokenizer = new Tokenizer();
private final Map<String, String> variableMap = new HashMap<String, String>();
private static boolean lastCommandError = false;
private Thread mainThread;
private Thread commandThread;
private String prompt;
private String forcePrompt;
private String kerberosPrincipal;
private String kerberosKeyTab;
private static class FileLineReader extends ConsoleReader
{
private final BufferedReader br;
FileLineReader(String fileName) throws IOException
{
super();
fileName = expandFileName(fileName, true);
br = new BufferedReader(new FileReader(fileName));
}
@Override
public String readLine(String prompt) throws IOException
{
return br.readLine();
}
@Override
public String readLine(String prompt, Character mask) throws IOException
{
return br.readLine();
}
@Override
public String readLine(Character mask) throws IOException
{
return br.readLine();
}
public void close() throws IOException
{
br.close();
}
}
public class Tokenizer
{
private void appendToCommandBuffer(List<String> commandBuffer, StringBuffer buf, boolean potentialEmptyArg)
{
if (potentialEmptyArg || buf.length() > 0) {
commandBuffer.add(buf.toString());
buf.setLength(0);
}
}
private List<String> startNewCommand(LinkedList<List<String>> resultBuffer)
{
List<String> newCommand = new ArrayList<String>();
if (!resultBuffer.isEmpty()) {
List<String> lastCommand = resultBuffer.peekLast();
if (lastCommand.size() == 1) {
String first = lastCommand.get(0);
if (first.matches("^[A-Za-z][A-Za-z0-9]*=.*")) {
// This is a variable assignment
int equalSign = first.indexOf('=');
variableMap.put(first.substring(0, equalSign), first.substring(equalSign + 1));
resultBuffer.removeLast();
}
}
}
resultBuffer.add(newCommand);
return newCommand;
}
public List<String[]> tokenize(String commandLine)
{
LinkedList<List<String>> resultBuffer = new LinkedList<List<String>>();
List<String> commandBuffer = startNewCommand(resultBuffer);
if (commandLine != null) {
commandLine = ltrim(commandLine);
if (commandLine.startsWith("#")) {
return null;
}
int len = commandLine.length();
boolean insideQuotes = false;
boolean potentialEmptyArg = false;
StringBuffer buf = new StringBuffer(commandLine.length());
for (@SuppressWarnings("AssignmentToForLoopParameter") int i = 0; i < len; ++i) {
char c = commandLine.charAt(i);
if (c == '"') {
potentialEmptyArg = true;
insideQuotes = !insideQuotes;
}
else if (c == '\\') {
if (len > i + 1) {
switch (commandLine.charAt(i + 1)) {
case 'n':
buf.append("\n");
break;
case 't':
buf.append("\t");
break;
case 'r':
buf.append("\r");
break;
case 'b':
buf.append("\b");
break;
case 'f':
buf.append("\f");
break;
default:
buf.append(commandLine.charAt(i + 1));
}
++i;
}
}
else {
if (insideQuotes) {
buf.append(c);
}
else {
if (c == '$') {
StringBuilder variableName = new StringBuilder(32);
if (len > i + 1) {
if (commandLine.charAt(i + 1) == '{') {
++i;
while (len > i + 1) {
char ch = commandLine.charAt(i + 1);
if (ch != '}') {
variableName.append(ch);
}
++i;
if (ch == '}') {
break;
}
if (len <= i + 1) {
throw new CliException("Parse error: unmatched brace");
}
}
} else if (commandLine.charAt(i + 1) == '?') {
++i;
buf.append(lastCommandError ? "1" : "0");
continue;
} else {
while (len > i + 1) {
char ch = commandLine.charAt(i + 1);
if ((variableName.length() > 0 && ch >= '0' && ch <= '9') || ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) {
variableName.append(ch);
}
else {
break;
}
++i;
}
}
if (variableName.length() == 0) {
buf.append(c);
}
else {
String value = variableMap.get(variableName.toString());
if (value != null) {
buf.append(value);
}
}
}
else {
buf.append(c);
}
}
else if (c == ';') {
appendToCommandBuffer(commandBuffer, buf, potentialEmptyArg);
commandBuffer = startNewCommand(resultBuffer);
}
else if (Character.isWhitespace(c)) {
appendToCommandBuffer(commandBuffer, buf, potentialEmptyArg);
potentialEmptyArg = false;
if (len > i + 1 && commandLine.charAt(i + 1) == '#') {
break;
}
}
else {
buf.append(c);
}
}
}
}
appendToCommandBuffer(commandBuffer, buf, potentialEmptyArg);
}
startNewCommand(resultBuffer);
List<String[]> result = new ArrayList<String[]>();
for (List<String> command : resultBuffer) {
String[] commandArray = new String[command.size()];
result.add(command.toArray(commandArray));
}
return result;
}
}
private interface Command
{
void execute(String[] args, ConsoleReader reader) throws Exception;
}
private static class Arg
{
final String name;
Arg(String name)
{
this.name = name;
}
@Override
public String toString()
{
return name;
}
}
private static class FileArg extends Arg
{
FileArg(String name)
{
super(name);
}
}
// VarArg must be in optional argument and must be at the end
private static class VarArg extends Arg
{
VarArg(String name)
{
super(name);
}
}
private static class CommandArg extends Arg
{
CommandArg(String name)
{
super(name);
}
}
protected PrintStream suppressOutput()
{
PrintStream originalStream = System.out;
if (raw) {
PrintStream dummyStream = new PrintStream(new OutputStream()
{
@Override
public void write(int b)
{
// no-op
}
});
System.setOut(dummyStream);
}
return originalStream;
}
protected void restoreOutput(PrintStream originalStream)
{
if (raw) {
System.setOut(originalStream);
}
}
AppPackage newAppPackageInstance(File f) throws IOException, ZipException
{
PrintStream outputStream = suppressOutput();
try {
return new AppPackage(f, true);
} finally {
restoreOutput(outputStream);
}
}
@SuppressWarnings("unused")
private StramAppLauncher getStramAppLauncher(String jarfileUri, Configuration config, boolean ignorePom) throws Exception
{
URI uri = new URI(jarfileUri);
String scheme = uri.getScheme();
StramAppLauncher appLauncher = null;
if (scheme == null || scheme.equals("file")) {
File jf = new File(uri.getPath());
appLauncher = new StramAppLauncher(jf, config);
}
else {
FileSystem tmpFs = FileSystem.newInstance(uri, conf);
try {
Path path = new Path(uri.getPath());
appLauncher = new StramAppLauncher(tmpFs, path, config);
}
finally {
tmpFs.close();
}
}
if (appLauncher != null) {
if (verboseLevel > 0) {
System.err.print(appLauncher.getMvnBuildClasspathOutput());
}
return appLauncher;
}
else {
throw new CliException("Scheme " + scheme + " not supported.");
}
}
private static class CommandSpec
{
Command command;
Arg[] requiredArgs;
Arg[] optionalArgs;
String description;
CommandSpec(Command command, Arg[] requiredArgs, Arg[] optionalArgs, String description)
{
this.command = command;
this.requiredArgs = requiredArgs;
this.optionalArgs = optionalArgs;
this.description = description;
}
void verifyArguments(String[] args) throws CliException
{
int minArgs = 0;
int maxArgs = 0;
if (requiredArgs != null) {
minArgs = requiredArgs.length;
maxArgs = requiredArgs.length;
}
if (optionalArgs != null) {
for (Arg arg : optionalArgs) {
if (arg instanceof VarArg) {
maxArgs = Integer.MAX_VALUE;
break;
} else {
maxArgs++;
}
}
}
if (args.length - 1 < minArgs || args.length - 1 > maxArgs) {
throw new CliException("Command parameter error");
}
}
void printUsage(String cmd)
{
System.err.print("Usage: " + cmd);
if (requiredArgs != null) {
for (Arg arg : requiredArgs) {
System.err.print(" <" + arg + ">");
}
}
if (optionalArgs != null) {
for (Arg arg : optionalArgs) {
if (arg instanceof VarArg) {
System.err.print(" [<" + arg + "> ... ]");
} else {
System.err.print(" [<" + arg + ">]");
}
}
}
System.err.println();
}
}
private static class OptionsCommandSpec extends CommandSpec
{
Options options;
OptionsCommandSpec(Command command, Arg[] requiredArgs, Arg[] optionalArgs, String description, Options options)
{
super(command, requiredArgs, optionalArgs, description);
this.options = options;
}
@Override
void verifyArguments(String[] args) throws CliException
{
try {
args = new PosixParser().parse(options, args).getArgs();
super.verifyArguments(args);
}
catch (Exception ex) {
throw new CliException("Command parameter error");
}
}
@Override
void printUsage(String cmd)
{
super.printUsage(cmd + ((options == null) ? "" : " [options]"));
if (options != null) {
System.out.println("Options:");
HelpFormatter formatter = new HelpFormatter();
PrintWriter pw = new PrintWriter(System.out);
formatter.printOptions(pw, 80, options, 4, 4);
pw.flush();
}
}
}
DTCli()
{
//
// Global command specification starts here
//
globalCommands.put("help", new CommandSpec(new HelpCommand(),
null,
new Arg[]{new CommandArg("command")},
"Show help"));
globalCommands.put("echo", new CommandSpec(new EchoCommand(),
null, new Arg[]{new VarArg("arg")},
"Echo the arguments"));
globalCommands.put("connect", new CommandSpec(new ConnectCommand(),
new Arg[]{new Arg("app-id")},
null,
"Connect to an app"));
globalCommands.put("launch", new OptionsCommandSpec(new LaunchCommand(),
new Arg[]{new FileArg("jar-file/json-file/properties-file/app-package-file")},
new Arg[]{new Arg("matching-app-name")},
"Launch an app", LAUNCH_OPTIONS.options));
globalCommands.put("shutdown-app", new CommandSpec(new ShutdownAppCommand(),
new Arg[]{new Arg("app-id")},
new Arg[]{new VarArg("app-id")},
"Shutdown an app"));
globalCommands.put("list-apps", new CommandSpec(new ListAppsCommand(),
null,
new Arg[]{new Arg("pattern")},
"List applications"));
globalCommands.put("kill-app", new CommandSpec(new KillAppCommand(),
new Arg[]{new Arg("app-id")},
new Arg[]{new VarArg("app-id")},
"Kill an app"));
globalCommands.put("show-logical-plan", new OptionsCommandSpec(new ShowLogicalPlanCommand(),
new Arg[]{new FileArg("jar-file/app-package-file")},
new Arg[]{new Arg("class-name")},
"List apps in a jar or show logical plan of an app class",
getShowLogicalPlanCommandLineOptions()));
globalCommands.put("get-jar-operator-classes", new OptionsCommandSpec(new GetJarOperatorClassesCommand(),
new Arg[]{new FileArg("jar-files-comma-separated")},
new Arg[]{new Arg("search-term")},
"List operators in a jar list",
GET_OPERATOR_CLASSES_OPTIONS.options));
globalCommands.put("get-jar-operator-properties", new CommandSpec(new GetJarOperatorPropertiesCommand(),
new Arg[]{new FileArg("jar-files-comma-separated"), new Arg("operator-class-name")},
null,
"List properties in specified operator"));
globalCommands.put("alias", new CommandSpec(new AliasCommand(),
new Arg[]{new Arg("alias-name"), new CommandArg("command")},
null,
"Create a command alias"));
globalCommands.put("source", new CommandSpec(new SourceCommand(),
new Arg[]{new FileArg("file")},
null,
"Execute the commands in a file"));
globalCommands.put("exit", new CommandSpec(new ExitCommand(),
null,
null,
"Exit the CLI"));
globalCommands.put("begin-macro", new CommandSpec(new BeginMacroCommand(),
new Arg[]{new Arg("name")},
null,
"Begin Macro Definition ($1...$9 to access parameters and type 'end' to end the definition)"));
globalCommands.put("dump-properties-file", new CommandSpec(new DumpPropertiesFileCommand(),
new Arg[]{new FileArg("out-file"), new FileArg("jar-file"), new Arg("class-name")},
null,
"Dump the properties file of an app class"));
globalCommands.put("get-app-info", new CommandSpec(new GetAppInfoCommand(),
new Arg[]{new Arg("app-id")},
null,
"Get the information of an app"));
globalCommands.put("set-pager", new CommandSpec(new SetPagerCommand(),
new Arg[]{new Arg("on/off")},
null,
"Set the pager program for output"));
globalCommands.put("get-config-parameter", new CommandSpec(new GetConfigParameterCommand(),
null,
new Arg[]{new FileArg("parameter-name")},
"Get the configuration parameter"));
globalCommands.put("get-app-package-info", new CommandSpec(new GetAppPackageInfoCommand(),
new Arg[]{new FileArg("app-package-file")},
null,
"Get info on the app package file"));
globalCommands.put("get-app-package-operators", new OptionsCommandSpec(new GetAppPackageOperatorsCommand(),
new Arg[]{new FileArg("app-package-file")},
new Arg[]{new Arg("search-term")},
"Get operators within the given app package",
GET_OPERATOR_CLASSES_OPTIONS.options));
globalCommands.put("get-app-package-operator-properties", new CommandSpec(new GetAppPackageOperatorPropertiesCommand(),
new Arg[]{new FileArg("app-package-file"), new Arg("operator-class")},
null,
"Get operator properties within the given app package"));
globalCommands.put("list-application-attributes", new CommandSpec(new ListAttributesCommand(AttributesType.APPLICATION),
null, null, "Lists the application attributes"));
globalCommands.put("list-operator-attributes", new CommandSpec(new ListAttributesCommand(AttributesType.OPERATOR),
null, null, "Lists the operator attributes"));
globalCommands.put("list-port-attributes", new CommandSpec(new ListAttributesCommand(AttributesType.PORT), null, null,
"Lists the port attributes"));
//
// Connected command specification starts here
//
connectedCommands.put("list-containers", new CommandSpec(new ListContainersCommand(),
null,
null,
"List containers"));
connectedCommands.put("list-operators", new CommandSpec(new ListOperatorsCommand(),
null,
new Arg[]{new Arg("pattern")},
"List operators"));
connectedCommands.put("show-physical-plan", new CommandSpec(new ShowPhysicalPlanCommand(),
null,
null,
"Show physical plan"));
connectedCommands.put("kill-container", new CommandSpec(new KillContainerCommand(),
new Arg[]{new Arg("container-id")},
new Arg[]{new VarArg("container-id")},
"Kill a container"));
connectedCommands.put("shutdown-app", new CommandSpec(new ShutdownAppCommand(),
null,
new Arg[]{new VarArg("app-id")},
"Shutdown an app"));
connectedCommands.put("kill-app", new CommandSpec(new KillAppCommand(),
null,
new Arg[]{new VarArg("app-id")},
"Kill an app"));
connectedCommands.put("wait", new CommandSpec(new WaitCommand(),
new Arg[]{new Arg("timeout")},
null,
"Wait for completion of current application"));
connectedCommands.put("start-recording", new CommandSpec(new StartRecordingCommand(),
new Arg[]{new Arg("operator-id")},
new Arg[]{new Arg("port-name"), new Arg("num-windows")},
"Start recording"));
connectedCommands.put("stop-recording", new CommandSpec(new StopRecordingCommand(),
new Arg[]{new Arg("operator-id")},
new Arg[]{new Arg("port-name")},
"Stop recording"));
connectedCommands.put("get-operator-attributes", new CommandSpec(new GetOperatorAttributesCommand(),
new Arg[]{new Arg("operator-name")},
new Arg[]{new Arg("attribute-name")},
"Get attributes of an operator"));
connectedCommands.put("get-operator-properties", new CommandSpec(new GetOperatorPropertiesCommand(),
new Arg[]{new Arg("operator-name")},
new Arg[]{new Arg("property-name")},
"Get properties of a logical operator"));
connectedCommands.put("get-physical-operator-properties", new OptionsCommandSpec(new GetPhysicalOperatorPropertiesCommand(),
new Arg[]{new Arg("operator-id")},
null,
"Get properties of a physical operator", GET_PHYSICAL_PROPERTY_OPTIONS.options));
connectedCommands.put("set-operator-property", new CommandSpec(new SetOperatorPropertyCommand(),
new Arg[]{new Arg("operator-name"), new Arg("property-name"), new Arg("property-value")},
null,
"Set a property of an operator"));
connectedCommands.put("set-physical-operator-property", new CommandSpec(new SetPhysicalOperatorPropertyCommand(),
new Arg[]{new Arg("operator-id"), new Arg("property-name"), new Arg("property-value")},
null,
"Set a property of an operator"));
connectedCommands.put("get-app-attributes", new CommandSpec(new GetAppAttributesCommand(),
null,
new Arg[]{new Arg("attribute-name")},
"Get attributes of the connected app"));
connectedCommands.put("get-port-attributes", new CommandSpec(new GetPortAttributesCommand(),
new Arg[]{new Arg("operator-name"), new Arg("port-name")},
new Arg[]{new Arg("attribute-name")},
"Get attributes of a port"));
connectedCommands.put("begin-logical-plan-change", new CommandSpec(new BeginLogicalPlanChangeCommand(),
null,
null,
"Begin Logical Plan Change"));
connectedCommands.put("show-logical-plan", new OptionsCommandSpec(new ShowLogicalPlanCommand(),
null,
new Arg[]{new FileArg("jar-file/app-package-file"), new Arg("class-name")},
"Show logical plan of an app class",
getShowLogicalPlanCommandLineOptions()));
connectedCommands.put("dump-properties-file", new CommandSpec(new DumpPropertiesFileCommand(),
new Arg[]{new FileArg("out-file")},
new Arg[]{new FileArg("jar-file"), new Arg("class-name")},
"Dump the properties file of an app class"));
connectedCommands.put("get-app-info", new CommandSpec(new GetAppInfoCommand(),
null,
new Arg[]{new Arg("app-id")},
"Get the information of an app"));
connectedCommands.put("get-recording-info", new CommandSpec(new GetRecordingInfoCommand(),
null,
new Arg[]{new Arg("operator-id"), new Arg("start-time")},
"Get tuple recording info"));
//
// Logical plan change command specification starts here
//
logicalPlanChangeCommands.put("help", new CommandSpec(new HelpCommand(),
null,
new Arg[]{new Arg("command")},
"Show help"));
logicalPlanChangeCommands.put("create-operator", new CommandSpec(new CreateOperatorCommand(),
new Arg[]{new Arg("operator-name"), new Arg("class-name")},
null,
"Create an operator"));
logicalPlanChangeCommands.put("create-stream", new CommandSpec(new CreateStreamCommand(),
new Arg[]{new Arg("stream-name"), new Arg("from-operator-name"), new Arg("from-port-name"), new Arg("to-operator-name"), new Arg("to-port-name")},
null,
"Create a stream"));
logicalPlanChangeCommands.put("add-stream-sink", new CommandSpec(new AddStreamSinkCommand(),
new Arg[]{new Arg("stream-name"), new Arg("to-operator-name"), new Arg("to-port-name")},
null,
"Add a sink to an existing stream"));
logicalPlanChangeCommands.put("remove-operator", new CommandSpec(new RemoveOperatorCommand(),
new Arg[]{new Arg("operator-name")},
null,
"Remove an operator"));
logicalPlanChangeCommands.put("remove-stream", new CommandSpec(new RemoveStreamCommand(),
new Arg[]{new Arg("stream-name")},
null,
"Remove a stream"));
logicalPlanChangeCommands.put("set-operator-property", new CommandSpec(new SetOperatorPropertyCommand(),
new Arg[]{new Arg("operator-name"), new Arg("property-name"), new Arg("property-value")},
null,
"Set a property of an operator"));
logicalPlanChangeCommands.put("set-operator-attribute", new CommandSpec(new SetOperatorAttributeCommand(),
new Arg[]{new Arg("operator-name"), new Arg("attr-name"), new Arg("attr-value")},
null,
"Set an attribute of an operator"));
logicalPlanChangeCommands.put("set-port-attribute", new CommandSpec(new SetPortAttributeCommand(),
new Arg[]{new Arg("operator-name"), new Arg("port-name"), new Arg("attr-name"), new Arg("attr-value")},
null,
"Set an attribute of a port"));
logicalPlanChangeCommands.put("set-stream-attribute", new CommandSpec(new SetStreamAttributeCommand(),
new Arg[]{new Arg("stream-name"), new Arg("attr-name"), new Arg("attr-value")},
null,
"Set an attribute of a stream"));
logicalPlanChangeCommands.put("show-queue", new CommandSpec(new ShowQueueCommand(),
null,
null,
"Show the queue of the plan change"));
logicalPlanChangeCommands.put("submit", new CommandSpec(new SubmitCommand(),
null,
null,
"Submit the plan change"));
logicalPlanChangeCommands.put("abort", new CommandSpec(new AbortCommand(),
null,
null,
"Abort the plan change"));
}
private void printJson(String json) throws IOException
{
PrintStream os = getOutputPrintStream();
if (jsonp != null) {
os.println(jsonp + "(" + json + ");");
}
else {
os.println(json);
}
os.flush();
closeOutputPrintStream(os);
}
private void printJson(JSONObject json) throws JSONException, IOException
{
printJson(raw ? json.toString() : json.toString(2));
}
private void printJson(JSONArray jsonArray, String name) throws JSONException, IOException
{
JSONObject json = new JSONObject();
json.put(name, jsonArray);
printJson(json);
}
private <K, V> void printJson(Map<K, V> map) throws IOException, JSONException
{
printJson(new JSONObject(mapper.writeValueAsString(map)));
}
private <T> void printJson(List<T> list, String name) throws IOException, JSONException
{
printJson(new JSONArray(mapper.writeValueAsString(list)), name);
}
private PrintStream getOutputPrintStream() throws IOException
{
if (pagerCommand == null) {
pagerProcess = null;
return System.out;
}
else {
pagerProcess = Runtime.getRuntime().exec(new String[]{"sh", "-c",
pagerCommand + " >/dev/tty"});
return new PrintStream(pagerProcess.getOutputStream());
}
}
private void closeOutputPrintStream(PrintStream os)
{
if (os != System.out) {
os.close();
try {
pagerProcess.waitFor();
}
catch (InterruptedException ex) {
LOG.debug("Interrupted");
}
}
}
private static String expandFileName(String fileName, boolean expandWildCard) throws IOException
{
if (fileName.matches("^[a-zA-Z]+:.*")) {
// it's a URL
return fileName;
}
// TODO: need to work with other users' home directory
if (fileName.startsWith("~" + File.separator)) {
fileName = System.getProperty("user.home") + fileName.substring(1);
}
fileName = new File(fileName).getCanonicalPath();
//LOG.debug("Canonical path: {}", fileName);
if (expandWildCard) {
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{fileName});
scanner.scan();
String[] files = scanner.getIncludedFiles();
if (files.length == 0) {
throw new CliException(fileName + " does not match any file");
}
else if (files.length > 1) {
throw new CliException(fileName + " matches more than one file");
}
return files[0];
}
else {
return fileName;
}
}
private static String[] expandFileNames(String fileName) throws IOException
{
// TODO: need to work with other users
if (fileName.matches("^[a-zA-Z]+:.*")) {
// it's a URL
return new String[]{fileName};
}
if (fileName.startsWith("~" + File.separator)) {
fileName = System.getProperty("user.home") + fileName.substring(1);
}
fileName = new File(fileName).getCanonicalPath();
LOG.debug("Canonical path: {}", fileName);
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{fileName});
scanner.scan();
return scanner.getIncludedFiles();
}
private static String expandCommaSeparatedFiles(String filenames) throws IOException
{
String[] entries = filenames.split(",");
StringBuilder result = new StringBuilder(filenames.length());
for (String entry : entries) {
for (String file : expandFileNames(entry)) {
if (result.length() > 0) {
result.append(",");
}
result.append(file);
}
}
if (result.length() == 0) {
return null;
}
return result.toString();
}
protected ApplicationReport getApplication(String appId)
{
List<ApplicationReport> appList = getApplicationList();
if (StringUtils.isNumeric(appId)) {
int appSeq = Integer.parseInt(appId);
for (ApplicationReport ar : appList) {
if (ar.getApplicationId().getId() == appSeq) {
return ar;
}
}
}
else {
for (ApplicationReport ar : appList) {
if (ar.getApplicationId().toString().equals(appId)) {
return ar;
}
}
}
return null;
}
private static class CliException extends RuntimeException
{
private static final long serialVersionUID = 1L;
CliException(String msg, Throwable cause)
{
super(msg, cause);
}
CliException(String msg)
{
super(msg);
}
}
public void preImpersonationInit(String[] args) throws IOException
{
Signal.handle(new Signal("INT"), new SignalHandler()
{
@Override
public void handle(Signal sig)
{
System.out.println("^C");
if (commandThread != null) {
commandThread.interrupt();
mainThread.interrupt();
}
else {
System.out.print(prompt);
System.out.flush();
}
}
});
consolePresent = (System.console() != null);
Options options = new Options();
options.addOption("e", true, "Commands are read from the argument");
options.addOption("v", false, "Verbose mode level 1");
options.addOption("vv", false, "Verbose mode level 2");
options.addOption("vvv", false, "Verbose mode level 3");
options.addOption("vvvv", false, "Verbose mode level 4");
options.addOption("r", false, "JSON Raw mode");
options.addOption("p", true, "JSONP padding function");
options.addOption("h", false, "Print this help");
options.addOption("f", true, "Use the specified prompt at all time");
options.addOption("kp", true, "Use the specified kerberos principal");
options.addOption("kt", true, "Use the specified kerberos keytab");
CommandLineParser parser = new BasicParser();
try {
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("v")) {
verboseLevel = 1;
}
if (cmd.hasOption("vv")) {
verboseLevel = 2;
}
if (cmd.hasOption("vvv")) {
verboseLevel = 3;
}
if (cmd.hasOption("vvvv")) {
verboseLevel = 4;
}
if (cmd.hasOption("r")) {
raw = true;
}
if (cmd.hasOption("e")) {
commandsToExecute = cmd.getOptionValues("e");
consolePresent = false;
}
if (cmd.hasOption("p")) {
jsonp = cmd.getOptionValue("p");
}
if (cmd.hasOption("f")) {
forcePrompt = cmd.getOptionValue("f");
}
if (cmd.hasOption("h")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(DTCli.class.getSimpleName(), options);
System.exit(0);
}
if (cmd.hasOption("kp")) {
kerberosPrincipal = cmd.getOptionValue("kp");
}
if (cmd.hasOption("kt")) {
kerberosKeyTab = cmd.getOptionValue("kt");
}
}
catch (ParseException ex) {
System.err.println("Invalid argument: " + ex);
System.exit(1);
}
if (kerberosPrincipal == null && kerberosKeyTab != null) {
System.err.println("Kerberos key tab is specified but not the kerberos principal. Please specify it using the -kp option.");
System.exit(1);
}
if (kerberosPrincipal != null && kerberosKeyTab == null) {
System.err.println("Kerberos principal is specified but not the kerberos key tab. Please specify it using the -kt option.");
System.exit(1);
}
Level logLevel;
switch (verboseLevel) {
case 0:
logLevel = Level.OFF;
break;
case 1:
logLevel = Level.ERROR;
break;
case 2:
logLevel = Level.WARN;
break;
case 3:
logLevel = Level.INFO;
break;
default:
logLevel = Level.DEBUG;
break;
}
for (org.apache.log4j.Logger logger : new org.apache.log4j.Logger[]{org.apache.log4j.Logger.getRootLogger(),
org.apache.log4j.Logger.getLogger(DTCli.class)}) {
@SuppressWarnings("unchecked")
Enumeration<Appender> allAppenders = logger.getAllAppenders();
while (allAppenders.hasMoreElements()) {
Appender appender = allAppenders.nextElement();
if (appender instanceof ConsoleAppender) {
((ConsoleAppender) appender).setThreshold(logLevel);
}
}
}
if (commandsToExecute != null) {
for (String command : commandsToExecute) {
LOG.debug("Command to be executed: {}", command);
}
}
if (kerberosPrincipal != null && kerberosKeyTab != null) {
StramUserLogin.authenticate(kerberosPrincipal, kerberosKeyTab);
} else {
Configuration config = new YarnConfiguration();
StramClientUtils.addDTLocalResources(config);
StramUserLogin.attemptAuthentication(config);
}
}
public void init() throws IOException
{
conf = StramClientUtils.addDTSiteResources(new YarnConfiguration());
fs = StramClientUtils.newFileSystemInstance(conf);
stramAgent = new StramAgent(fs, conf);
yarnClient.init(conf);
yarnClient.start();
LOG.debug("Yarn Client initialized and started");
String socks = conf.get(CommonConfigurationKeysPublic.HADOOP_SOCKS_SERVER_KEY);
if (socks != null) {
int colon = socks.indexOf(':');
if (colon > 0) {
LOG.info("Using socks proxy at {}", socks);
System.setProperty("socksProxyHost", socks.substring(0, colon));
System.setProperty("socksProxyPort", socks.substring(colon + 1));
}
}
}
private void processSourceFile(String fileName, ConsoleReader reader) throws FileNotFoundException, IOException
{
fileName = expandFileName(fileName, true);
LOG.debug("Sourcing {}", fileName);
boolean consolePresentSaved = consolePresent;
consolePresent = false;
FileLineReader fr = null;
String line;
try {
fr = new FileLineReader(fileName);
while ((line = fr.readLine("")) != null) {
processLine(line, fr, true);
}
}
finally {
consolePresent = consolePresentSaved;
if (fr != null) {
fr.close();
}
}
}
private final static class MyNullCompleter implements Completer
{
public static final MyNullCompleter INSTANCE = new MyNullCompleter();
@Override
public int complete(final String buffer, final int cursor, final List<CharSequence> candidates)
{
candidates.add("");
return cursor;
}
}
private final static class MyFileNameCompleter extends FileNameCompleter
{
@Override
public int complete(final String buffer, final int cursor, final List<CharSequence> candidates)
{
int result = super.complete(buffer, cursor, candidates);
if (candidates.isEmpty()) {
candidates.add("");
result = cursor;
}
return result;
}
}
private List<Completer> defaultCompleters()
{
Map<String, CommandSpec> commands = new TreeMap<String, CommandSpec>();
commands.putAll(logicalPlanChangeCommands);
commands.putAll(connectedCommands);
commands.putAll(globalCommands);
List<Completer> completers = new LinkedList<Completer>();
for (Map.Entry<String, CommandSpec> entry : commands.entrySet()) {
String command = entry.getKey();
CommandSpec cs = entry.getValue();
List<Completer> argCompleters = new LinkedList<Completer>();
argCompleters.add(new StringsCompleter(command));
Arg[] args = (Arg[]) ArrayUtils.addAll(cs.requiredArgs, cs.optionalArgs);
if (args != null) {
if (cs instanceof OptionsCommandSpec) {
// ugly hack because jline cannot dynamically change completer while user types
if (args[0] instanceof FileArg || args[0] instanceof VarArg) {
for (int i = 0; i < 10; i++) {
argCompleters.add(new MyFileNameCompleter());
}
}
}
else {
for (Arg arg : args) {
if (arg instanceof FileArg || arg instanceof VarArg) {
argCompleters.add(new MyFileNameCompleter());
}
else if (arg instanceof CommandArg) {
argCompleters.add(new StringsCompleter(commands.keySet().toArray(new String[]{})));
}
else {
argCompleters.add(MyNullCompleter.INSTANCE);
}
}
}
}
completers.add(new ArgumentCompleter(argCompleters));
}
List<Completer> argCompleters = new LinkedList<Completer>();
Set<String> set = new TreeSet<String>();
set.addAll(aliases.keySet());
set.addAll(macros.keySet());
argCompleters.add(new StringsCompleter(set.toArray(new String[]{})));
for (int i = 0; i < 10; i++) {
argCompleters.add(new MyFileNameCompleter());
}
completers.add(new ArgumentCompleter(argCompleters));
return completers;
}
private void setupCompleter(ConsoleReader reader)
{
reader.addCompleter(new AggregateCompleter(defaultCompleters()));
}
private void updateCompleter(ConsoleReader reader)
{
List<Completer> completers = new ArrayList<Completer>(reader.getCompleters());
for (Completer c : completers) {
reader.removeCompleter(c);
}
setupCompleter(reader);
}
private void setupHistory(ConsoleReader reader)
{
File historyFile = new File(StramClientUtils.getUserDTDirectory(), "cli_history");
historyFile.getParentFile().mkdirs();
try {
topLevelHistory = new FileHistory(historyFile);
reader.setHistory(topLevelHistory);
historyFile = new File(StramClientUtils.getUserDTDirectory(), "cli_history_clp");
changingLogicalPlanHistory = new FileHistory(historyFile);
}
catch (IOException ex) {
System.err.printf("Unable to open %s for writing.", historyFile);
}
}
private void setupAgents() throws IOException
{
recordingsAgent = new RecordingsAgent(stramAgent);
}
public void run() throws IOException
{
ConsoleReader reader = new ConsoleReader();
reader.setExpandEvents(false);
reader.setBellEnabled(false);
try {
processSourceFile(StramClientUtils.getConfigDir() + "/clirc_system", reader);
}
catch (Exception ex) {
// ignore
}
try {
processSourceFile(StramClientUtils.getUserDTDirectory() + "/clirc", reader);
}
catch (Exception ex) {
// ignore
}
if (consolePresent) {
printWelcomeMessage();
setupCompleter(reader);
setupHistory(reader);
//reader.setHandleUserInterrupt(true);
}
else {
reader.setEchoCharacter((char) 0);
}
setupAgents();
String line;
PrintWriter out = new PrintWriter(System.out);
int i = 0;
while (true) {
if (commandsToExecute != null) {
if (i >= commandsToExecute.length) {
break;
}
line = commandsToExecute[i++];
}
else {
line = readLine(reader);
if (line == null) {
break;
}
}
processLine(line, reader, true);
out.flush();
}
if (topLevelHistory != null) {
try {
topLevelHistory.flush();
} catch (IOException ex) {
LOG.warn("Cannot flush command history", ex);
}
}
if (changingLogicalPlanHistory != null) {
try {
changingLogicalPlanHistory.flush();
} catch (IOException ex) {
LOG.warn("Cannot flush command history", ex);
}
}
if (consolePresent) {
System.out.println("exit");
}
}
private List<String> expandMacro(List<String> lines, String[] args)
{
List<String> expandedLines = new ArrayList<String>();
for (String line : lines) {
int previousIndex = 0;
StringBuilder expandedLine = new StringBuilder(line.length());
while (true) {
// Search for $0..$9 within the each line and replace by corresponding args
int currentIndex = line.indexOf('$', previousIndex);
if (currentIndex > 0 && line.length() > currentIndex + 1) {
int argIndex = line.charAt(currentIndex + 1) - '0';
if (args.length > argIndex && argIndex >= 0) {
// Replace $0 with macro name or $1..$9 with input arguments
expandedLine.append(line.substring(previousIndex, currentIndex)).append(args[argIndex]);
}
else if (argIndex >= 0 && argIndex <= 9) {
// Arguments for $1..$9 were not supplied - replace with empty strings
expandedLine.append(line.substring(previousIndex, currentIndex));
}
else {
// Outside valid arguments range - ignore and do not replace
expandedLine.append(line.substring(previousIndex, currentIndex + 2));
}
currentIndex += 2;
}
else {
expandedLine.append(line.substring(previousIndex));
expandedLines.add(expandedLine.toString());
break;
}
previousIndex = currentIndex;
}
}
return expandedLines;
}
private static String ltrim(String s)
{
int i = 0;
while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
i++;
}
return s.substring(i);
}
private void processLine(String line, final ConsoleReader reader, boolean expandMacroAlias)
{
try {
// clear interrupt flag
Thread.interrupted();
if (reader.isHistoryEnabled()) {
History history = reader.getHistory();
if (history instanceof FileHistory) {
try {
((FileHistory) history).flush();
}
catch (IOException ex) {
// ignore
}
}
}
//LOG.debug("line: \"{}\"", line);
List<String[]> commands = tokenizer.tokenize(line);
if (commands == null) {
return;
}
for (final String[] args : commands) {
if (args.length == 0 || StringUtils.isBlank(args[0])) {
continue;
}
//LOG.debug("Got: {}", mapper.writeValueAsString(args));
if (expandMacroAlias) {
if (macros.containsKey(args[0])) {
List<String> macroItems = expandMacro(macros.get(args[0]), args);
for (String macroItem : macroItems) {
if (consolePresent) {
System.out.println("expanded-macro> " + macroItem);
}
processLine(macroItem, reader, false);
}
continue;
}
if (aliases.containsKey(args[0])) {
processLine(aliases.get(args[0]), reader, false);
continue;
}
}
CommandSpec cs = null;
if (changingLogicalPlan) {
cs = logicalPlanChangeCommands.get(args[0]);
}
else {
if (currentApp != null) {
cs = connectedCommands.get(args[0]);
}
if (cs == null) {
cs = globalCommands.get(args[0]);
}
}
if (cs == null) {
if (connectedCommands.get(args[0]) != null) {
System.err.println("\"" + args[0] + "\" is valid only when connected to an application. Type \"connect <appid>\" to connect to an application.");
lastCommandError = true;
}
else if (logicalPlanChangeCommands.get(args[0]) != null) {
System.err.println("\"" + args[0] + "\" is valid only when changing a logical plan. Type \"begin-logical-plan-change\" to change a logical plan");
lastCommandError = true;
}
else {
System.err.println("Invalid command '" + args[0] + "'. Type \"help\" for list of commands");
lastCommandError = true;
}
}
else {
try {
cs.verifyArguments(args);
}
catch (CliException ex) {
cs.printUsage(args[0]);
throw ex;
}
final Command command = cs.command;
commandThread = new Thread()
{
@Override
public void run()
{
try {
command.execute(args, reader);
lastCommandError = false;
}
catch (Exception e) {
handleException(e);
}
}
};
mainThread = Thread.currentThread();
commandThread.start();
try {
commandThread.join();
}
catch (InterruptedException ex) {
System.err.println("Interrupted");
}
commandThread = null;
}
}
}
catch (Exception e) {
handleException(e);
}
}
private void handleException(Exception e)
{
StringBuilder sb = new StringBuilder();
String msg = e.getMessage();
if (null != msg) {
sb.append(msg);
}
Throwable cause = e.getCause();
if (cause != null && cause.getMessage() != null) {
sb.append(": ");
sb.append(cause.getMessage());
}
sb.append(Arrays.toString(e.getStackTrace()));
System.err.println(sb.toString());
LOG.error("Exception caught: ", e);
lastCommandError = true;
}
private void printWelcomeMessage()
{
System.out.println("DT CLI " + VersionInfo.getVersion() + " " + VersionInfo.getDate() + " " + VersionInfo.getRevision());
if (!StramClientUtils.configComplete(conf)) {
System.err.println("WARNING: Configuration of DataTorrent has not been complete. Please proceed with caution and only in development environment!");
}
}
private void printHelp(String command, CommandSpec commandSpec, PrintStream os)
{
if (consolePresent) {
os.print("\033[0;93m");
os.print(command);
os.print("\033[0m");
}
else {
os.print(command);
}
if (commandSpec instanceof OptionsCommandSpec) {
OptionsCommandSpec ocs = (OptionsCommandSpec) commandSpec;
if (ocs.options != null) {
os.print(" [options]");
}
}
if (commandSpec.requiredArgs != null) {
for (Arg arg : commandSpec.requiredArgs) {
if (consolePresent) {
os.print(" \033[3m" + arg + "\033[0m");
}
else {
os.print(" <" + arg + ">");
}
}
}
if (commandSpec.optionalArgs != null) {
for (Arg arg : commandSpec.optionalArgs) {
if (consolePresent) {
os.print(" [\033[3m" + arg + "\033[0m");
}
else {
os.print(" [<" + arg + ">");
}
if (arg instanceof VarArg) {
os.print(" ...");
}
os.print("]");
}
}
os.println("\n\t" + commandSpec.description);
if (commandSpec instanceof OptionsCommandSpec) {
OptionsCommandSpec ocs = (OptionsCommandSpec) commandSpec;
if (ocs.options != null) {
os.println("\tOptions:");
HelpFormatter formatter = new HelpFormatter();
PrintWriter pw = new PrintWriter(os);
formatter.printOptions(pw, 80, ocs.options, 12, 4);
pw.flush();
}
}
}
private void printHelp(Map<String, CommandSpec> commandSpecs, PrintStream os)
{
for (Map.Entry<String, CommandSpec> entry : commandSpecs.entrySet()) {
printHelp(entry.getKey(), entry.getValue(), os);
}
}
private String readLine(ConsoleReader reader)
throws IOException
{
if (forcePrompt == null) {
prompt = "";
if (consolePresent) {
if (changingLogicalPlan) {
prompt = "logical-plan-change";
}
else {
prompt = "dt";
}
if (currentApp != null) {
prompt += " (";
prompt += currentApp.getApplicationId().toString();
prompt += ") ";
}
prompt += "> ";
}
}
else {
prompt = forcePrompt;
}
String line = reader.readLine(prompt, consolePresent ? null : (char) 0);
if (line == null) {
return null;
}
return ltrim(line);
}
private List<ApplicationReport> getApplicationList()
{
try {
return yarnClient.getApplications(Sets.newHashSet(StramClient.YARN_APPLICATION_TYPE));
}
catch (Exception e) {
throw new CliException("Error getting application list from resource manager", e);
}
}
private String getContainerLongId(String containerId)
{
JSONObject json = getResource(StramWebServices.PATH_PHYSICAL_PLAN_CONTAINERS, currentApp);
int shortId = 0;
if (StringUtils.isNumeric(containerId)) {
shortId = Integer.parseInt(containerId);
}
try {
Object containersObj = json.get("containers");
JSONArray containers;
if (containersObj instanceof JSONArray) {
containers = (JSONArray) containersObj;
}
else {
containers = new JSONArray();
containers.put(containersObj);
}
if (containersObj != null) {
for (int o = containers.length(); o-- > 0; ) {
JSONObject container = containers.getJSONObject(o);
String id = container.getString("id");
if (id.equals(containerId) || (shortId != 0 && (id.endsWith("_" + shortId) || id.endsWith("0" + shortId)))) {
return id;
}
}
}
}
catch (JSONException ex) {
}
return null;
}
private ApplicationReport assertRunningApp(ApplicationReport app)
{
ApplicationReport r;
try {
r = yarnClient.getApplicationReport(app.getApplicationId());
if (r.getYarnApplicationState() != YarnApplicationState.RUNNING) {
String msg = String.format("Application %s not running (status %s)",
r.getApplicationId().getId(), r.getYarnApplicationState());
throw new CliException(msg);
}
}
catch (YarnException rmExc) {
throw new CliException("Unable to determine application status", rmExc);
}
catch (IOException rmExc) {
throw new CliException("Unable to determine application status", rmExc);
}
return r;
}
private JSONObject getResource(String resourcePath, ApplicationReport appReport)
{
return getResource(new StramAgent.StramUriSpec().path(resourcePath), appReport, new WebServicesClient.GetWebServicesHandler<JSONObject>());
}
private JSONObject getResource(StramAgent.StramUriSpec uriSpec, ApplicationReport appReport)
{
return getResource(uriSpec, appReport, new WebServicesClient.GetWebServicesHandler<JSONObject>());
}
private JSONObject getResource(StramAgent.StramUriSpec uriSpec, ApplicationReport appReport, WebServicesClient.WebServicesHandler handler)
{
if (appReport == null) {
throw new CliException("No application selected");
}
if (StringUtils.isEmpty(appReport.getTrackingUrl()) || appReport.getFinalApplicationStatus() != FinalApplicationStatus.UNDEFINED) {
appReport = null;
throw new CliException("Application terminated");
}
WebServicesClient wsClient = new WebServicesClient();
try {
return stramAgent.issueStramWebRequest(wsClient, appReport.getApplicationId().toString(), uriSpec, handler);
} catch (Exception e) {
// check the application status as above may have failed due application termination etc.
if (appReport == currentApp) {
currentApp = assertRunningApp(appReport);
}
throw new CliException("Failed to request web service for appid " + appReport.getApplicationId().toString(), e);
}
}
private List<AppFactory> getMatchingAppFactories(StramAppLauncher submitApp, String matchString, boolean exactMatch)
{
try {
List<AppFactory> cfgList = submitApp.getBundledTopologies();
if (cfgList.isEmpty()) {
return null;
}
else if (matchString == null) {
return cfgList;
}
else {
List<AppFactory> result = new ArrayList<AppFactory>();
if (!exactMatch) {
matchString = matchString.toLowerCase();
}
for (AppFactory ac : cfgList) {
String appName = ac.getName();
String appAlias = submitApp.getLogicalPlanConfiguration().getAppAlias(appName);
if (exactMatch) {
if (matchString.equals(appName) || matchString.equals(appAlias)) {
result.add(ac);
}
}
else if (appName.toLowerCase().contains(matchString) || (appAlias != null && appAlias.toLowerCase().contains(matchString))) {
result.add(ac);
}
}
return result;
}
}
catch (Exception ex) {
LOG.warn("Caught Exception: ", ex);
return null;
}
}
/*
* Below is the implementation of all commands
*/
private class HelpCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
PrintStream os = getOutputPrintStream();
if (args.length < 2) {
os.println("GLOBAL COMMANDS EXCEPT WHEN CHANGING LOGICAL PLAN:\n");
printHelp(globalCommands, os);
os.println();
os.println("COMMANDS WHEN CONNECTED TO AN APP (via connect <appid>) EXCEPT WHEN CHANGING LOGICAL PLAN:\n");
printHelp(connectedCommands, os);
os.println();
os.println("COMMANDS WHEN CHANGING LOGICAL PLAN (via begin-logical-plan-change):\n");
printHelp(logicalPlanChangeCommands, os);
os.println();
}
else {
if (args[1].equals("help")) {
printHelp("help", globalCommands.get("help"), os);
}
else {
boolean valid = false;
CommandSpec cs = globalCommands.get(args[1]);
if (cs != null) {
os.println("This usage is valid except when changing logical plan");
printHelp(args[1], cs, os);
os.println();
valid = true;
}
cs = connectedCommands.get(args[1]);
if (cs != null) {
os.println("This usage is valid when connected to an app except when changing logical plan");
printHelp(args[1], cs, os);
os.println();
valid = true;
}
cs = logicalPlanChangeCommands.get(args[1]);
if (cs != null) {
os.println("This usage is only valid when changing logical plan (via begin-logical-plan-change)");
printHelp(args[1], cs, os);
os.println();
valid = true;
}
if (!valid) {
os.println("Help for \"" + args[1] + "\" does not exist.");
}
}
}
closeOutputPrintStream(os);
}
}
private class EchoCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
for (int i = 1; i < args.length; i++) {
if (i > 1) {
System.out.print(" ");
}
System.out.print(args[i]);
}
System.out.println();
}
}
private class ConnectCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
currentApp = getApplication(args[1]);
if (currentApp == null) {
throw new CliException("Streaming application with id " + args[1] + " is not found.");
}
try {
LOG.debug("Selected {} with tracking url {}", currentApp.getApplicationId(), currentApp.getTrackingUrl());
getResource(StramWebServices.PATH_INFO, currentApp);
if (consolePresent) {
System.out.println("Connected to application " + currentApp.getApplicationId());
}
}
catch (CliException e) {
throw e; // pass on
}
}
}
private class LaunchCommand implements Command
{
@Override
@SuppressWarnings("SleepWhileInLoop")
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, args.length - 1);
LaunchCommandLineInfo commandLineInfo = getLaunchCommandLineInfo(newArgs);
if (commandLineInfo.configFile != null) {
commandLineInfo.configFile = expandFileName(commandLineInfo.configFile, true);
}
// see if the given config file is a config package
ConfigPackage cp = null;
String requiredAppPackageName = null;
try {
cp = new ConfigPackage(new File(commandLineInfo.configFile));
requiredAppPackageName = cp.getAppPackageName();
} catch (Exception ex) {
// fall through, it's not a config package
}
try {
Configuration config;
String configFile = cp == null ? commandLineInfo.configFile : null;
try {
config = StramAppLauncher.getOverriddenConfig(StramClientUtils.addDTSiteResources(new Configuration()), configFile, commandLineInfo.overrideProperties);
if (commandLineInfo.libjars != null) {
commandLineInfo.libjars = expandCommaSeparatedFiles(commandLineInfo.libjars);
if (commandLineInfo.libjars != null) {
config.set(StramAppLauncher.LIBJARS_CONF_KEY_NAME, commandLineInfo.libjars);
}
}
if (commandLineInfo.files != null) {
commandLineInfo.files = expandCommaSeparatedFiles(commandLineInfo.files);
if (commandLineInfo.files != null) {
config.set(StramAppLauncher.FILES_CONF_KEY_NAME, commandLineInfo.files);
}
}
if (commandLineInfo.archives != null) {
commandLineInfo.archives = expandCommaSeparatedFiles(commandLineInfo.archives);
if (commandLineInfo.archives != null) {
config.set(StramAppLauncher.ARCHIVES_CONF_KEY_NAME, commandLineInfo.archives);
}
}
if (commandLineInfo.origAppId != null) {
config.set(StramAppLauncher.ORIGINAL_APP_ID, commandLineInfo.origAppId);
}
config.set(StramAppLauncher.QUEUE_NAME, commandLineInfo.queue != null ? commandLineInfo.queue : "default");
} catch (Throwable t) {
throw new CliException("Error opening the config XML file: " + configFile, t);
}
String fileName = expandFileName(commandLineInfo.args[0], true);
StramAppLauncher submitApp;
AppFactory appFactory = null;
String matchString = commandLineInfo.args.length >= 2 ? commandLineInfo.args[1] : null;
if (fileName.endsWith(".json")) {
File file = new File(fileName);
submitApp = new StramAppLauncher(file.getName(), config);
appFactory = new StramAppLauncher.JsonFileAppFactory(file);
if (matchString != null) {
LOG.warn("Match string \"{}\" is ignored for launching applications specified in JSON", matchString);
}
} else if (fileName.endsWith(".properties")) {
File file = new File(fileName);
submitApp = new StramAppLauncher(file.getName(), config);
appFactory = new StramAppLauncher.PropertyFileAppFactory(file);
if (matchString != null) {
LOG.warn("Match string \"{}\" is ignored for launching applications specified in properties file", matchString);
}
} else {
// see if it's an app package
AppPackage ap = null;
try {
ap = newAppPackageInstance(new File(fileName));
} catch (Exception ex) {
// It's not an app package
if (requiredAppPackageName != null) {
throw new CliException("Config package requires an app package name of \"" + requiredAppPackageName + "\"");
}
}
if (ap != null) {
try {
checkCompatible(ap, cp);
launchAppPackage(ap, cp, commandLineInfo, reader);
return;
} finally {
IOUtils.closeQuietly(ap);
}
}
submitApp = getStramAppLauncher(fileName, config, commandLineInfo.ignorePom);
}
submitApp.loadDependencies();
if (commandLineInfo.origAppId != null) {
// ensure app is not running
ApplicationReport ar = null;
try {
ar = getApplication(commandLineInfo.origAppId);
} catch (Exception e) {
// application (no longer) in the RM history, does not prevent restart from state in DFS
LOG.debug("Cannot determine status of application {} {}", commandLineInfo.origAppId, ExceptionUtils.getMessage(e));
}
if (ar != null) {
if (ar.getFinalApplicationStatus() == FinalApplicationStatus.UNDEFINED) {
throw new CliException("Cannot relaunch non-terminated application: " + commandLineInfo.origAppId + " " + ar.getYarnApplicationState());
}
if (appFactory == null && matchString == null) {
// skip selection if we can match application name from previous run
List<AppFactory> matchingAppFactories = getMatchingAppFactories(submitApp, ar.getName(), commandLineInfo.exactMatch);
for (AppFactory af : matchingAppFactories) {
String appName = submitApp.getLogicalPlanConfiguration().getAppAlias(af.getName());
if (appName == null) {
appName = af.getName();
}
// limit to exact match
if (appName.equals(ar.getName())) {
appFactory = af;
break;
}
}
}
}
}
if (appFactory == null && matchString != null) {
// attempt to interpret argument as property file - do we still need it?
try {
File file = new File(expandFileName(commandLineInfo.args[1], true));
if (file.exists()) {
if (commandLineInfo.args[1].endsWith(".properties")) {
appFactory = new StramAppLauncher.PropertyFileAppFactory(file);
} else if (commandLineInfo.args[1].endsWith(".json")) {
appFactory = new StramAppLauncher.JsonFileAppFactory(file);
}
}
} catch (Throwable t) {
// ignore
}
}
if (appFactory == null) {
List<AppFactory> matchingAppFactories = getMatchingAppFactories(submitApp, matchString, commandLineInfo.exactMatch);
if (matchingAppFactories == null || matchingAppFactories.isEmpty()) {
throw new CliException("No applications matching \"" + matchString + "\" bundled in jar.");
} else if (matchingAppFactories.size() == 1) {
appFactory = matchingAppFactories.get(0);
} else if (matchingAppFactories.size() > 1) {
//Store the appNames sorted in alphabetical order and their position in matchingAppFactories list
TreeMap<String, Integer> appNamesInAlphabeticalOrder = new TreeMap<String, Integer>();
// Display matching applications
for (int i = 0; i < matchingAppFactories.size(); i++) {
String appName = matchingAppFactories.get(i).getName();
String appAlias = submitApp.getLogicalPlanConfiguration().getAppAlias(appName);
if (appAlias != null) {
appName = appAlias;
}
appNamesInAlphabeticalOrder.put(appName, i);
}
//Create a mapping between the app display number and original index at matchingAppFactories
int index = 1;
HashMap<Integer, Integer> displayIndexToOriginalUnsortedIndexMap = new HashMap<Integer, Integer>();
for (Map.Entry<String, Integer> entry : appNamesInAlphabeticalOrder.entrySet()) {
//Map display number of the app to original unsorted index
displayIndexToOriginalUnsortedIndexMap.put(index, entry.getValue());
//Display the app names
System.out.printf("%3d. %s\n", index++, entry.getKey());
}
// Exit if not in interactive mode
if (!consolePresent) {
throw new CliException("More than one application in jar file match '" + matchString + "'");
} else {
boolean useHistory = reader.isHistoryEnabled();
reader.setHistoryEnabled(false);
History previousHistory = reader.getHistory();
History dummyHistory = new MemoryHistory();
reader.setHistory(dummyHistory);
List<Completer> completers = new ArrayList<Completer>(reader.getCompleters());
for (Completer c : completers) {
reader.removeCompleter(c);
}
reader.setHandleUserInterrupt(true);
String optionLine;
try {
optionLine = reader.readLine("Choose application: ");
} finally {
reader.setHandleUserInterrupt(false);
reader.setHistoryEnabled(useHistory);
reader.setHistory(previousHistory);
for (Completer c : completers) {
reader.addCompleter(c);
}
}
try {
int option = Integer.parseInt(optionLine);
if (0 < option && option <= matchingAppFactories.size()) {
int appIndex = displayIndexToOriginalUnsortedIndexMap.get(option);
appFactory = matchingAppFactories.get(appIndex);
}
} catch (Exception ex) {
// ignore
}
}
}
}
if (appFactory != null) {
if (!commandLineInfo.localMode) {
// see whether there is an app with the same name and user name running
String appNameAttributeName = StreamingApplication.DT_PREFIX + Context.DAGContext.APPLICATION_NAME.getName();
String appName = config.get(appNameAttributeName, appFactory.getName());
ApplicationReport duplicateApp = StramClientUtils.getStartedAppInstanceByName(yarnClient, appName, UserGroupInformation.getLoginUser().getUserName(), null);
if (duplicateApp != null) {
throw new CliException("Application with the name \"" + duplicateApp.getName() + "\" already running under the current user \"" + duplicateApp.getUser() + "\". Please choose another name. You can change the name by setting " + appNameAttributeName);
}
// This is for suppressing System.out printouts from applications so that the user of CLI will not be confused by those printouts
PrintStream originalStream = suppressOutput();
ApplicationId appId = null;
try {
if (raw) {
PrintStream dummyStream = new PrintStream(new OutputStream()
{
@Override
public void write(int b)
{
// no-op
}
});
System.setOut(dummyStream);
}
appId = submitApp.launchApp(appFactory);
currentApp = yarnClient.getApplicationReport(appId);
} finally {
restoreOutput(originalStream);
}
if (appId != null) {
printJson("{\"appId\": \"" + appId + "\"}");
}
} else {
submitApp.runLocal(appFactory);
}
} else {
System.err.println("No application specified.");
}
} finally {
IOUtils.closeQuietly(cp);
}
}
}
private class GetConfigParameterCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
PrintStream os = getOutputPrintStream();
if (args.length == 1) {
Map<String, String> sortedMap = new TreeMap<String, String>();
for (Map.Entry<String, String> entry : conf) {
sortedMap.put(entry.getKey(), entry.getValue());
}
for (Map.Entry<String, String> entry : sortedMap.entrySet()) {
os.println(entry.getKey() + "=" + entry.getValue());
}
}
else {
String value = conf.get(args[1]);
if (value != null) {
os.println(value);
}
}
closeOutputPrintStream(os);
}
}
private class ShutdownAppCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
ApplicationReport[] apps;
WebServicesClient webServicesClient = new WebServicesClient();
if (args.length == 1) {
if (currentApp == null) {
throw new CliException("No application selected");
}
else {
apps = new ApplicationReport[]{currentApp};
}
}
else {
apps = new ApplicationReport[args.length - 1];
for (int i = 1; i < args.length; i++) {
apps[i - 1] = getApplication(args[i]);
if (apps[i - 1] == null) {
throw new CliException("Streaming application with id " + args[i] + " is not found.");
}
}
}
for (ApplicationReport app : apps) {
try {
JSONObject response = getResource(new StramAgent.StramUriSpec().path(StramWebServices.PATH_SHUTDOWN), app, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(clazz, new JSONObject());
}
});
if (consolePresent) {
System.out.println("Shutdown requested: " + response);
}
currentApp = null;
} catch (Exception e) {
throw new CliException("Failed to request shutdown for appid " + app.getApplicationId().toString(), e);
}
}
}
}
private class ListAppsCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
try {
JSONArray jsonArray = new JSONArray();
List<ApplicationReport> appList = getApplicationList();
Collections.sort(appList, new Comparator<ApplicationReport>()
{
@Override
public int compare(ApplicationReport o1, ApplicationReport o2)
{
return o1.getApplicationId().getId() - o2.getApplicationId().getId();
}
});
int totalCnt = 0;
int runningCnt = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
for (ApplicationReport ar : appList) {
/*
* This is inefficient, but what the heck, if this can be passed through the command line, can anyone notice slowness.
*/
JSONObject jsonObj = new JSONObject();
jsonObj.put("startTime", sdf.format(new java.util.Date(ar.getStartTime())));
jsonObj.put("id", ar.getApplicationId().getId());
jsonObj.put("name", ar.getName());
jsonObj.put("state", ar.getYarnApplicationState().name());
jsonObj.put("trackingUrl", ar.getTrackingUrl());
jsonObj.put("finalStatus", ar.getFinalApplicationStatus());
totalCnt++;
if (ar.getYarnApplicationState() == YarnApplicationState.RUNNING) {
runningCnt++;
}
if (args.length > 1) {
if (StringUtils.isNumeric(args[1])) {
if (jsonObj.getString("id").equals(args[1])) {
jsonArray.put(jsonObj);
break;
}
}
else {
@SuppressWarnings("unchecked")
Iterator<String> keys = jsonObj.keys();
while (keys.hasNext()) {
if (jsonObj.get(keys.next()).toString().toLowerCase().contains(args[1].toLowerCase())) {
jsonArray.put(jsonObj);
break;
}
}
}
}
else {
jsonArray.put(jsonObj);
}
}
printJson(jsonArray, "apps");
if (consolePresent) {
System.out.println(runningCnt + " active, total " + totalCnt + " applications.");
}
}
catch (Exception ex) {
throw new CliException("Failed to retrieve application list", ex);
}
}
}
private class KillAppCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (args.length == 1) {
if (currentApp == null) {
throw new CliException("No application selected");
}
else {
try {
yarnClient.killApplication(currentApp.getApplicationId());
currentApp = null;
}
catch (YarnException e) {
throw new CliException("Failed to kill " + currentApp.getApplicationId(), e);
}
}
if (consolePresent) {
System.out.println("Kill app requested");
}
return;
}
ApplicationReport app = null;
int i = 0;
try {
while (++i < args.length) {
app = getApplication(args[i]);
if (app == null) {
throw new CliException("Streaming application with id " + args[i] + " is not found.");
}
yarnClient.killApplication(app.getApplicationId());
if (app == currentApp) {
currentApp = null;
}
}
if (consolePresent) {
System.out.println("Kill app requested");
}
}
catch (YarnException e) {
throw new CliException("Failed to kill " + ((app == null || app.getApplicationId() == null) ? "unknown application" : app.getApplicationId()) + ". Aborting killing of any additional applications.", e);
}
catch (NumberFormatException nfe) {
throw new CliException("Invalid application Id " + args[i], nfe);
}
}
}
private class AliasCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (args[1].equals(args[2])) {
throw new CliException("Alias to itself!");
}
aliases.put(args[1], args[2]);
if (consolePresent) {
System.out.println("Alias " + args[1] + " created.");
}
updateCompleter(reader);
}
}
private class SourceCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
processSourceFile(args[1], reader);
if (consolePresent) {
System.out.println("File " + args[1] + " sourced.");
}
}
}
private class ExitCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (topLevelHistory != null) {
try {
topLevelHistory.flush();
} catch (IOException ex) {
LOG.warn("Cannot flush command history");
}
}
if (changingLogicalPlanHistory != null) {
try {
changingLogicalPlanHistory.flush();
} catch (IOException ex) {
LOG.warn("Cannot flush command history");
}
}
System.exit(0);
}
}
private class ListContainersCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
JSONObject json = getResource(StramWebServices.PATH_PHYSICAL_PLAN_CONTAINERS, currentApp);
if (args.length == 1) {
printJson(json);
}
else {
Object containersObj = json.get("containers");
JSONArray containers;
if (containersObj instanceof JSONArray) {
containers = (JSONArray) containersObj;
}
else {
containers = new JSONArray();
containers.put(containersObj);
}
if (containersObj == null) {
System.out.println("No containers found!");
}
else {
JSONArray resultContainers = new JSONArray();
for (int o = containers.length(); o-- > 0; ) {
JSONObject container = containers.getJSONObject(o);
String id = container.getString("id");
if (id != null && !id.isEmpty()) {
for (int argc = args.length; argc-- > 1; ) {
String s1 = "0" + args[argc];
String s2 = "_" + args[argc];
if (id.equals(args[argc]) || id.endsWith(s1) || id.endsWith(s2)) {
resultContainers.put(container);
}
}
}
}
printJson(resultContainers, "containers");
}
}
}
}
private class ListOperatorsCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
JSONObject json = getResource(StramWebServices.PATH_PHYSICAL_PLAN_OPERATORS, currentApp);
if (args.length > 1) {
String singleKey = "" + json.keys().next();
JSONArray matches = new JSONArray();
// filter operators
JSONArray arr;
Object obj = json.get(singleKey);
if (obj instanceof JSONArray) {
arr = (JSONArray) obj;
}
else {
arr = new JSONArray();
arr.put(obj);
}
for (int i = 0; i < arr.length(); i++) {
JSONObject oper = arr.getJSONObject(i);
if (StringUtils.isNumeric(args[1])) {
if (oper.getString("id").equals(args[1])) {
matches.put(oper);
break;
}
}
else {
@SuppressWarnings("unchecked")
Iterator<String> keys = oper.keys();
while (keys.hasNext()) {
if (oper.get(keys.next()).toString().toLowerCase().contains(args[1].toLowerCase())) {
matches.put(oper);
break;
}
}
}
}
json.put(singleKey, matches);
}
printJson(json);
}
}
private class ShowPhysicalPlanCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
try {
printJson(getResource(StramWebServices.PATH_SHUTDOWN, currentApp));
} catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
}
}
private class KillContainerCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
for (int i = 1; i < args.length; i++) {
String containerLongId = getContainerLongId(args[i]);
if (containerLongId == null) {
throw new CliException("Container " + args[i] + " not found");
}
try {
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_PHYSICAL_PLAN_CONTAINERS).path(URLEncoder.encode(containerLongId, "UTF-8")).path("kill");
JSONObject response = getResource(uriSpec, currentApp, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(clazz, new JSONObject());
}
});
if (consolePresent) {
System.out.println("Kill container requested: " + response);
}
} catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
}
}
}
private class WaitCommand implements Command
{
@Override
public void execute(String[] args, final ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
int timeout = Integer.valueOf(args[1]);
ClientRMHelper.AppStatusCallback cb = new ClientRMHelper.AppStatusCallback()
{
@Override
public boolean exitLoop(ApplicationReport report)
{
System.out.println("current status is: " + report.getYarnApplicationState());
try {
if (reader.getInput().available() > 0) {
return true;
}
}
catch (IOException e) {
LOG.error("Error checking for input.", e);
}
return false;
}
};
try {
ClientRMHelper clientRMHelper = new ClientRMHelper(yarnClient);
boolean result = clientRMHelper.waitForCompletion(currentApp.getApplicationId(), cb, timeout * 1000);
if (!result) {
System.err.println("Application terminated unsucessful.");
}
}
catch (YarnException e) {
throw new CliException("Failed to kill " + currentApp.getApplicationId(), e);
}
}
}
private class StartRecordingCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String opId = args[1];
String port = null;
long numWindows = 0;
if (args.length >= 3) {
port = args[2];
}
if (args.length >= 4) {
numWindows = Long.valueOf(args[3]);
}
printJson(recordingsAgent.startRecording(currentApp.getApplicationId().toString(), opId, port, numWindows));
}
}
private class StopRecordingCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String opId = args[1];
String port = null;
if (args.length == 3) {
port = args[2];
}
printJson(recordingsAgent.stopRecording(currentApp.getApplicationId().toString(), opId, port));
}
}
private class GetRecordingInfoCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (args.length <= 1) {
List<RecordingInfo> recordingInfo = recordingsAgent.getRecordingInfo(currentApp.getApplicationId().toString());
printJson(recordingInfo, "recordings");
}
else if (args.length <= 2) {
String opId = args[1];
List<RecordingInfo> recordingInfo = recordingsAgent.getRecordingInfo(currentApp.getApplicationId().toString(), opId);
printJson(recordingInfo, "recordings");
}
else {
String opId = args[1];
String id = args[2];
RecordingInfo recordingInfo = recordingsAgent.getRecordingInfo(currentApp.getApplicationId().toString(), opId, id);
printJson(new JSONObject(mapper.writeValueAsString(recordingInfo)));
}
}
}
private class GetAppAttributesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_LOGICAL_PLAN).path("attributes");
if (args.length > 1) {
uriSpec = uriSpec.queryParam("attributeName", args[1]);
}
try {
JSONObject response = getResource(uriSpec, currentApp);
printJson(response);
} catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
}
}
private class GetOperatorAttributesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_LOGICAL_PLAN_OPERATORS).path(URLEncoder.encode(args[1], "UTF-8")).path("attributes");
if (args.length > 2) {
uriSpec = uriSpec.queryParam("attributeName", args[2]);
}
try {
JSONObject response = getResource(uriSpec, currentApp);
printJson(response);
} catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
}
}
private class GetPortAttributesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_LOGICAL_PLAN_OPERATORS).path(URLEncoder.encode(args[1], "UTF-8")).path("ports").path(URLEncoder.encode(args[2], "UTF-8")).path("attributes");
if (args.length > 3) {
uriSpec = uriSpec.queryParam("attributeName", args[3]);
}
try {
JSONObject response = getResource(uriSpec, currentApp);
printJson(response);
} catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
}
}
private class GetOperatorPropertiesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_LOGICAL_PLAN_OPERATORS).path(URLEncoder.encode(args[1], "UTF-8")).path("properties");
if (args.length > 2) {
uriSpec = uriSpec.queryParam("propertyName", args[2]);
}
try {
JSONObject response = getResource(uriSpec, currentApp);
printJson(response);
} catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
}
}
private class GetPhysicalOperatorPropertiesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
if (!NumberUtils.isDigits(args[1])) {
throw new CliException("Operator ID must be a number");
}
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, args.length - 1);
PosixParser parser = new PosixParser();
CommandLine line = parser.parse(GET_PHYSICAL_PROPERTY_OPTIONS.options, newArgs);
String waitTime = line.getOptionValue(GET_PHYSICAL_PROPERTY_OPTIONS.waitTime.getOpt());
String propertyName = line.getOptionValue(GET_PHYSICAL_PROPERTY_OPTIONS.propertyName.getOpt());
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_PHYSICAL_PLAN_OPERATORS).path(args[1]).path("properties");
if (propertyName != null) {
uriSpec = uriSpec.queryParam("propertyName", propertyName);
}
if (waitTime != null) {
uriSpec = uriSpec.queryParam("waitTime", waitTime);
}
try {
JSONObject response = getResource(uriSpec, currentApp);
printJson(response);
} catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
}
}
private class SetOperatorPropertyCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
if (changingLogicalPlan) {
String operatorName = args[1];
String propertyName = args[2];
String propertyValue = args[3];
SetOperatorPropertyRequest request = new SetOperatorPropertyRequest();
request.setOperatorName(operatorName);
request.setPropertyName(propertyName);
request.setPropertyValue(propertyValue);
logicalPlanRequestQueue.add(request);
}
else {
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_LOGICAL_PLAN_OPERATORS).path(URLEncoder.encode(args[1], "UTF-8")).path("properties");
final JSONObject request = new JSONObject();
request.put(args[2], args[3]);
JSONObject response = getResource(uriSpec, currentApp, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(JSONObject.class, request);
}
});
printJson(response);
}
}
}
private class SetPhysicalOperatorPropertyCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
if (!NumberUtils.isDigits(args[1])) {
throw new CliException("Operator ID must be a number");
}
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_PHYSICAL_PLAN_OPERATORS).path(args[1]).path("properties");
final JSONObject request = new JSONObject();
request.put(args[2], args[3]);
JSONObject response = getResource(uriSpec, currentApp, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(JSONObject.class, request);
}
});
printJson(response);
}
}
private class BeginLogicalPlanChangeCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
changingLogicalPlan = true;
reader.setHistory(changingLogicalPlanHistory);
}
}
private class ShowLogicalPlanCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, args.length - 1);
ShowLogicalPlanCommandLineInfo commandLineInfo = getShowLogicalPlanCommandLineInfo(newArgs);
Configuration config = StramClientUtils.addDTSiteResources(new Configuration());
if (commandLineInfo.libjars != null) {
commandLineInfo.libjars = expandCommaSeparatedFiles(commandLineInfo.libjars);
if (commandLineInfo.libjars != null) {
config.set(StramAppLauncher.LIBJARS_CONF_KEY_NAME, commandLineInfo.libjars);
}
}
if (commandLineInfo.args.length >= 2) {
String jarfile = expandFileName(commandLineInfo.args[0], true);
AppPackage ap = null;
// see if the first argument is actually an app package
try {
ap = new AppPackage(new File(jarfile));
}
catch (Exception ex) {
// fall through
}
if (ap != null) {
new ShowLogicalPlanAppPackageCommand().execute(args, reader);
return;
}
String appName = commandLineInfo.args[1];
StramAppLauncher submitApp = getStramAppLauncher(jarfile, config, commandLineInfo.ignorePom);
submitApp.loadDependencies();
List<AppFactory> matchingAppFactories = getMatchingAppFactories(submitApp, appName, commandLineInfo.exactMatch);
if (matchingAppFactories == null || matchingAppFactories.isEmpty()) {
throw new CliException("No application in jar file matches '" + appName + "'");
}
else if (matchingAppFactories.size() > 1) {
throw new CliException("More than one application in jar file match '" + appName + "'");
}
else {
Map<String, Object> map = new HashMap<String, Object>();
PrintStream originalStream = System.out;
AppFactory appFactory = matchingAppFactories.get(0);
try {
if (raw) {
PrintStream dummyStream = new PrintStream(new OutputStream()
{
@Override
public void write(int b)
{
// no-op
}
});
System.setOut(dummyStream);
}
LogicalPlan logicalPlan = appFactory.createApp(submitApp.getLogicalPlanConfiguration());
map.put("applicationName", appFactory.getName());
map.put("logicalPlan", LogicalPlanSerializer.convertToMap(logicalPlan));
}
finally {
if (raw) {
System.setOut(originalStream);
}
}
printJson(map);
}
}
else if (commandLineInfo.args.length == 1) {
String filename = expandFileName(commandLineInfo.args[0], true);
if (filename.endsWith(".json")) {
File file = new File(filename);
StramAppLauncher submitApp = new StramAppLauncher(file.getName(), config);
AppFactory appFactory = new StramAppLauncher.JsonFileAppFactory(file);
LogicalPlan logicalPlan = appFactory.createApp(submitApp.getLogicalPlanConfiguration());
Map<String, Object> map = new HashMap<String, Object>();
map.put("applicationName", appFactory.getName());
map.put("logicalPlan", LogicalPlanSerializer.convertToMap(logicalPlan));
printJson(map);
}
else if (filename.endsWith(".properties")) {
File file = new File(filename);
StramAppLauncher submitApp = new StramAppLauncher(file.getName(), config);
AppFactory appFactory = new StramAppLauncher.PropertyFileAppFactory(file);
LogicalPlan logicalPlan = appFactory.createApp(submitApp.getLogicalPlanConfiguration());
Map<String, Object> map = new HashMap<String, Object>();
map.put("applicationName", appFactory.getName());
map.put("logicalPlan", LogicalPlanSerializer.convertToMap(logicalPlan));
printJson(map);
}
else {
StramAppLauncher submitApp = getStramAppLauncher(filename, config, commandLineInfo.ignorePom);
submitApp.loadDependencies();
List<Map<String, Object>> appList = new ArrayList<Map<String, Object>>();
List<AppFactory> appFactoryList = submitApp.getBundledTopologies();
for (AppFactory appFactory : appFactoryList) {
Map<String, Object> m = new HashMap<String, Object>();
m.put("name", appFactory.getName());
appList.add(m);
}
printJson(appList, "applications");
}
}
else {
if (currentApp == null) {
throw new CliException("No application selected");
}
JSONObject response = getResource(StramWebServices.PATH_LOGICAL_PLAN, currentApp);
printJson(response);
}
}
}
private class ShowLogicalPlanAppPackageCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String jarfile = expandFileName(args[1], true);
AppPackage ap = null;
try {
ap = newAppPackageInstance(new File(jarfile));
List<AppInfo> applications = ap.getApplications();
if (args.length >= 3) {
for (AppInfo appInfo : applications) {
if (args[2].equals(appInfo.name)) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("applicationName", appInfo.name);
if (appInfo.dag != null) {
map.put("logicalPlan", LogicalPlanSerializer.convertToMap(appInfo.dag));
}
if (appInfo.error != null) {
map.put("error", appInfo.error);
}
printJson(map);
}
}
} else {
List<Map<String, Object>> appList = new ArrayList<Map<String, Object>>();
for (AppInfo appInfo : applications) {
Map<String, Object> m = new HashMap<String, Object>();
m.put("name", appInfo.name);
m.put("type", appInfo.type);
appList.add(m);
}
printJson(appList, "applications");
}
} finally {
IOUtils.closeQuietly(ap);
}
}
}
private File copyToLocal(String[] files) throws IOException
{
File tmpDir = new File("/tmp/datatorrent/" + ManagementFactory.getRuntimeMXBean().getName());
tmpDir.mkdirs();
for (int i = 0; i < files.length; i++) {
try {
URI uri = new URI(files[i]);
String scheme = uri.getScheme();
if (scheme == null || scheme.equals("file")) {
files[i] = uri.getPath();
}
else {
FileSystem tmpFs = FileSystem.newInstance(uri, conf);
try {
Path srcPath = new Path(uri.getPath());
Path dstPath = new Path(tmpDir.getAbsolutePath(), String.valueOf(i) + srcPath.getName());
tmpFs.copyToLocalFile(srcPath, dstPath);
files[i] = dstPath.toUri().getPath();
}
finally {
tmpFs.close();
}
}
}
catch (URISyntaxException ex) {
throw new RuntimeException(ex);
}
}
return tmpDir;
}
public static class GetOperatorClassesCommandLineOptions
{
final Options options = new Options();
final Option parent = add(new Option("parent", "Specify the parent class for the operators"));
private Option add(Option opt)
{
this.options.addOption(opt);
return opt;
}
}
private static GetOperatorClassesCommandLineOptions GET_OPERATOR_CLASSES_OPTIONS = new GetOperatorClassesCommandLineOptions();
private static class GetOperatorClassesCommandLineInfo
{
String parent;
String[] args;
}
private static GetOperatorClassesCommandLineInfo getGetOperatorClassesCommandLineInfo(String[] args) throws ParseException
{
CommandLineParser parser = new PosixParser();
GetOperatorClassesCommandLineInfo result = new GetOperatorClassesCommandLineInfo();
CommandLine line = parser.parse(GET_OPERATOR_CLASSES_OPTIONS.options, args);
result.parent = line.getOptionValue("parent");
result.args = line.getArgs();
return result;
}
private class GetJarOperatorClassesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, args.length - 1);
GetOperatorClassesCommandLineInfo commandLineInfo = getGetOperatorClassesCommandLineInfo(newArgs);
String parentName = commandLineInfo.parent != null ? commandLineInfo.parent : Operator.class.getName();
String files = expandCommaSeparatedFiles(commandLineInfo.args[0]);
if (files == null) {
throw new CliException("File " + commandLineInfo.args[0] + " is not found");
}
String[] jarFiles = files.split(",");
File tmpDir = copyToLocal(jarFiles);
try {
ObjectMapper defaultValueMapper = ObjectMapperFactory.getOperatorValueSerializer();
OperatorDiscoverer operatorDiscoverer = new OperatorDiscoverer(jarFiles);
String searchTerm = commandLineInfo.args.length > 1 ? commandLineInfo.args[1] : null;
Set<Class<? extends Operator>> operatorClasses = operatorDiscoverer.getOperatorClasses(parentName, searchTerm);
JSONObject json = new JSONObject();
JSONArray arr = new JSONArray();
JSONObject portClassHier = new JSONObject();
JSONObject failed = new JSONObject();
for (Class<? extends Operator> clazz : operatorClasses) {
try {
JSONObject oper = operatorDiscoverer.describeOperator(clazz);
// add default value
Operator operIns = clazz.newInstance();
String s = defaultValueMapper.writeValueAsString(operIns);
oper.put("defaultValue", new JSONObject(s).get(clazz.getName()));
// add class hier info to portClassHier
operatorDiscoverer.buildPortClassHier(oper, portClassHier);
arr.put(oper);
} catch (Throwable t) {
// ignore this class
final String cls = clazz.getName(), ex = t.toString();
failed.put(cls, ex);
}
}
json.put("operatorClasses", arr);
json.put("portClassHier", portClassHier);
if (failed.length() > 0) {
json.put("failedOperators", failed);
}
printJson(json);
}
finally {
FileUtils.deleteDirectory(tmpDir);
}
}
}
private class GetJarOperatorPropertiesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String files = expandCommaSeparatedFiles(args[1]);
if (files == null) {
throw new CliException("File " + args[1] + " is not found");
}
String[] jarFiles = files.split(",");
File tmpDir = copyToLocal(jarFiles);
try {
OperatorDiscoverer operatorDiscoverer = new OperatorDiscoverer(jarFiles);
Class<? extends Operator> operatorClass = operatorDiscoverer.getOperatorClass(args[2]);
printJson(operatorDiscoverer.describeOperator(operatorClass));
} finally {
FileUtils.deleteDirectory(tmpDir);
}
}
}
private class DumpPropertiesFileCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String outfilename = expandFileName(args[1], false);
if (args.length > 3) {
String jarfile = args[2];
String appName = args[3];
Configuration config = StramClientUtils.addDTSiteResources(new Configuration());
StramAppLauncher submitApp = getStramAppLauncher(jarfile, config, false);
submitApp.loadDependencies();
List<AppFactory> matchingAppFactories = getMatchingAppFactories(submitApp, appName, true);
if (matchingAppFactories == null || matchingAppFactories.isEmpty()) {
throw new CliException("No application in jar file matches '" + appName + "'");
}
else if (matchingAppFactories.size() > 1) {
throw new CliException("More than one application in jar file match '" + appName + "'");
}
else {
AppFactory appFactory = matchingAppFactories.get(0);
LogicalPlan logicalPlan = appFactory.createApp(submitApp.getLogicalPlanConfiguration());
File file = new File(outfilename);
if (!file.exists()) {
file.createNewFile();
}
LogicalPlanSerializer.convertToProperties(logicalPlan).save(file);
}
}
else {
if (currentApp == null) {
throw new CliException("No application selected");
}
JSONObject response = getResource(StramWebServices.PATH_LOGICAL_PLAN, currentApp);
File file = new File(outfilename);
if (!file.exists()) {
file.createNewFile();
}
LogicalPlanSerializer.convertToProperties(response).save(file);
}
System.out.println("Property file is saved at " + outfilename);
}
}
private class CreateOperatorCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String operatorName = args[1];
String className = args[2];
CreateOperatorRequest request = new CreateOperatorRequest();
request.setOperatorName(operatorName);
request.setOperatorFQCN(className);
logicalPlanRequestQueue.add(request);
}
}
private class RemoveOperatorCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String operatorName = args[1];
RemoveOperatorRequest request = new RemoveOperatorRequest();
request.setOperatorName(operatorName);
logicalPlanRequestQueue.add(request);
}
}
private class CreateStreamCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String streamName = args[1];
String sourceOperatorName = args[2];
String sourcePortName = args[3];
String sinkOperatorName = args[4];
String sinkPortName = args[5];
CreateStreamRequest request = new CreateStreamRequest();
request.setStreamName(streamName);
request.setSourceOperatorName(sourceOperatorName);
request.setSinkOperatorName(sinkOperatorName);
request.setSourceOperatorPortName(sourcePortName);
request.setSinkOperatorPortName(sinkPortName);
logicalPlanRequestQueue.add(request);
}
}
private class AddStreamSinkCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String streamName = args[1];
String sinkOperatorName = args[2];
String sinkPortName = args[3];
AddStreamSinkRequest request = new AddStreamSinkRequest();
request.setStreamName(streamName);
request.setSinkOperatorName(sinkOperatorName);
request.setSinkOperatorPortName(sinkPortName);
logicalPlanRequestQueue.add(request);
}
}
private class RemoveStreamCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String streamName = args[1];
RemoveStreamRequest request = new RemoveStreamRequest();
request.setStreamName(streamName);
logicalPlanRequestQueue.add(request);
}
}
private class SetOperatorAttributeCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String operatorName = args[1];
String attributeName = args[2];
String attributeValue = args[3];
SetOperatorAttributeRequest request = new SetOperatorAttributeRequest();
request.setOperatorName(operatorName);
request.setAttributeName(attributeName);
request.setAttributeValue(attributeValue);
logicalPlanRequestQueue.add(request);
}
}
private class SetStreamAttributeCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String streamName = args[1];
String attributeName = args[2];
String attributeValue = args[3];
SetStreamAttributeRequest request = new SetStreamAttributeRequest();
request.setStreamName(streamName);
request.setAttributeName(attributeName);
request.setAttributeValue(attributeValue);
logicalPlanRequestQueue.add(request);
}
}
private class SetPortAttributeCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String operatorName = args[1];
String attributeName = args[2];
String attributeValue = args[3];
SetPortAttributeRequest request = new SetPortAttributeRequest();
request.setOperatorName(operatorName);
request.setAttributeName(attributeName);
request.setAttributeValue(attributeValue);
logicalPlanRequestQueue.add(request);
}
}
private class AbortCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
logicalPlanRequestQueue.clear();
changingLogicalPlan = false;
reader.setHistory(topLevelHistory);
}
}
private class SubmitCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (logicalPlanRequestQueue.isEmpty()) {
throw new CliException("Nothing to submit. Type \"abort\" to abort change");
}
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_LOGICAL_PLAN);
try {
final Map<String, Object> m = new HashMap<String, Object>();
ObjectMapper mapper = new ObjectMapper();
m.put("requests", logicalPlanRequestQueue);
final JSONObject jsonRequest = new JSONObject(mapper.writeValueAsString(m));
JSONObject response = getResource(uriSpec, currentApp, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(JSONObject.class, jsonRequest);
}
});
printJson(response);
}
catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
logicalPlanRequestQueue.clear();
changingLogicalPlan = false;
reader.setHistory(topLevelHistory);
}
}
private class ShowQueueCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
printJson(logicalPlanRequestQueue, "queue");
if (consolePresent) {
System.out.println("Total operations in queue: " + logicalPlanRequestQueue.size());
}
}
}
private class BeginMacroCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String name = args[1];
if (macros.containsKey(name) || aliases.containsKey(name)) {
System.err.println("Name '" + name + "' already exists.");
return;
}
try {
List<String> commands = new ArrayList<String>();
while (true) {
String line;
if (consolePresent) {
line = reader.readLine("macro def (" + name + ") > ");
}
else {
line = reader.readLine("", (char) 0);
}
if (line.equals("end")) {
macros.put(name, commands);
updateCompleter(reader);
if (consolePresent) {
System.out.println("Macro '" + name + "' created.");
}
return;
}
else if (line.equals("abort")) {
System.err.println("Aborted");
return;
}
else {
commands.add(line);
}
}
}
catch (IOException ex) {
System.err.println("Aborted");
}
}
}
private class SetPagerCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (args[1].equals("off")) {
pagerCommand = null;
}
else if (args[1].equals("on")) {
if (consolePresent) {
pagerCommand = "less -F -X -r";
}
}
else {
throw new CliException("set-pager parameter is either on or off.");
}
}
}
private class GetAppInfoCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
ApplicationReport appReport;
if (args.length > 1) {
appReport = getApplication(args[1]);
if (appReport == null) {
throw new CliException("Streaming application with id " + args[1] + " is not found.");
}
}
else {
if (currentApp == null) {
throw new CliException("No application selected");
}
// refresh the state in currentApp
currentApp = yarnClient.getApplicationReport(currentApp.getApplicationId());
appReport = currentApp;
}
JSONObject response;
try {
response = getResource(StramWebServices.PATH_INFO, currentApp);
}
catch (Exception ex) {
response = new JSONObject();
response.put("startTime", appReport.getStartTime());
response.put("id", appReport.getApplicationId().toString());
response.put("name", appReport.getName());
response.put("user", appReport.getUser());
}
response.put("state", appReport.getYarnApplicationState().name());
response.put("trackingUrl", appReport.getTrackingUrl());
response.put("finalStatus", appReport.getFinalApplicationStatus());
printJson(response);
}
}
private class GetAppPackageInfoCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
AppPackage ap = null;
try {
ap = newAppPackageInstance(new File(expandFileName(args[1], true)));
JSONSerializationProvider jomp = new JSONSerializationProvider();
JSONObject apInfo = new JSONObject(jomp.getContext(null).writeValueAsString(ap));
apInfo.remove("name");
printJson(apInfo);
}
finally {
IOUtils.closeQuietly(ap);
}
}
}
private void checkCompatible(AppPackage ap, ConfigPackage cp)
{
if (cp == null) {
return;
}
String requiredAppPackageName = cp.getAppPackageName();
if (requiredAppPackageName != null && !requiredAppPackageName.equals(ap.getAppPackageName())) {
throw new CliException("Config package requires an app package name of \"" + requiredAppPackageName + "\". The app package given has the name of \"" + ap.getAppPackageName() + "\"");
}
String requiredAppPackageMinVersion = cp.getAppPackageMinVersion();
if (requiredAppPackageMinVersion != null && VersionInfo.compare(requiredAppPackageMinVersion, ap.getAppPackageVersion()) > 0) {
throw new CliException("Config package requires an app package minimum version of \"" + requiredAppPackageMinVersion + "\". The app package given is of version \"" + ap.getAppPackageVersion() + "\"");
}
String requiredAppPackageMaxVersion = cp.getAppPackageMaxVersion();
if (requiredAppPackageMaxVersion != null && VersionInfo.compare(requiredAppPackageMaxVersion, ap.getAppPackageVersion()) < 0) {
throw new CliException("Config package requires an app package maximum version of \"" + requiredAppPackageMaxVersion + "\". The app package given is of version \"" + ap.getAppPackageVersion() + "\"");
}
}
private void launchAppPackage(AppPackage ap, ConfigPackage cp, LaunchCommandLineInfo commandLineInfo, ConsoleReader reader) throws Exception
{
new LaunchCommand().execute(getLaunchAppPackageArgs(ap, cp, commandLineInfo, reader), reader);
}
String[] getLaunchAppPackageArgs(AppPackage ap, ConfigPackage cp, LaunchCommandLineInfo commandLineInfo, ConsoleReader reader) throws Exception
{
String matchAppName = null;
if (commandLineInfo.args.length > 1) {
matchAppName = commandLineInfo.args[1];
}
List<AppInfo> applications = new ArrayList<AppInfo>(ap.getApplications());
if (matchAppName != null) {
Iterator<AppInfo> it = applications.iterator();
while (it.hasNext()) {
AppInfo ai = it.next();
if ((commandLineInfo.exactMatch && !ai.name.equals(matchAppName))
|| !ai.name.toLowerCase().matches(".*" + matchAppName.toLowerCase() + ".*")) {
it.remove();
}
}
}
AppInfo selectedApp = null;
if (applications.isEmpty()) {
throw new CliException("No applications in Application Package" + (matchAppName != null ? " matching \"" + matchAppName + "\"" : ""));
} else if (applications.size() == 1) {
selectedApp = applications.get(0);
} else {
//Store the appNames sorted in alphabetical order and their position in matchingAppFactories list
TreeMap<String, Integer> appNamesInAlphabeticalOrder = new TreeMap<String, Integer>();
// Display matching applications
for (int i = 0; i < applications.size(); i++) {
String appName = applications.get(i).name;
appNamesInAlphabeticalOrder.put(appName, i);
}
//Create a mapping between the app display number and original index at matchingAppFactories
int index = 1;
HashMap<Integer, Integer> displayIndexToOriginalUnsortedIndexMap = new HashMap<Integer, Integer>();
for (Map.Entry<String, Integer> entry : appNamesInAlphabeticalOrder.entrySet()) {
//Map display number of the app to original unsorted index
displayIndexToOriginalUnsortedIndexMap.put(index, entry.getValue());
//Display the app names
System.out.printf("%3d. %s\n", index++, entry.getKey());
}
// Exit if not in interactive mode
if (!consolePresent) {
throw new CliException("More than one application in Application Package match '" + matchAppName + "'");
} else {
boolean useHistory = reader.isHistoryEnabled();
reader.setHistoryEnabled(false);
History previousHistory = reader.getHistory();
History dummyHistory = new MemoryHistory();
reader.setHistory(dummyHistory);
List<Completer> completers = new ArrayList<Completer>(reader.getCompleters());
for (Completer c : completers) {
reader.removeCompleter(c);
}
reader.setHandleUserInterrupt(true);
String optionLine;
try {
optionLine = reader.readLine("Choose application: ");
} finally {
reader.setHandleUserInterrupt(false);
reader.setHistoryEnabled(useHistory);
reader.setHistory(previousHistory);
for (Completer c : completers) {
reader.addCompleter(c);
}
}
try {
int option = Integer.parseInt(optionLine);
if (0 < option && option <= applications.size()) {
int appIndex = displayIndexToOriginalUnsortedIndexMap.get(option);
selectedApp = applications.get(appIndex);
}
} catch (Exception ex) {
// ignore
}
}
}
if (selectedApp == null) {
throw new CliException("No application selected");
}
DTConfiguration launchProperties = getLaunchAppPackageProperties(ap, cp, commandLineInfo, selectedApp.name);
String appFile = ap.tempDirectory() + "/app/" + selectedApp.file;
List<String> launchArgs = new ArrayList<String>();
launchArgs.add("launch");
launchArgs.add("-exactMatch");
List<String> absClassPath = new ArrayList<String>(ap.getClassPath());
for (int i = 0; i < absClassPath.size(); i++) {
String path = absClassPath.get(i);
if (!path.startsWith("/")) {
absClassPath.set(i, ap.tempDirectory() + "/" + path);
}
}
if (cp != null) {
StringBuilder files = new StringBuilder();
for (String file : cp.getClassPath()) {
if (files.length() != 0) {
files.append(',');
}
files.append(cp.tempDirectory()).append(File.separatorChar).append(file);
}
if (!StringUtils.isBlank(files.toString())) {
if (commandLineInfo.libjars != null) {
commandLineInfo.libjars = files.toString() + "," + commandLineInfo.libjars;
} else {
commandLineInfo.libjars = files.toString();
}
}
files.setLength(0);
for (String file : cp.getFiles()) {
if (files.length() != 0) {
files.append(',');
}
files.append(cp.tempDirectory()).append(File.separatorChar).append(file);
}
if (!StringUtils.isBlank(files.toString())) {
if (commandLineInfo.files != null) {
commandLineInfo.files = files.toString() + "," + commandLineInfo.files;
} else {
commandLineInfo.files = files.toString();
}
}
}
StringBuilder libjarsVal = new StringBuilder();
if (!absClassPath.isEmpty() || commandLineInfo.libjars != null) {
if (!absClassPath.isEmpty()) {
libjarsVal.append(org.apache.commons.lang3.StringUtils.join(absClassPath, ','));
}
if (commandLineInfo.libjars != null) {
if (libjarsVal.length() > 0) {
libjarsVal.append(",");
}
libjarsVal.append(commandLineInfo.libjars);
}
}
if (appFile.endsWith(".json") || appFile.endsWith(".properties")) {
if (libjarsVal.length() > 0) {
libjarsVal.append(",");
}
libjarsVal.append(ap.tempDirectory()).append("/app/*.jar");
}
if (libjarsVal.length() > 0) {
launchArgs.add("-libjars");
launchArgs.add(libjarsVal.toString());
}
File launchPropertiesFile = new File(ap.tempDirectory(), "launch.xml");
launchProperties.writeToFile(launchPropertiesFile, "");
launchArgs.add("-conf");
launchArgs.add(launchPropertiesFile.getCanonicalPath());
if (commandLineInfo.localMode) {
launchArgs.add("-local");
}
if (commandLineInfo.archives != null) {
launchArgs.add("-archives");
launchArgs.add(commandLineInfo.archives);
}
if (commandLineInfo.files != null) {
launchArgs.add("-files");
launchArgs.add(commandLineInfo.files);
}
if (commandLineInfo.origAppId != null) {
launchArgs.add("-originalAppId");
launchArgs.add(commandLineInfo.origAppId);
}
if (commandLineInfo.queue != null) {
launchArgs.add("-queue");
launchArgs.add(commandLineInfo.queue);
}
launchArgs.add(appFile);
if (!appFile.endsWith(".json") && !appFile.endsWith(".properties")) {
launchArgs.add(selectedApp.name);
}
LOG.debug("Launch command: {}", StringUtils.join(launchArgs, " "));
return launchArgs.toArray(new String[]{});
}
DTConfiguration getLaunchAppPackageProperties(AppPackage ap, ConfigPackage cp, LaunchCommandLineInfo commandLineInfo, String appName) throws Exception
{
DTConfiguration launchProperties = new DTConfiguration();
List<AppInfo> applications = ap.getApplications();
AppInfo selectedApp = null;
for (AppInfo app : applications) {
if (app.name.equals(appName)) {
selectedApp = app;
break;
}
}
Map<String, String> defaultProperties = selectedApp == null ? ap.getDefaultProperties() : selectedApp.defaultProperties;
Set<String> requiredProperties = new TreeSet<String>(selectedApp == null ? ap.getRequiredProperties() : selectedApp.requiredProperties);
for (Map.Entry<String, String> entry : defaultProperties.entrySet()) {
launchProperties.set(entry.getKey(), entry.getValue(), Scope.TRANSIENT, null);
requiredProperties.remove(entry.getKey());
}
// settings specified in the user's environment take precedence over defaults in package.
// since both are merged into a single -conf option below, apply them on top of the defaults here.
File confFile = new File(StramClientUtils.getUserDTDirectory(), StramClientUtils.DT_SITE_XML_FILE);
if (confFile.exists()) {
Configuration userConf = new Configuration(false);
userConf.addResource(new Path(confFile.toURI()));
Iterator<Entry<String, String>> it = userConf.iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
// filter relevant entries
if (entry.getKey().startsWith(StreamingApplication.DT_PREFIX)) {
launchProperties.set(entry.getKey(), entry.getValue(), Scope.TRANSIENT, null);
requiredProperties.remove(entry.getKey());
}
}
}
if (commandLineInfo.apConfigFile != null) {
DTConfiguration givenConfig = new DTConfiguration();
givenConfig.loadFile(new File(ap.tempDirectory() + "/conf/" + commandLineInfo.apConfigFile));
for (Map.Entry<String, String> entry : givenConfig) {
launchProperties.set(entry.getKey(), entry.getValue(), Scope.TRANSIENT, null);
requiredProperties.remove(entry.getKey());
}
}
if (cp != null) {
Map<String, String> properties = cp.getProperties(appName);
for (Map.Entry<String, String> entry : properties.entrySet()) {
launchProperties.set(entry.getKey(), entry.getValue(), Scope.TRANSIENT, null);
requiredProperties.remove(entry.getKey());
}
} else if (commandLineInfo.configFile != null) {
DTConfiguration givenConfig = new DTConfiguration();
givenConfig.loadFile(new File(commandLineInfo.configFile));
for (Map.Entry<String, String> entry : givenConfig) {
launchProperties.set(entry.getKey(), entry.getValue(), Scope.TRANSIENT, null);
requiredProperties.remove(entry.getKey());
}
}
if (commandLineInfo.overrideProperties != null) {
for (Map.Entry<String, String> entry : commandLineInfo.overrideProperties.entrySet()) {
launchProperties.set(entry.getKey(), entry.getValue(), Scope.TRANSIENT, null);
requiredProperties.remove(entry.getKey());
}
}
// now look at whether it is in default configuration
for (Map.Entry<String, String> entry : conf) {
if (StringUtils.isNotBlank(entry.getValue())) {
requiredProperties.remove(entry.getKey());
}
}
if (!requiredProperties.isEmpty()) {
throw new CliException("Required properties not set: " + StringUtils.join(requiredProperties, ", "));
}
//StramClientUtils.evalProperties(launchProperties);
return launchProperties;
}
private class GetAppPackageOperatorsCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String[] tmpArgs = new String[args.length - 1];
System.arraycopy(args, 1, tmpArgs, 0, args.length - 1);
GetOperatorClassesCommandLineInfo commandLineInfo = getGetOperatorClassesCommandLineInfo(tmpArgs);
AppPackage ap = null;
try {
ap = newAppPackageInstance(new File(expandFileName(commandLineInfo.args[0], true)));
List<String> newArgs = new ArrayList<String>();
List<String> jars = new ArrayList<String>();
for (String jar : ap.getAppJars()) {
jars.add(ap.tempDirectory() + "/app/" + jar);
}
for (String libJar : ap.getClassPath()) {
jars.add(ap.tempDirectory() + "/" + libJar);
}
newArgs.add("get-jar-operator-classes");
if (commandLineInfo.parent != null) {
newArgs.add("-parent");
newArgs.add(commandLineInfo.parent);
}
newArgs.add(StringUtils.join(jars, ","));
for (int i = 1; i < commandLineInfo.args.length; i++) {
newArgs.add(commandLineInfo.args[i]);
}
LOG.debug("Executing: " + newArgs);
new GetJarOperatorClassesCommand().execute(newArgs.toArray(new String[]{}), reader);
}
finally {
IOUtils.closeQuietly(ap);
}
}
}
private class GetAppPackageOperatorPropertiesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
AppPackage ap = null;
try {
ap = newAppPackageInstance(new File(expandFileName(args[1], true)));
List<String> newArgs = new ArrayList<String>();
List<String> jars = new ArrayList<String>();
for (String jar : ap.getAppJars()) {
jars.add(ap.tempDirectory() + "/app/" + jar);
}
for (String libJar : ap.getClassPath()) {
jars.add(ap.tempDirectory() + "/" + libJar);
}
newArgs.add("get-jar-operator-properties");
newArgs.add(StringUtils.join(jars, ","));
newArgs.add(args[2]);
new GetJarOperatorPropertiesCommand().execute(newArgs.toArray(new String[]{}), reader);
}
finally {
IOUtils.closeQuietly(ap);
}
}
}
private enum AttributesType
{
APPLICATION, OPERATOR, PORT
}
private class ListAttributesCommand implements Command
{
private final AttributesType type;
protected ListAttributesCommand(@NotNull AttributesType type)
{
this.type = Preconditions.checkNotNull(type);
}
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
JSONObject result;
if (type == AttributesType.APPLICATION) {
result = TypeDiscoverer.getAppAttributes();
}
else if (type == AttributesType.OPERATOR) {
result = TypeDiscoverer.getOperatorAttributes();
}
else {
//get port attributes
result = TypeDiscoverer.getPortAttributes();
}
printJson(result);
}
}
@SuppressWarnings("static-access")
public static class GetPhysicalPropertiesCommandLineOptions
{
final Options options = new Options();
final Option propertyName = add(OptionBuilder.withArgName("property name").hasArg().withDescription("The name of the property whose value needs to be retrieved").create("propertyName"));
final Option waitTime = add (OptionBuilder.withArgName("wait time").hasArg().withDescription("How long to wait to get the result").create("waitTime"));
private Option add(Option opt)
{
this.options.addOption(opt);
return opt;
}
}
private static GetPhysicalPropertiesCommandLineOptions GET_PHYSICAL_PROPERTY_OPTIONS = new GetPhysicalPropertiesCommandLineOptions();
@SuppressWarnings("static-access")
public static class LaunchCommandLineOptions
{
final Options options = new Options();
final Option local = add(new Option("local", "Run application in local mode."));
final Option configFile = add(OptionBuilder.withArgName("configuration file").hasArg().withDescription("Specify an application configuration file.").create("conf"));
final Option apConfigFile = add(OptionBuilder.withArgName("app package configuration file").hasArg().withDescription("Specify an application configuration file within the app package if launching an app package.").create("apconf"));
final Option defProperty = add(OptionBuilder.withArgName("property=value").hasArg().withDescription("Use value for given property.").create("D"));
final Option libjars = add(OptionBuilder.withArgName("comma separated list of libjars").hasArg().withDescription("Specify comma separated jar files or other resource files to include in the classpath.").create("libjars"));
final Option files = add(OptionBuilder.withArgName("comma separated list of files").hasArg().withDescription("Specify comma separated files to be copied on the compute machines.").create("files"));
final Option archives = add(OptionBuilder.withArgName("comma separated list of archives").hasArg().withDescription("Specify comma separated archives to be unarchived on the compute machines.").create("archives"));
final Option ignorePom = add(new Option("ignorepom", "Do not run maven to find the dependency"));
final Option originalAppID = add(OptionBuilder.withArgName("application id").hasArg().withDescription("Specify original application identifier for restart.").create("originalAppId"));
final Option exactMatch = add(new Option("exactMatch", "Only consider applications with exact app name"));
final Option queue = add(OptionBuilder.withArgName("queue name").hasArg().withDescription("Specify the queue to launch the application").create("queue"));
private Option add(Option opt)
{
this.options.addOption(opt);
return opt;
}
}
private static LaunchCommandLineOptions LAUNCH_OPTIONS = new LaunchCommandLineOptions();
static LaunchCommandLineInfo getLaunchCommandLineInfo(String[] args) throws ParseException
{
CommandLineParser parser = new PosixParser();
LaunchCommandLineInfo result = new LaunchCommandLineInfo();
CommandLine line = parser.parse(LAUNCH_OPTIONS.options, args);
result.localMode = line.hasOption(LAUNCH_OPTIONS.local.getOpt());
result.configFile = line.getOptionValue(LAUNCH_OPTIONS.configFile.getOpt());
result.apConfigFile = line.getOptionValue(LAUNCH_OPTIONS.apConfigFile.getOpt());
result.ignorePom = line.hasOption(LAUNCH_OPTIONS.ignorePom.getOpt());
String[] defs = line.getOptionValues(LAUNCH_OPTIONS.defProperty.getOpt());
if (defs != null) {
result.overrideProperties = new HashMap<String, String>();
for (String def : defs) {
int equal = def.indexOf('=');
if (equal < 0) {
result.overrideProperties.put(def, null);
}
else {
result.overrideProperties.put(def.substring(0, equal), def.substring(equal + 1));
}
}
}
result.libjars = line.getOptionValue(LAUNCH_OPTIONS.libjars.getOpt());
result.archives = line.getOptionValue(LAUNCH_OPTIONS.archives.getOpt());
result.files = line.getOptionValue(LAUNCH_OPTIONS.files.getOpt());
result.queue = line.getOptionValue(LAUNCH_OPTIONS.queue.getOpt());
result.args = line.getArgs();
result.origAppId = line.getOptionValue(LAUNCH_OPTIONS.originalAppID.getOpt());
result.exactMatch = line.hasOption("exactMatch");
return result;
}
static class LaunchCommandLineInfo
{
boolean localMode;
boolean ignorePom;
String configFile;
String apConfigFile;
Map<String, String> overrideProperties;
String libjars;
String files;
String queue;
String archives;
String origAppId;
boolean exactMatch;
String[] args;
}
@SuppressWarnings("static-access")
public static Options getShowLogicalPlanCommandLineOptions()
{
Options options = new Options();
Option libjars = OptionBuilder.withArgName("comma separated list of jars").hasArg().withDescription("Specify comma separated jar/resource files to include in the classpath.").create("libjars");
Option ignorePom = new Option("ignorepom", "Do not run maven to find the dependency");
Option exactMatch = new Option("exactMatch", "Only consider exact match for app name");
options.addOption(libjars);
options.addOption(ignorePom);
options.addOption(exactMatch);
return options;
}
private static ShowLogicalPlanCommandLineInfo getShowLogicalPlanCommandLineInfo(String[] args) throws ParseException
{
CommandLineParser parser = new PosixParser();
ShowLogicalPlanCommandLineInfo result = new ShowLogicalPlanCommandLineInfo();
CommandLine line = parser.parse(getShowLogicalPlanCommandLineOptions(), args);
result.libjars = line.getOptionValue("libjars");
result.ignorePom = line.hasOption("ignorepom");
result.args = line.getArgs();
result.exactMatch = line.hasOption("exactMatch");
return result;
}
private static class ShowLogicalPlanCommandLineInfo
{
String libjars;
boolean ignorePom;
String[] args;
boolean exactMatch;
}
public void mainHelper() throws Exception
{
init();
run();
System.exit(lastCommandError ? 1 : 0);
}
public static void main(final String[] args) throws Exception
{
final DTCli shell = new DTCli();
shell.preImpersonationInit(args);
String hadoopUserName = System.getenv("HADOOP_USER_NAME");
if (UserGroupInformation.isSecurityEnabled()
&& StringUtils.isNotBlank(hadoopUserName)
&& !hadoopUserName.equals(UserGroupInformation.getLoginUser().getUserName())) {
LOG.info("You ({}) are running as user {}", UserGroupInformation.getLoginUser().getUserName(), hadoopUserName);
UserGroupInformation ugi
= UserGroupInformation.createProxyUser(hadoopUserName, UserGroupInformation.getLoginUser());
ugi.doAs(new PrivilegedExceptionAction<Void>()
{
@Override
public Void run() throws Exception
{
shell.mainHelper();
return null;
}
});
}
else {
shell.mainHelper();
}
}
}
|
engine/src/main/java/com/datatorrent/stram/cli/DTCli.java
|
/**
* Copyright (C) 2015 DataTorrent, 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.datatorrent.stram.cli;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.security.PrivilegedExceptionAction;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import javax.validation.constraints.NotNull;
import javax.ws.rs.core.MediaType;
import jline.console.ConsoleReader;
import jline.console.completer.*;
import jline.console.history.FileHistory;
import jline.console.history.History;
import jline.console.history.MemoryHistory;
import org.apache.commons.cli.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.YarnApplicationState;
import org.apache.hadoop.yarn.client.api.YarnClient;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.tools.ant.DirectoryScanner;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Signal;
import sun.misc.SignalHandler;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
import com.sun.jersey.api.client.WebResource;
import com.datatorrent.api.Context;
import com.datatorrent.api.Operator;
import com.datatorrent.api.StreamingApplication;
import com.datatorrent.stram.StramClient;
import com.datatorrent.stram.client.*;
import com.datatorrent.stram.client.AppPackage.AppInfo;
import com.datatorrent.stram.client.DTConfiguration.Scope;
import com.datatorrent.stram.client.RecordingsAgent.RecordingInfo;
import com.datatorrent.stram.client.StramAppLauncher.AppFactory;
import com.datatorrent.stram.client.StramClientUtils.ClientRMHelper;
import com.datatorrent.stram.codec.LogicalPlanSerializer;
import com.datatorrent.stram.plan.logical.LogicalPlan;
import com.datatorrent.stram.plan.logical.requests.*;
import com.datatorrent.stram.security.StramUserLogin;
import com.datatorrent.stram.util.JSONSerializationProvider;
import com.datatorrent.stram.util.ObjectMapperFactory;
import com.datatorrent.stram.util.VersionInfo;
import com.datatorrent.stram.util.WebServicesClient;
import com.datatorrent.stram.webapp.OperatorDiscoverer;
import com.datatorrent.stram.webapp.StramWebServices;
import com.datatorrent.stram.webapp.TypeDiscoverer;
import net.lingala.zip4j.exception.ZipException;
/**
* Provides command line interface for a streaming application on hadoop (yarn)
* <p>
*
* @since 0.3.2
*/
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public class DTCli
{
private static final Logger LOG = LoggerFactory.getLogger(DTCli.class);
private Configuration conf;
private FileSystem fs;
private StramAgent stramAgent;
private final YarnClient yarnClient = YarnClient.createYarnClient();
private ApplicationReport currentApp = null;
private boolean consolePresent;
private String[] commandsToExecute;
private final Map<String, CommandSpec> globalCommands = new TreeMap<String, CommandSpec>();
private final Map<String, CommandSpec> connectedCommands = new TreeMap<String, CommandSpec>();
private final Map<String, CommandSpec> logicalPlanChangeCommands = new TreeMap<String, CommandSpec>();
private final Map<String, String> aliases = new HashMap<String, String>();
private final Map<String, List<String>> macros = new HashMap<String, List<String>>();
private boolean changingLogicalPlan = false;
private final List<LogicalPlanRequest> logicalPlanRequestQueue = new ArrayList<LogicalPlanRequest>();
private FileHistory topLevelHistory;
private FileHistory changingLogicalPlanHistory;
private String jsonp;
private boolean raw = false;
private RecordingsAgent recordingsAgent;
private final ObjectMapper mapper = new JSONSerializationProvider().getContext(null);
private String pagerCommand;
private Process pagerProcess;
private int verboseLevel = 0;
private final Tokenizer tokenizer = new Tokenizer();
private final Map<String, String> variableMap = new HashMap<String, String>();
private static boolean lastCommandError = false;
private Thread mainThread;
private Thread commandThread;
private String prompt;
private String forcePrompt;
private String kerberosPrincipal;
private String kerberosKeyTab;
private static class FileLineReader extends ConsoleReader
{
private final BufferedReader br;
FileLineReader(String fileName) throws IOException
{
super();
fileName = expandFileName(fileName, true);
br = new BufferedReader(new FileReader(fileName));
}
@Override
public String readLine(String prompt) throws IOException
{
return br.readLine();
}
@Override
public String readLine(String prompt, Character mask) throws IOException
{
return br.readLine();
}
@Override
public String readLine(Character mask) throws IOException
{
return br.readLine();
}
public void close() throws IOException
{
br.close();
}
}
public class Tokenizer
{
private void appendToCommandBuffer(List<String> commandBuffer, StringBuffer buf, boolean potentialEmptyArg)
{
if (potentialEmptyArg || buf.length() > 0) {
commandBuffer.add(buf.toString());
buf.setLength(0);
}
}
private List<String> startNewCommand(LinkedList<List<String>> resultBuffer)
{
List<String> newCommand = new ArrayList<String>();
if (!resultBuffer.isEmpty()) {
List<String> lastCommand = resultBuffer.peekLast();
if (lastCommand.size() == 1) {
String first = lastCommand.get(0);
if (first.matches("^[A-Za-z][A-Za-z0-9]*=.*")) {
// This is a variable assignment
int equalSign = first.indexOf('=');
variableMap.put(first.substring(0, equalSign), first.substring(equalSign + 1));
resultBuffer.removeLast();
}
}
}
resultBuffer.add(newCommand);
return newCommand;
}
public List<String[]> tokenize(String commandLine)
{
LinkedList<List<String>> resultBuffer = new LinkedList<List<String>>();
List<String> commandBuffer = startNewCommand(resultBuffer);
if (commandLine != null) {
commandLine = ltrim(commandLine);
if (commandLine.startsWith("#")) {
return null;
}
int len = commandLine.length();
boolean insideQuotes = false;
boolean potentialEmptyArg = false;
StringBuffer buf = new StringBuffer(commandLine.length());
for (@SuppressWarnings("AssignmentToForLoopParameter") int i = 0; i < len; ++i) {
char c = commandLine.charAt(i);
if (c == '"') {
potentialEmptyArg = true;
insideQuotes = !insideQuotes;
}
else if (c == '\\') {
if (len > i + 1) {
switch (commandLine.charAt(i + 1)) {
case 'n':
buf.append("\n");
break;
case 't':
buf.append("\t");
break;
case 'r':
buf.append("\r");
break;
case 'b':
buf.append("\b");
break;
case 'f':
buf.append("\f");
break;
default:
buf.append(commandLine.charAt(i + 1));
}
++i;
}
}
else {
if (insideQuotes) {
buf.append(c);
}
else {
if (c == '$') {
StringBuilder variableName = new StringBuilder(32);
if (len > i + 1) {
if (commandLine.charAt(i + 1) == '{') {
++i;
while (len > i + 1) {
char ch = commandLine.charAt(i + 1);
if (ch != '}') {
variableName.append(ch);
}
++i;
if (ch == '}') {
break;
}
if (len <= i + 1) {
throw new CliException("Parse error: unmatched brace");
}
}
} else if (commandLine.charAt(i + 1) == '?') {
++i;
buf.append(lastCommandError ? "1" : "0");
continue;
} else {
while (len > i + 1) {
char ch = commandLine.charAt(i + 1);
if ((variableName.length() > 0 && ch >= '0' && ch <= '9') || ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) {
variableName.append(ch);
}
else {
break;
}
++i;
}
}
if (variableName.length() == 0) {
buf.append(c);
}
else {
String value = variableMap.get(variableName.toString());
if (value != null) {
buf.append(value);
}
}
}
else {
buf.append(c);
}
}
else if (c == ';') {
appendToCommandBuffer(commandBuffer, buf, potentialEmptyArg);
commandBuffer = startNewCommand(resultBuffer);
}
else if (Character.isWhitespace(c)) {
appendToCommandBuffer(commandBuffer, buf, potentialEmptyArg);
potentialEmptyArg = false;
if (len > i + 1 && commandLine.charAt(i + 1) == '#') {
break;
}
}
else {
buf.append(c);
}
}
}
}
appendToCommandBuffer(commandBuffer, buf, potentialEmptyArg);
}
startNewCommand(resultBuffer);
List<String[]> result = new ArrayList<String[]>();
for (List<String> command : resultBuffer) {
String[] commandArray = new String[command.size()];
result.add(command.toArray(commandArray));
}
return result;
}
}
private interface Command
{
void execute(String[] args, ConsoleReader reader) throws Exception;
}
private static class Arg
{
final String name;
Arg(String name)
{
this.name = name;
}
@Override
public String toString()
{
return name;
}
}
private static class FileArg extends Arg
{
FileArg(String name)
{
super(name);
}
}
// VarArg must be in optional argument and must be at the end
private static class VarArg extends Arg
{
VarArg(String name)
{
super(name);
}
}
private static class CommandArg extends Arg
{
CommandArg(String name)
{
super(name);
}
}
protected PrintStream suppressOutput()
{
PrintStream originalStream = System.out;
if (raw) {
PrintStream dummyStream = new PrintStream(new OutputStream()
{
@Override
public void write(int b)
{
// no-op
}
});
System.setOut(dummyStream);
}
return originalStream;
}
protected void restoreOutput(PrintStream originalStream)
{
if (raw) {
System.setOut(originalStream);
}
}
AppPackage newAppPackageInstance(File f) throws IOException, ZipException
{
PrintStream outputStream = suppressOutput();
try {
return new AppPackage(f, true);
} finally {
restoreOutput(outputStream);
}
}
@SuppressWarnings("unused")
private StramAppLauncher getStramAppLauncher(String jarfileUri, Configuration config, boolean ignorePom) throws Exception
{
URI uri = new URI(jarfileUri);
String scheme = uri.getScheme();
StramAppLauncher appLauncher = null;
if (scheme == null || scheme.equals("file")) {
File jf = new File(uri.getPath());
appLauncher = new StramAppLauncher(jf, config);
}
else {
FileSystem tmpFs = FileSystem.newInstance(uri, conf);
try {
Path path = new Path(uri.getPath());
appLauncher = new StramAppLauncher(tmpFs, path, config);
}
finally {
tmpFs.close();
}
}
if (appLauncher != null) {
if (verboseLevel > 0) {
System.err.print(appLauncher.getMvnBuildClasspathOutput());
}
return appLauncher;
}
else {
throw new CliException("Scheme " + scheme + " not supported.");
}
}
private static class CommandSpec
{
Command command;
Arg[] requiredArgs;
Arg[] optionalArgs;
String description;
CommandSpec(Command command, Arg[] requiredArgs, Arg[] optionalArgs, String description)
{
this.command = command;
this.requiredArgs = requiredArgs;
this.optionalArgs = optionalArgs;
this.description = description;
}
void verifyArguments(String[] args) throws CliException
{
int minArgs = 0;
int maxArgs = 0;
if (requiredArgs != null) {
minArgs = requiredArgs.length;
maxArgs = requiredArgs.length;
}
if (optionalArgs != null) {
for (Arg arg : optionalArgs) {
if (arg instanceof VarArg) {
maxArgs = Integer.MAX_VALUE;
break;
} else {
maxArgs++;
}
}
}
if (args.length - 1 < minArgs || args.length - 1 > maxArgs) {
throw new CliException("Command parameter error");
}
}
void printUsage(String cmd)
{
System.err.print("Usage: " + cmd);
if (requiredArgs != null) {
for (Arg arg : requiredArgs) {
System.err.print(" <" + arg + ">");
}
}
if (optionalArgs != null) {
for (Arg arg : optionalArgs) {
if (arg instanceof VarArg) {
System.err.print(" [<" + arg + "> ... ]");
} else {
System.err.print(" [<" + arg + ">]");
}
}
}
System.err.println();
}
}
private static class OptionsCommandSpec extends CommandSpec
{
Options options;
OptionsCommandSpec(Command command, Arg[] requiredArgs, Arg[] optionalArgs, String description, Options options)
{
super(command, requiredArgs, optionalArgs, description);
this.options = options;
}
@Override
void verifyArguments(String[] args) throws CliException
{
try {
args = new PosixParser().parse(options, args).getArgs();
super.verifyArguments(args);
}
catch (Exception ex) {
throw new CliException("Command parameter error");
}
}
@Override
void printUsage(String cmd)
{
super.printUsage(cmd + ((options == null) ? "" : " [options]"));
if (options != null) {
System.out.println("Options:");
HelpFormatter formatter = new HelpFormatter();
PrintWriter pw = new PrintWriter(System.out);
formatter.printOptions(pw, 80, options, 4, 4);
pw.flush();
}
}
}
DTCli()
{
//
// Global command specification starts here
//
globalCommands.put("help", new CommandSpec(new HelpCommand(),
null,
new Arg[]{new CommandArg("command")},
"Show help"));
globalCommands.put("echo", new CommandSpec(new EchoCommand(),
null, new Arg[]{new VarArg("arg")},
"Echo the arguments"));
globalCommands.put("connect", new CommandSpec(new ConnectCommand(),
new Arg[]{new Arg("app-id")},
null,
"Connect to an app"));
globalCommands.put("launch", new OptionsCommandSpec(new LaunchCommand(),
new Arg[]{new FileArg("jar-file/json-file/properties-file/app-package-file")},
new Arg[]{new Arg("matching-app-name")},
"Launch an app", LAUNCH_OPTIONS.options));
globalCommands.put("shutdown-app", new CommandSpec(new ShutdownAppCommand(),
new Arg[]{new Arg("app-id")},
new Arg[]{new VarArg("app-id")},
"Shutdown an app"));
globalCommands.put("list-apps", new CommandSpec(new ListAppsCommand(),
null,
new Arg[]{new Arg("pattern")},
"List applications"));
globalCommands.put("kill-app", new CommandSpec(new KillAppCommand(),
new Arg[]{new Arg("app-id")},
new Arg[]{new VarArg("app-id")},
"Kill an app"));
globalCommands.put("show-logical-plan", new OptionsCommandSpec(new ShowLogicalPlanCommand(),
new Arg[]{new FileArg("jar-file/app-package-file")},
new Arg[]{new Arg("class-name")},
"List apps in a jar or show logical plan of an app class",
getShowLogicalPlanCommandLineOptions()));
globalCommands.put("get-jar-operator-classes", new OptionsCommandSpec(new GetJarOperatorClassesCommand(),
new Arg[]{new FileArg("jar-files-comma-separated")},
new Arg[]{new Arg("search-term")},
"List operators in a jar list",
GET_OPERATOR_CLASSES_OPTIONS.options));
globalCommands.put("get-jar-operator-properties", new CommandSpec(new GetJarOperatorPropertiesCommand(),
new Arg[]{new FileArg("jar-files-comma-separated"), new Arg("operator-class-name")},
null,
"List properties in specified operator"));
globalCommands.put("alias", new CommandSpec(new AliasCommand(),
new Arg[]{new Arg("alias-name"), new CommandArg("command")},
null,
"Create a command alias"));
globalCommands.put("source", new CommandSpec(new SourceCommand(),
new Arg[]{new FileArg("file")},
null,
"Execute the commands in a file"));
globalCommands.put("exit", new CommandSpec(new ExitCommand(),
null,
null,
"Exit the CLI"));
globalCommands.put("begin-macro", new CommandSpec(new BeginMacroCommand(),
new Arg[]{new Arg("name")},
null,
"Begin Macro Definition ($1...$9 to access parameters and type 'end' to end the definition)"));
globalCommands.put("dump-properties-file", new CommandSpec(new DumpPropertiesFileCommand(),
new Arg[]{new FileArg("out-file"), new FileArg("jar-file"), new Arg("class-name")},
null,
"Dump the properties file of an app class"));
globalCommands.put("get-app-info", new CommandSpec(new GetAppInfoCommand(),
new Arg[]{new Arg("app-id")},
null,
"Get the information of an app"));
globalCommands.put("set-pager", new CommandSpec(new SetPagerCommand(),
new Arg[]{new Arg("on/off")},
null,
"Set the pager program for output"));
globalCommands.put("get-config-parameter", new CommandSpec(new GetConfigParameterCommand(),
null,
new Arg[]{new FileArg("parameter-name")},
"Get the configuration parameter"));
globalCommands.put("get-app-package-info", new CommandSpec(new GetAppPackageInfoCommand(),
new Arg[]{new FileArg("app-package-file")},
null,
"Get info on the app package file"));
globalCommands.put("get-app-package-operators", new OptionsCommandSpec(new GetAppPackageOperatorsCommand(),
new Arg[]{new FileArg("app-package-file")},
new Arg[]{new Arg("search-term")},
"Get operators within the given app package",
GET_OPERATOR_CLASSES_OPTIONS.options));
globalCommands.put("get-app-package-operator-properties", new CommandSpec(new GetAppPackageOperatorPropertiesCommand(),
new Arg[]{new FileArg("app-package-file"), new Arg("operator-class")},
null,
"Get operator properties within the given app package"));
globalCommands.put("list-application-attributes", new CommandSpec(new ListAttributesCommand(AttributesType.APPLICATION),
null, null, "Lists the application attributes"));
globalCommands.put("list-operator-attributes", new CommandSpec(new ListAttributesCommand(AttributesType.OPERATOR),
null, null, "Lists the operator attributes"));
globalCommands.put("list-port-attributes", new CommandSpec(new ListAttributesCommand(AttributesType.PORT), null, null,
"Lists the port attributes"));
//
// Connected command specification starts here
//
connectedCommands.put("list-containers", new CommandSpec(new ListContainersCommand(),
null,
null,
"List containers"));
connectedCommands.put("list-operators", new CommandSpec(new ListOperatorsCommand(),
null,
new Arg[]{new Arg("pattern")},
"List operators"));
connectedCommands.put("show-physical-plan", new CommandSpec(new ShowPhysicalPlanCommand(),
null,
null,
"Show physical plan"));
connectedCommands.put("kill-container", new CommandSpec(new KillContainerCommand(),
new Arg[]{new Arg("container-id")},
new Arg[]{new VarArg("container-id")},
"Kill a container"));
connectedCommands.put("shutdown-app", new CommandSpec(new ShutdownAppCommand(),
null,
new Arg[]{new VarArg("app-id")},
"Shutdown an app"));
connectedCommands.put("kill-app", new CommandSpec(new KillAppCommand(),
null,
new Arg[]{new VarArg("app-id")},
"Kill an app"));
connectedCommands.put("wait", new CommandSpec(new WaitCommand(),
new Arg[]{new Arg("timeout")},
null,
"Wait for completion of current application"));
connectedCommands.put("start-recording", new CommandSpec(new StartRecordingCommand(),
new Arg[]{new Arg("operator-id")},
new Arg[]{new Arg("port-name"), new Arg("num-windows")},
"Start recording"));
connectedCommands.put("stop-recording", new CommandSpec(new StopRecordingCommand(),
new Arg[]{new Arg("operator-id")},
new Arg[]{new Arg("port-name")},
"Stop recording"));
connectedCommands.put("get-operator-attributes", new CommandSpec(new GetOperatorAttributesCommand(),
new Arg[]{new Arg("operator-name")},
new Arg[]{new Arg("attribute-name")},
"Get attributes of an operator"));
connectedCommands.put("get-operator-properties", new CommandSpec(new GetOperatorPropertiesCommand(),
new Arg[]{new Arg("operator-name")},
new Arg[]{new Arg("property-name")},
"Get properties of a logical operator"));
connectedCommands.put("get-physical-operator-properties", new OptionsCommandSpec(new GetPhysicalOperatorPropertiesCommand(),
new Arg[]{new Arg("operator-id")},
null,
"Get properties of a physical operator", GET_PHYSICAL_PROPERTY_OPTIONS.options));
connectedCommands.put("set-operator-property", new CommandSpec(new SetOperatorPropertyCommand(),
new Arg[]{new Arg("operator-name"), new Arg("property-name"), new Arg("property-value")},
null,
"Set a property of an operator"));
connectedCommands.put("set-physical-operator-property", new CommandSpec(new SetPhysicalOperatorPropertyCommand(),
new Arg[]{new Arg("operator-id"), new Arg("property-name"), new Arg("property-value")},
null,
"Set a property of an operator"));
connectedCommands.put("get-app-attributes", new CommandSpec(new GetAppAttributesCommand(),
null,
new Arg[]{new Arg("attribute-name")},
"Get attributes of the connected app"));
connectedCommands.put("get-port-attributes", new CommandSpec(new GetPortAttributesCommand(),
new Arg[]{new Arg("operator-name"), new Arg("port-name")},
new Arg[]{new Arg("attribute-name")},
"Get attributes of a port"));
connectedCommands.put("begin-logical-plan-change", new CommandSpec(new BeginLogicalPlanChangeCommand(),
null,
null,
"Begin Logical Plan Change"));
connectedCommands.put("show-logical-plan", new OptionsCommandSpec(new ShowLogicalPlanCommand(),
null,
new Arg[]{new FileArg("jar-file/app-package-file"), new Arg("class-name")},
"Show logical plan of an app class",
getShowLogicalPlanCommandLineOptions()));
connectedCommands.put("dump-properties-file", new CommandSpec(new DumpPropertiesFileCommand(),
new Arg[]{new FileArg("out-file")},
new Arg[]{new FileArg("jar-file"), new Arg("class-name")},
"Dump the properties file of an app class"));
connectedCommands.put("get-app-info", new CommandSpec(new GetAppInfoCommand(),
null,
new Arg[]{new Arg("app-id")},
"Get the information of an app"));
connectedCommands.put("get-recording-info", new CommandSpec(new GetRecordingInfoCommand(),
null,
new Arg[]{new Arg("operator-id"), new Arg("start-time")},
"Get tuple recording info"));
//
// Logical plan change command specification starts here
//
logicalPlanChangeCommands.put("help", new CommandSpec(new HelpCommand(),
null,
new Arg[]{new Arg("command")},
"Show help"));
logicalPlanChangeCommands.put("create-operator", new CommandSpec(new CreateOperatorCommand(),
new Arg[]{new Arg("operator-name"), new Arg("class-name")},
null,
"Create an operator"));
logicalPlanChangeCommands.put("create-stream", new CommandSpec(new CreateStreamCommand(),
new Arg[]{new Arg("stream-name"), new Arg("from-operator-name"), new Arg("from-port-name"), new Arg("to-operator-name"), new Arg("to-port-name")},
null,
"Create a stream"));
logicalPlanChangeCommands.put("add-stream-sink", new CommandSpec(new AddStreamSinkCommand(),
new Arg[]{new Arg("stream-name"), new Arg("to-operator-name"), new Arg("to-port-name")},
null,
"Add a sink to an existing stream"));
logicalPlanChangeCommands.put("remove-operator", new CommandSpec(new RemoveOperatorCommand(),
new Arg[]{new Arg("operator-name")},
null,
"Remove an operator"));
logicalPlanChangeCommands.put("remove-stream", new CommandSpec(new RemoveStreamCommand(),
new Arg[]{new Arg("stream-name")},
null,
"Remove a stream"));
logicalPlanChangeCommands.put("set-operator-property", new CommandSpec(new SetOperatorPropertyCommand(),
new Arg[]{new Arg("operator-name"), new Arg("property-name"), new Arg("property-value")},
null,
"Set a property of an operator"));
logicalPlanChangeCommands.put("set-operator-attribute", new CommandSpec(new SetOperatorAttributeCommand(),
new Arg[]{new Arg("operator-name"), new Arg("attr-name"), new Arg("attr-value")},
null,
"Set an attribute of an operator"));
logicalPlanChangeCommands.put("set-port-attribute", new CommandSpec(new SetPortAttributeCommand(),
new Arg[]{new Arg("operator-name"), new Arg("port-name"), new Arg("attr-name"), new Arg("attr-value")},
null,
"Set an attribute of a port"));
logicalPlanChangeCommands.put("set-stream-attribute", new CommandSpec(new SetStreamAttributeCommand(),
new Arg[]{new Arg("stream-name"), new Arg("attr-name"), new Arg("attr-value")},
null,
"Set an attribute of a stream"));
logicalPlanChangeCommands.put("show-queue", new CommandSpec(new ShowQueueCommand(),
null,
null,
"Show the queue of the plan change"));
logicalPlanChangeCommands.put("submit", new CommandSpec(new SubmitCommand(),
null,
null,
"Submit the plan change"));
logicalPlanChangeCommands.put("abort", new CommandSpec(new AbortCommand(),
null,
null,
"Abort the plan change"));
}
private void printJson(String json) throws IOException
{
PrintStream os = getOutputPrintStream();
if (jsonp != null) {
os.println(jsonp + "(" + json + ");");
}
else {
os.println(json);
}
os.flush();
closeOutputPrintStream(os);
}
private void printJson(JSONObject json) throws JSONException, IOException
{
printJson(raw ? json.toString() : json.toString(2));
}
private void printJson(JSONArray jsonArray, String name) throws JSONException, IOException
{
JSONObject json = new JSONObject();
json.put(name, jsonArray);
printJson(json);
}
private <K, V> void printJson(Map<K, V> map) throws IOException, JSONException
{
printJson(new JSONObject(mapper.writeValueAsString(map)));
}
private <T> void printJson(List<T> list, String name) throws IOException, JSONException
{
printJson(new JSONArray(mapper.writeValueAsString(list)), name);
}
private PrintStream getOutputPrintStream() throws IOException
{
if (pagerCommand == null) {
pagerProcess = null;
return System.out;
}
else {
pagerProcess = Runtime.getRuntime().exec(new String[]{"sh", "-c",
pagerCommand + " >/dev/tty"});
return new PrintStream(pagerProcess.getOutputStream());
}
}
private void closeOutputPrintStream(PrintStream os)
{
if (os != System.out) {
os.close();
try {
pagerProcess.waitFor();
}
catch (InterruptedException ex) {
LOG.debug("Interrupted");
}
}
}
private static String expandFileName(String fileName, boolean expandWildCard) throws IOException
{
if (fileName.matches("^[a-zA-Z]+:.*")) {
// it's a URL
return fileName;
}
// TODO: need to work with other users' home directory
if (fileName.startsWith("~" + File.separator)) {
fileName = System.getProperty("user.home") + fileName.substring(1);
}
fileName = new File(fileName).getCanonicalPath();
//LOG.debug("Canonical path: {}", fileName);
if (expandWildCard) {
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{fileName});
scanner.scan();
String[] files = scanner.getIncludedFiles();
if (files.length == 0) {
throw new CliException(fileName + " does not match any file");
}
else if (files.length > 1) {
throw new CliException(fileName + " matches more than one file");
}
return files[0];
}
else {
return fileName;
}
}
private static String[] expandFileNames(String fileName) throws IOException
{
// TODO: need to work with other users
if (fileName.matches("^[a-zA-Z]+:.*")) {
// it's a URL
return new String[]{fileName};
}
if (fileName.startsWith("~" + File.separator)) {
fileName = System.getProperty("user.home") + fileName.substring(1);
}
fileName = new File(fileName).getCanonicalPath();
LOG.debug("Canonical path: {}", fileName);
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{fileName});
scanner.scan();
return scanner.getIncludedFiles();
}
private static String expandCommaSeparatedFiles(String filenames) throws IOException
{
String[] entries = filenames.split(",");
StringBuilder result = new StringBuilder(filenames.length());
for (String entry : entries) {
for (String file : expandFileNames(entry)) {
if (result.length() > 0) {
result.append(",");
}
result.append(file);
}
}
if (result.length() == 0) {
return null;
}
return result.toString();
}
protected ApplicationReport getApplication(String appId)
{
List<ApplicationReport> appList = getApplicationList();
if (StringUtils.isNumeric(appId)) {
int appSeq = Integer.parseInt(appId);
for (ApplicationReport ar : appList) {
if (ar.getApplicationId().getId() == appSeq) {
return ar;
}
}
}
else {
for (ApplicationReport ar : appList) {
if (ar.getApplicationId().toString().equals(appId)) {
return ar;
}
}
}
return null;
}
private static class CliException extends RuntimeException
{
private static final long serialVersionUID = 1L;
CliException(String msg, Throwable cause)
{
super(msg, cause);
}
CliException(String msg)
{
super(msg);
}
}
public void preImpersonationInit(String[] args) throws IOException
{
Signal.handle(new Signal("INT"), new SignalHandler()
{
@Override
public void handle(Signal sig)
{
System.out.println("^C");
if (commandThread != null) {
commandThread.interrupt();
mainThread.interrupt();
}
else {
System.out.print(prompt);
System.out.flush();
}
}
});
consolePresent = (System.console() != null);
Options options = new Options();
options.addOption("e", true, "Commands are read from the argument");
options.addOption("v", false, "Verbose mode level 1");
options.addOption("vv", false, "Verbose mode level 2");
options.addOption("vvv", false, "Verbose mode level 3");
options.addOption("vvvv", false, "Verbose mode level 4");
options.addOption("r", false, "JSON Raw mode");
options.addOption("p", true, "JSONP padding function");
options.addOption("h", false, "Print this help");
options.addOption("f", true, "Use the specified prompt at all time");
options.addOption("kp", true, "Use the specified kerberos principal");
options.addOption("kt", true, "Use the specified kerberos keytab");
CommandLineParser parser = new BasicParser();
try {
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("v")) {
verboseLevel = 1;
}
if (cmd.hasOption("vv")) {
verboseLevel = 2;
}
if (cmd.hasOption("vvv")) {
verboseLevel = 3;
}
if (cmd.hasOption("vvvv")) {
verboseLevel = 4;
}
if (cmd.hasOption("r")) {
raw = true;
}
if (cmd.hasOption("e")) {
commandsToExecute = cmd.getOptionValues("e");
consolePresent = false;
}
if (cmd.hasOption("p")) {
jsonp = cmd.getOptionValue("p");
}
if (cmd.hasOption("f")) {
forcePrompt = cmd.getOptionValue("f");
}
if (cmd.hasOption("h")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(DTCli.class.getSimpleName(), options);
System.exit(0);
}
if (cmd.hasOption("kp")) {
kerberosPrincipal = cmd.getOptionValue("kp");
}
if (cmd.hasOption("kt")) {
kerberosKeyTab = cmd.getOptionValue("kt");
}
}
catch (ParseException ex) {
System.err.println("Invalid argument: " + ex);
System.exit(1);
}
if (kerberosPrincipal == null && kerberosKeyTab != null) {
System.err.println("Kerberos key tab is specified but not the kerberos principal. Please specify it using the -kp option.");
System.exit(1);
}
if (kerberosPrincipal != null && kerberosKeyTab == null) {
System.err.println("Kerberos principal is specified but not the kerberos key tab. Please specify it using the -kt option.");
System.exit(1);
}
Level logLevel;
switch (verboseLevel) {
case 0:
logLevel = Level.OFF;
break;
case 1:
logLevel = Level.ERROR;
break;
case 2:
logLevel = Level.WARN;
break;
case 3:
logLevel = Level.INFO;
break;
default:
logLevel = Level.DEBUG;
break;
}
for (org.apache.log4j.Logger logger : new org.apache.log4j.Logger[]{org.apache.log4j.Logger.getRootLogger(),
org.apache.log4j.Logger.getLogger(DTCli.class)}) {
@SuppressWarnings("unchecked")
Enumeration<Appender> allAppenders = logger.getAllAppenders();
while (allAppenders.hasMoreElements()) {
Appender appender = allAppenders.nextElement();
if (appender instanceof ConsoleAppender) {
((ConsoleAppender) appender).setThreshold(logLevel);
}
}
}
if (commandsToExecute != null) {
for (String command : commandsToExecute) {
LOG.debug("Command to be executed: {}", command);
}
}
if (kerberosPrincipal != null && kerberosKeyTab != null) {
StramUserLogin.authenticate(kerberosPrincipal, kerberosKeyTab);
} else {
Configuration config = new YarnConfiguration();
StramClientUtils.addDTLocalResources(config);
StramUserLogin.attemptAuthentication(config);
}
}
public void init() throws IOException
{
conf = StramClientUtils.addDTSiteResources(new YarnConfiguration());
fs = StramClientUtils.newFileSystemInstance(conf);
stramAgent = new StramAgent(fs, conf);
yarnClient.init(conf);
yarnClient.start();
LOG.debug("Yarn Client initialized and started");
String socks = conf.get(CommonConfigurationKeysPublic.HADOOP_SOCKS_SERVER_KEY);
if (socks != null) {
int colon = socks.indexOf(':');
if (colon > 0) {
LOG.info("Using socks proxy at {}", socks);
System.setProperty("socksProxyHost", socks.substring(0, colon));
System.setProperty("socksProxyPort", socks.substring(colon + 1));
}
}
}
private void processSourceFile(String fileName, ConsoleReader reader) throws FileNotFoundException, IOException
{
fileName = expandFileName(fileName, true);
LOG.debug("Sourcing {}", fileName);
boolean consolePresentSaved = consolePresent;
consolePresent = false;
FileLineReader fr = null;
String line;
try {
fr = new FileLineReader(fileName);
while ((line = fr.readLine("")) != null) {
processLine(line, fr, true);
}
}
finally {
consolePresent = consolePresentSaved;
if (fr != null) {
fr.close();
}
}
}
private final static class MyNullCompleter implements Completer
{
public static final MyNullCompleter INSTANCE = new MyNullCompleter();
@Override
public int complete(final String buffer, final int cursor, final List<CharSequence> candidates)
{
candidates.add("");
return cursor;
}
}
private final static class MyFileNameCompleter extends FileNameCompleter
{
@Override
public int complete(final String buffer, final int cursor, final List<CharSequence> candidates)
{
int result = super.complete(buffer, cursor, candidates);
if (candidates.isEmpty()) {
candidates.add("");
result = cursor;
}
return result;
}
}
private List<Completer> defaultCompleters()
{
Map<String, CommandSpec> commands = new TreeMap<String, CommandSpec>();
commands.putAll(logicalPlanChangeCommands);
commands.putAll(connectedCommands);
commands.putAll(globalCommands);
List<Completer> completers = new LinkedList<Completer>();
for (Map.Entry<String, CommandSpec> entry : commands.entrySet()) {
String command = entry.getKey();
CommandSpec cs = entry.getValue();
List<Completer> argCompleters = new LinkedList<Completer>();
argCompleters.add(new StringsCompleter(command));
Arg[] args = (Arg[]) ArrayUtils.addAll(cs.requiredArgs, cs.optionalArgs);
if (args != null) {
if (cs instanceof OptionsCommandSpec) {
// ugly hack because jline cannot dynamically change completer while user types
if (args[0] instanceof FileArg || args[0] instanceof VarArg) {
for (int i = 0; i < 10; i++) {
argCompleters.add(new MyFileNameCompleter());
}
}
}
else {
for (Arg arg : args) {
if (arg instanceof FileArg || arg instanceof VarArg) {
argCompleters.add(new MyFileNameCompleter());
}
else if (arg instanceof CommandArg) {
argCompleters.add(new StringsCompleter(commands.keySet().toArray(new String[]{})));
}
else {
argCompleters.add(MyNullCompleter.INSTANCE);
}
}
}
}
completers.add(new ArgumentCompleter(argCompleters));
}
List<Completer> argCompleters = new LinkedList<Completer>();
Set<String> set = new TreeSet<String>();
set.addAll(aliases.keySet());
set.addAll(macros.keySet());
argCompleters.add(new StringsCompleter(set.toArray(new String[]{})));
for (int i = 0; i < 10; i++) {
argCompleters.add(new MyFileNameCompleter());
}
completers.add(new ArgumentCompleter(argCompleters));
return completers;
}
private void setupCompleter(ConsoleReader reader)
{
reader.addCompleter(new AggregateCompleter(defaultCompleters()));
}
private void updateCompleter(ConsoleReader reader)
{
List<Completer> completers = new ArrayList<Completer>(reader.getCompleters());
for (Completer c : completers) {
reader.removeCompleter(c);
}
setupCompleter(reader);
}
private void setupHistory(ConsoleReader reader)
{
File historyFile = new File(StramClientUtils.getUserDTDirectory(), "cli_history");
historyFile.getParentFile().mkdirs();
try {
topLevelHistory = new FileHistory(historyFile);
reader.setHistory(topLevelHistory);
historyFile = new File(StramClientUtils.getUserDTDirectory(), "cli_history_clp");
changingLogicalPlanHistory = new FileHistory(historyFile);
}
catch (IOException ex) {
System.err.printf("Unable to open %s for writing.", historyFile);
}
}
private void setupAgents() throws IOException
{
recordingsAgent = new RecordingsAgent(stramAgent);
}
public void run() throws IOException
{
ConsoleReader reader = new ConsoleReader();
reader.setExpandEvents(false);
reader.setBellEnabled(false);
try {
processSourceFile(StramClientUtils.getConfigDir() + "/clirc_system", reader);
}
catch (Exception ex) {
// ignore
}
try {
processSourceFile(StramClientUtils.getUserDTDirectory() + "/clirc", reader);
}
catch (Exception ex) {
// ignore
}
if (consolePresent) {
printWelcomeMessage();
setupCompleter(reader);
setupHistory(reader);
//reader.setHandleUserInterrupt(true);
}
else {
reader.setEchoCharacter((char) 0);
}
setupAgents();
String line;
PrintWriter out = new PrintWriter(System.out);
int i = 0;
while (true) {
if (commandsToExecute != null) {
if (i >= commandsToExecute.length) {
break;
}
line = commandsToExecute[i++];
}
else {
line = readLine(reader);
if (line == null) {
break;
}
}
processLine(line, reader, true);
out.flush();
}
if (topLevelHistory != null) {
try {
topLevelHistory.flush();
} catch (IOException ex) {
LOG.warn("Cannot flush command history", ex);
}
}
if (changingLogicalPlanHistory != null) {
try {
changingLogicalPlanHistory.flush();
} catch (IOException ex) {
LOG.warn("Cannot flush command history", ex);
}
}
if (consolePresent) {
System.out.println("exit");
}
}
private List<String> expandMacro(List<String> lines, String[] args)
{
List<String> expandedLines = new ArrayList<String>();
for (String line : lines) {
int previousIndex = 0;
StringBuilder expandedLine = new StringBuilder(line.length());
while (true) {
// Search for $0..$9 within the each line and replace by corresponding args
int currentIndex = line.indexOf('$', previousIndex);
if (currentIndex > 0 && line.length() > currentIndex + 1) {
int argIndex = line.charAt(currentIndex + 1) - '0';
if (args.length > argIndex && argIndex >= 0) {
// Replace $0 with macro name or $1..$9 with input arguments
expandedLine.append(line.substring(previousIndex, currentIndex)).append(args[argIndex]);
}
else if (argIndex >= 0 && argIndex <= 9) {
// Arguments for $1..$9 were not supplied - replace with empty strings
expandedLine.append(line.substring(previousIndex, currentIndex));
}
else {
// Outside valid arguments range - ignore and do not replace
expandedLine.append(line.substring(previousIndex, currentIndex + 2));
}
currentIndex += 2;
}
else {
expandedLine.append(line.substring(previousIndex));
expandedLines.add(expandedLine.toString());
break;
}
previousIndex = currentIndex;
}
}
return expandedLines;
}
private static String ltrim(String s)
{
int i = 0;
while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
i++;
}
return s.substring(i);
}
private void processLine(String line, final ConsoleReader reader, boolean expandMacroAlias)
{
try {
// clear interrupt flag
Thread.interrupted();
if (reader.isHistoryEnabled()) {
History history = reader.getHistory();
if (history instanceof FileHistory) {
try {
((FileHistory) history).flush();
}
catch (IOException ex) {
// ignore
}
}
}
//LOG.debug("line: \"{}\"", line);
List<String[]> commands = tokenizer.tokenize(line);
if (commands == null) {
return;
}
for (final String[] args : commands) {
if (args.length == 0 || StringUtils.isBlank(args[0])) {
continue;
}
//LOG.debug("Got: {}", mapper.writeValueAsString(args));
if (expandMacroAlias) {
if (macros.containsKey(args[0])) {
List<String> macroItems = expandMacro(macros.get(args[0]), args);
for (String macroItem : macroItems) {
if (consolePresent) {
System.out.println("expanded-macro> " + macroItem);
}
processLine(macroItem, reader, false);
}
continue;
}
if (aliases.containsKey(args[0])) {
processLine(aliases.get(args[0]), reader, false);
continue;
}
}
CommandSpec cs = null;
if (changingLogicalPlan) {
cs = logicalPlanChangeCommands.get(args[0]);
}
else {
if (currentApp != null) {
cs = connectedCommands.get(args[0]);
}
if (cs == null) {
cs = globalCommands.get(args[0]);
}
}
if (cs == null) {
if (connectedCommands.get(args[0]) != null) {
System.err.println("\"" + args[0] + "\" is valid only when connected to an application. Type \"connect <appid>\" to connect to an application.");
lastCommandError = true;
}
else if (logicalPlanChangeCommands.get(args[0]) != null) {
System.err.println("\"" + args[0] + "\" is valid only when changing a logical plan. Type \"begin-logical-plan-change\" to change a logical plan");
lastCommandError = true;
}
else {
System.err.println("Invalid command '" + args[0] + "'. Type \"help\" for list of commands");
lastCommandError = true;
}
}
else {
try {
cs.verifyArguments(args);
}
catch (CliException ex) {
cs.printUsage(args[0]);
throw ex;
}
final Command command = cs.command;
commandThread = new Thread()
{
@Override
public void run()
{
try {
command.execute(args, reader);
lastCommandError = false;
}
catch (Exception e) {
handleException(e);
}
}
};
mainThread = Thread.currentThread();
commandThread.start();
try {
commandThread.join();
}
catch (InterruptedException ex) {
System.err.println("Interrupted");
}
commandThread = null;
}
}
}
catch (Exception e) {
handleException(e);
}
}
private void handleException(Exception e)
{
String msg = e.getMessage();
Throwable cause = e.getCause();
if (cause != null && cause.getMessage() != null) {
msg += ": " + cause.getMessage();
}
if (msg != null) {
System.err.println(msg);
}
LOG.error("Exception caught: ", e);
lastCommandError = true;
}
private void printWelcomeMessage()
{
System.out.println("DT CLI " + VersionInfo.getVersion() + " " + VersionInfo.getDate() + " " + VersionInfo.getRevision());
if (!StramClientUtils.configComplete(conf)) {
System.err.println("WARNING: Configuration of DataTorrent has not been complete. Please proceed with caution and only in development environment!");
}
}
private void printHelp(String command, CommandSpec commandSpec, PrintStream os)
{
if (consolePresent) {
os.print("\033[0;93m");
os.print(command);
os.print("\033[0m");
}
else {
os.print(command);
}
if (commandSpec instanceof OptionsCommandSpec) {
OptionsCommandSpec ocs = (OptionsCommandSpec) commandSpec;
if (ocs.options != null) {
os.print(" [options]");
}
}
if (commandSpec.requiredArgs != null) {
for (Arg arg : commandSpec.requiredArgs) {
if (consolePresent) {
os.print(" \033[3m" + arg + "\033[0m");
}
else {
os.print(" <" + arg + ">");
}
}
}
if (commandSpec.optionalArgs != null) {
for (Arg arg : commandSpec.optionalArgs) {
if (consolePresent) {
os.print(" [\033[3m" + arg + "\033[0m");
}
else {
os.print(" [<" + arg + ">");
}
if (arg instanceof VarArg) {
os.print(" ...");
}
os.print("]");
}
}
os.println("\n\t" + commandSpec.description);
if (commandSpec instanceof OptionsCommandSpec) {
OptionsCommandSpec ocs = (OptionsCommandSpec) commandSpec;
if (ocs.options != null) {
os.println("\tOptions:");
HelpFormatter formatter = new HelpFormatter();
PrintWriter pw = new PrintWriter(os);
formatter.printOptions(pw, 80, ocs.options, 12, 4);
pw.flush();
}
}
}
private void printHelp(Map<String, CommandSpec> commandSpecs, PrintStream os)
{
for (Map.Entry<String, CommandSpec> entry : commandSpecs.entrySet()) {
printHelp(entry.getKey(), entry.getValue(), os);
}
}
private String readLine(ConsoleReader reader)
throws IOException
{
if (forcePrompt == null) {
prompt = "";
if (consolePresent) {
if (changingLogicalPlan) {
prompt = "logical-plan-change";
}
else {
prompt = "dt";
}
if (currentApp != null) {
prompt += " (";
prompt += currentApp.getApplicationId().toString();
prompt += ") ";
}
prompt += "> ";
}
}
else {
prompt = forcePrompt;
}
String line = reader.readLine(prompt, consolePresent ? null : (char) 0);
if (line == null) {
return null;
}
return ltrim(line);
}
private List<ApplicationReport> getApplicationList()
{
try {
return yarnClient.getApplications(Sets.newHashSet(StramClient.YARN_APPLICATION_TYPE));
}
catch (Exception e) {
throw new CliException("Error getting application list from resource manager", e);
}
}
private String getContainerLongId(String containerId)
{
JSONObject json = getResource(StramWebServices.PATH_PHYSICAL_PLAN_CONTAINERS, currentApp);
int shortId = 0;
if (StringUtils.isNumeric(containerId)) {
shortId = Integer.parseInt(containerId);
}
try {
Object containersObj = json.get("containers");
JSONArray containers;
if (containersObj instanceof JSONArray) {
containers = (JSONArray) containersObj;
}
else {
containers = new JSONArray();
containers.put(containersObj);
}
if (containersObj != null) {
for (int o = containers.length(); o-- > 0; ) {
JSONObject container = containers.getJSONObject(o);
String id = container.getString("id");
if (id.equals(containerId) || (shortId != 0 && (id.endsWith("_" + shortId) || id.endsWith("0" + shortId)))) {
return id;
}
}
}
}
catch (JSONException ex) {
}
return null;
}
private ApplicationReport assertRunningApp(ApplicationReport app)
{
ApplicationReport r;
try {
r = yarnClient.getApplicationReport(app.getApplicationId());
if (r.getYarnApplicationState() != YarnApplicationState.RUNNING) {
String msg = String.format("Application %s not running (status %s)",
r.getApplicationId().getId(), r.getYarnApplicationState());
throw new CliException(msg);
}
}
catch (YarnException rmExc) {
throw new CliException("Unable to determine application status", rmExc);
}
catch (IOException rmExc) {
throw new CliException("Unable to determine application status", rmExc);
}
return r;
}
private JSONObject getResource(String resourcePath, ApplicationReport appReport)
{
return getResource(new StramAgent.StramUriSpec().path(resourcePath), appReport, new WebServicesClient.GetWebServicesHandler<JSONObject>());
}
private JSONObject getResource(StramAgent.StramUriSpec uriSpec, ApplicationReport appReport)
{
return getResource(uriSpec, appReport, new WebServicesClient.GetWebServicesHandler<JSONObject>());
}
private JSONObject getResource(StramAgent.StramUriSpec uriSpec, ApplicationReport appReport, WebServicesClient.WebServicesHandler handler)
{
if (appReport == null) {
throw new CliException("No application selected");
}
if (StringUtils.isEmpty(appReport.getTrackingUrl()) || appReport.getFinalApplicationStatus() != FinalApplicationStatus.UNDEFINED) {
appReport = null;
throw new CliException("Application terminated");
}
WebServicesClient wsClient = new WebServicesClient();
try {
return stramAgent.issueStramWebRequest(wsClient, appReport.getApplicationId().toString(), uriSpec, handler);
} catch (Exception e) {
// check the application status as above may have failed due application termination etc.
if (appReport == currentApp) {
currentApp = assertRunningApp(appReport);
}
throw new CliException("Failed to request web service for appid " + appReport.getApplicationId().toString(), e);
}
}
private List<AppFactory> getMatchingAppFactories(StramAppLauncher submitApp, String matchString, boolean exactMatch)
{
try {
List<AppFactory> cfgList = submitApp.getBundledTopologies();
if (cfgList.isEmpty()) {
return null;
}
else if (matchString == null) {
return cfgList;
}
else {
List<AppFactory> result = new ArrayList<AppFactory>();
if (!exactMatch) {
matchString = matchString.toLowerCase();
}
for (AppFactory ac : cfgList) {
String appName = ac.getName();
String appAlias = submitApp.getLogicalPlanConfiguration().getAppAlias(appName);
if (exactMatch) {
if (matchString.equals(appName) || matchString.equals(appAlias)) {
result.add(ac);
}
}
else if (appName.toLowerCase().contains(matchString) || (appAlias != null && appAlias.toLowerCase().contains(matchString))) {
result.add(ac);
}
}
return result;
}
}
catch (Exception ex) {
LOG.warn("Caught Exception: ", ex);
return null;
}
}
/*
* Below is the implementation of all commands
*/
private class HelpCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
PrintStream os = getOutputPrintStream();
if (args.length < 2) {
os.println("GLOBAL COMMANDS EXCEPT WHEN CHANGING LOGICAL PLAN:\n");
printHelp(globalCommands, os);
os.println();
os.println("COMMANDS WHEN CONNECTED TO AN APP (via connect <appid>) EXCEPT WHEN CHANGING LOGICAL PLAN:\n");
printHelp(connectedCommands, os);
os.println();
os.println("COMMANDS WHEN CHANGING LOGICAL PLAN (via begin-logical-plan-change):\n");
printHelp(logicalPlanChangeCommands, os);
os.println();
}
else {
if (args[1].equals("help")) {
printHelp("help", globalCommands.get("help"), os);
}
else {
boolean valid = false;
CommandSpec cs = globalCommands.get(args[1]);
if (cs != null) {
os.println("This usage is valid except when changing logical plan");
printHelp(args[1], cs, os);
os.println();
valid = true;
}
cs = connectedCommands.get(args[1]);
if (cs != null) {
os.println("This usage is valid when connected to an app except when changing logical plan");
printHelp(args[1], cs, os);
os.println();
valid = true;
}
cs = logicalPlanChangeCommands.get(args[1]);
if (cs != null) {
os.println("This usage is only valid when changing logical plan (via begin-logical-plan-change)");
printHelp(args[1], cs, os);
os.println();
valid = true;
}
if (!valid) {
os.println("Help for \"" + args[1] + "\" does not exist.");
}
}
}
closeOutputPrintStream(os);
}
}
private class EchoCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
for (int i = 1; i < args.length; i++) {
if (i > 1) {
System.out.print(" ");
}
System.out.print(args[i]);
}
System.out.println();
}
}
private class ConnectCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
currentApp = getApplication(args[1]);
if (currentApp == null) {
throw new CliException("Streaming application with id " + args[1] + " is not found.");
}
try {
LOG.debug("Selected {} with tracking url {}", currentApp.getApplicationId(), currentApp.getTrackingUrl());
getResource(StramWebServices.PATH_INFO, currentApp);
if (consolePresent) {
System.out.println("Connected to application " + currentApp.getApplicationId());
}
}
catch (CliException e) {
throw e; // pass on
}
}
}
private class LaunchCommand implements Command
{
@Override
@SuppressWarnings("SleepWhileInLoop")
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, args.length - 1);
LaunchCommandLineInfo commandLineInfo = getLaunchCommandLineInfo(newArgs);
if (commandLineInfo.configFile != null) {
commandLineInfo.configFile = expandFileName(commandLineInfo.configFile, true);
}
// see if the given config file is a config package
ConfigPackage cp = null;
String requiredAppPackageName = null;
try {
cp = new ConfigPackage(new File(commandLineInfo.configFile));
requiredAppPackageName = cp.getAppPackageName();
} catch (Exception ex) {
// fall through, it's not a config package
}
try {
Configuration config;
String configFile = cp == null ? commandLineInfo.configFile : null;
try {
config = StramAppLauncher.getOverriddenConfig(StramClientUtils.addDTSiteResources(new Configuration()), configFile, commandLineInfo.overrideProperties);
if (commandLineInfo.libjars != null) {
commandLineInfo.libjars = expandCommaSeparatedFiles(commandLineInfo.libjars);
if (commandLineInfo.libjars != null) {
config.set(StramAppLauncher.LIBJARS_CONF_KEY_NAME, commandLineInfo.libjars);
}
}
if (commandLineInfo.files != null) {
commandLineInfo.files = expandCommaSeparatedFiles(commandLineInfo.files);
if (commandLineInfo.files != null) {
config.set(StramAppLauncher.FILES_CONF_KEY_NAME, commandLineInfo.files);
}
}
if (commandLineInfo.archives != null) {
commandLineInfo.archives = expandCommaSeparatedFiles(commandLineInfo.archives);
if (commandLineInfo.archives != null) {
config.set(StramAppLauncher.ARCHIVES_CONF_KEY_NAME, commandLineInfo.archives);
}
}
if (commandLineInfo.origAppId != null) {
config.set(StramAppLauncher.ORIGINAL_APP_ID, commandLineInfo.origAppId);
}
config.set(StramAppLauncher.QUEUE_NAME, commandLineInfo.queue != null ? commandLineInfo.queue : "default");
} catch (Throwable t) {
throw new CliException("Error opening the config XML file: " + configFile, t);
}
String fileName = expandFileName(commandLineInfo.args[0], true);
StramAppLauncher submitApp;
AppFactory appFactory = null;
String matchString = commandLineInfo.args.length >= 2 ? commandLineInfo.args[1] : null;
if (fileName.endsWith(".json")) {
File file = new File(fileName);
submitApp = new StramAppLauncher(file.getName(), config);
appFactory = new StramAppLauncher.JsonFileAppFactory(file);
if (matchString != null) {
LOG.warn("Match string \"{}\" is ignored for launching applications specified in JSON", matchString);
}
} else if (fileName.endsWith(".properties")) {
File file = new File(fileName);
submitApp = new StramAppLauncher(file.getName(), config);
appFactory = new StramAppLauncher.PropertyFileAppFactory(file);
if (matchString != null) {
LOG.warn("Match string \"{}\" is ignored for launching applications specified in properties file", matchString);
}
} else {
// see if it's an app package
AppPackage ap = null;
try {
ap = newAppPackageInstance(new File(fileName));
} catch (Exception ex) {
// It's not an app package
if (requiredAppPackageName != null) {
throw new CliException("Config package requires an app package name of \"" + requiredAppPackageName + "\"");
}
}
if (ap != null) {
try {
checkCompatible(ap, cp);
launchAppPackage(ap, cp, commandLineInfo, reader);
return;
} finally {
IOUtils.closeQuietly(ap);
}
}
submitApp = getStramAppLauncher(fileName, config, commandLineInfo.ignorePom);
}
submitApp.loadDependencies();
if (commandLineInfo.origAppId != null) {
// ensure app is not running
ApplicationReport ar = null;
try {
ar = getApplication(commandLineInfo.origAppId);
} catch (Exception e) {
// application (no longer) in the RM history, does not prevent restart from state in DFS
LOG.debug("Cannot determine status of application {} {}", commandLineInfo.origAppId, ExceptionUtils.getMessage(e));
}
if (ar != null) {
if (ar.getFinalApplicationStatus() == FinalApplicationStatus.UNDEFINED) {
throw new CliException("Cannot relaunch non-terminated application: " + commandLineInfo.origAppId + " " + ar.getYarnApplicationState());
}
if (appFactory == null && matchString == null) {
// skip selection if we can match application name from previous run
List<AppFactory> matchingAppFactories = getMatchingAppFactories(submitApp, ar.getName(), commandLineInfo.exactMatch);
for (AppFactory af : matchingAppFactories) {
String appName = submitApp.getLogicalPlanConfiguration().getAppAlias(af.getName());
if (appName == null) {
appName = af.getName();
}
// limit to exact match
if (appName.equals(ar.getName())) {
appFactory = af;
break;
}
}
}
}
}
if (appFactory == null && matchString != null) {
// attempt to interpret argument as property file - do we still need it?
try {
File file = new File(expandFileName(commandLineInfo.args[1], true));
if (file.exists()) {
if (commandLineInfo.args[1].endsWith(".properties")) {
appFactory = new StramAppLauncher.PropertyFileAppFactory(file);
} else if (commandLineInfo.args[1].endsWith(".json")) {
appFactory = new StramAppLauncher.JsonFileAppFactory(file);
}
}
} catch (Throwable t) {
// ignore
}
}
if (appFactory == null) {
List<AppFactory> matchingAppFactories = getMatchingAppFactories(submitApp, matchString, commandLineInfo.exactMatch);
if (matchingAppFactories == null || matchingAppFactories.isEmpty()) {
throw new CliException("No applications matching \"" + matchString + "\" bundled in jar.");
} else if (matchingAppFactories.size() == 1) {
appFactory = matchingAppFactories.get(0);
} else if (matchingAppFactories.size() > 1) {
//Store the appNames sorted in alphabetical order and their position in matchingAppFactories list
TreeMap<String, Integer> appNamesInAlphabeticalOrder = new TreeMap<String, Integer>();
// Display matching applications
for (int i = 0; i < matchingAppFactories.size(); i++) {
String appName = matchingAppFactories.get(i).getName();
String appAlias = submitApp.getLogicalPlanConfiguration().getAppAlias(appName);
if (appAlias != null) {
appName = appAlias;
}
appNamesInAlphabeticalOrder.put(appName, i);
}
//Create a mapping between the app display number and original index at matchingAppFactories
int index = 1;
HashMap<Integer, Integer> displayIndexToOriginalUnsortedIndexMap = new HashMap<Integer, Integer>();
for (Map.Entry<String, Integer> entry : appNamesInAlphabeticalOrder.entrySet()) {
//Map display number of the app to original unsorted index
displayIndexToOriginalUnsortedIndexMap.put(index, entry.getValue());
//Display the app names
System.out.printf("%3d. %s\n", index++, entry.getKey());
}
// Exit if not in interactive mode
if (!consolePresent) {
throw new CliException("More than one application in jar file match '" + matchString + "'");
} else {
boolean useHistory = reader.isHistoryEnabled();
reader.setHistoryEnabled(false);
History previousHistory = reader.getHistory();
History dummyHistory = new MemoryHistory();
reader.setHistory(dummyHistory);
List<Completer> completers = new ArrayList<Completer>(reader.getCompleters());
for (Completer c : completers) {
reader.removeCompleter(c);
}
reader.setHandleUserInterrupt(true);
String optionLine;
try {
optionLine = reader.readLine("Choose application: ");
} finally {
reader.setHandleUserInterrupt(false);
reader.setHistoryEnabled(useHistory);
reader.setHistory(previousHistory);
for (Completer c : completers) {
reader.addCompleter(c);
}
}
try {
int option = Integer.parseInt(optionLine);
if (0 < option && option <= matchingAppFactories.size()) {
int appIndex = displayIndexToOriginalUnsortedIndexMap.get(option);
appFactory = matchingAppFactories.get(appIndex);
}
} catch (Exception ex) {
// ignore
}
}
}
}
if (appFactory != null) {
if (!commandLineInfo.localMode) {
// see whether there is an app with the same name and user name running
String appNameAttributeName = StreamingApplication.DT_PREFIX + Context.DAGContext.APPLICATION_NAME.getName();
String appName = config.get(appNameAttributeName, appFactory.getName());
ApplicationReport duplicateApp = StramClientUtils.getStartedAppInstanceByName(yarnClient, appName, UserGroupInformation.getLoginUser().getUserName(), null);
if (duplicateApp != null) {
throw new CliException("Application with the name \"" + duplicateApp.getName() + "\" already running under the current user \"" + duplicateApp.getUser() + "\". Please choose another name. You can change the name by setting " + appNameAttributeName);
}
// This is for suppressing System.out printouts from applications so that the user of CLI will not be confused by those printouts
PrintStream originalStream = suppressOutput();
ApplicationId appId = null;
try {
if (raw) {
PrintStream dummyStream = new PrintStream(new OutputStream()
{
@Override
public void write(int b)
{
// no-op
}
});
System.setOut(dummyStream);
}
appId = submitApp.launchApp(appFactory);
currentApp = yarnClient.getApplicationReport(appId);
} finally {
restoreOutput(originalStream);
}
if (appId != null) {
printJson("{\"appId\": \"" + appId + "\"}");
}
} else {
submitApp.runLocal(appFactory);
}
} else {
System.err.println("No application specified.");
}
} finally {
IOUtils.closeQuietly(cp);
}
}
}
private class GetConfigParameterCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
PrintStream os = getOutputPrintStream();
if (args.length == 1) {
Map<String, String> sortedMap = new TreeMap<String, String>();
for (Map.Entry<String, String> entry : conf) {
sortedMap.put(entry.getKey(), entry.getValue());
}
for (Map.Entry<String, String> entry : sortedMap.entrySet()) {
os.println(entry.getKey() + "=" + entry.getValue());
}
}
else {
String value = conf.get(args[1]);
if (value != null) {
os.println(value);
}
}
closeOutputPrintStream(os);
}
}
private class ShutdownAppCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
ApplicationReport[] apps;
WebServicesClient webServicesClient = new WebServicesClient();
if (args.length == 1) {
if (currentApp == null) {
throw new CliException("No application selected");
}
else {
apps = new ApplicationReport[]{currentApp};
}
}
else {
apps = new ApplicationReport[args.length - 1];
for (int i = 1; i < args.length; i++) {
apps[i - 1] = getApplication(args[i]);
if (apps[i - 1] == null) {
throw new CliException("Streaming application with id " + args[i] + " is not found.");
}
}
}
for (ApplicationReport app : apps) {
try {
JSONObject response = getResource(new StramAgent.StramUriSpec().path(StramWebServices.PATH_SHUTDOWN), app, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(clazz, new JSONObject());
}
});
if (consolePresent) {
System.out.println("Shutdown requested: " + response);
}
currentApp = null;
} catch (Exception e) {
throw new CliException("Failed to request shutdown for appid " + app.getApplicationId().toString(), e);
}
}
}
}
private class ListAppsCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
try {
JSONArray jsonArray = new JSONArray();
List<ApplicationReport> appList = getApplicationList();
Collections.sort(appList, new Comparator<ApplicationReport>()
{
@Override
public int compare(ApplicationReport o1, ApplicationReport o2)
{
return o1.getApplicationId().getId() - o2.getApplicationId().getId();
}
});
int totalCnt = 0;
int runningCnt = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
for (ApplicationReport ar : appList) {
/*
* This is inefficient, but what the heck, if this can be passed through the command line, can anyone notice slowness.
*/
JSONObject jsonObj = new JSONObject();
jsonObj.put("startTime", sdf.format(new java.util.Date(ar.getStartTime())));
jsonObj.put("id", ar.getApplicationId().getId());
jsonObj.put("name", ar.getName());
jsonObj.put("state", ar.getYarnApplicationState().name());
jsonObj.put("trackingUrl", ar.getTrackingUrl());
jsonObj.put("finalStatus", ar.getFinalApplicationStatus());
totalCnt++;
if (ar.getYarnApplicationState() == YarnApplicationState.RUNNING) {
runningCnt++;
}
if (args.length > 1) {
if (StringUtils.isNumeric(args[1])) {
if (jsonObj.getString("id").equals(args[1])) {
jsonArray.put(jsonObj);
break;
}
}
else {
@SuppressWarnings("unchecked")
Iterator<String> keys = jsonObj.keys();
while (keys.hasNext()) {
if (jsonObj.get(keys.next()).toString().toLowerCase().contains(args[1].toLowerCase())) {
jsonArray.put(jsonObj);
break;
}
}
}
}
else {
jsonArray.put(jsonObj);
}
}
printJson(jsonArray, "apps");
if (consolePresent) {
System.out.println(runningCnt + " active, total " + totalCnt + " applications.");
}
}
catch (Exception ex) {
throw new CliException("Failed to retrieve application list", ex);
}
}
}
private class KillAppCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (args.length == 1) {
if (currentApp == null) {
throw new CliException("No application selected");
}
else {
try {
yarnClient.killApplication(currentApp.getApplicationId());
currentApp = null;
}
catch (YarnException e) {
throw new CliException("Failed to kill " + currentApp.getApplicationId(), e);
}
}
if (consolePresent) {
System.out.println("Kill app requested");
}
return;
}
ApplicationReport app = null;
int i = 0;
try {
while (++i < args.length) {
app = getApplication(args[i]);
if (app == null) {
throw new CliException("Streaming application with id " + args[i] + " is not found.");
}
yarnClient.killApplication(app.getApplicationId());
if (app == currentApp) {
currentApp = null;
}
}
if (consolePresent) {
System.out.println("Kill app requested");
}
}
catch (YarnException e) {
throw new CliException("Failed to kill " + ((app == null || app.getApplicationId() == null) ? "unknown application" : app.getApplicationId()) + ". Aborting killing of any additional applications.", e);
}
catch (NumberFormatException nfe) {
throw new CliException("Invalid application Id " + args[i], nfe);
}
}
}
private class AliasCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (args[1].equals(args[2])) {
throw new CliException("Alias to itself!");
}
aliases.put(args[1], args[2]);
if (consolePresent) {
System.out.println("Alias " + args[1] + " created.");
}
updateCompleter(reader);
}
}
private class SourceCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
processSourceFile(args[1], reader);
if (consolePresent) {
System.out.println("File " + args[1] + " sourced.");
}
}
}
private class ExitCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (topLevelHistory != null) {
try {
topLevelHistory.flush();
} catch (IOException ex) {
LOG.warn("Cannot flush command history");
}
}
if (changingLogicalPlanHistory != null) {
try {
changingLogicalPlanHistory.flush();
} catch (IOException ex) {
LOG.warn("Cannot flush command history");
}
}
System.exit(0);
}
}
private class ListContainersCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
JSONObject json = getResource(StramWebServices.PATH_PHYSICAL_PLAN_CONTAINERS, currentApp);
if (args.length == 1) {
printJson(json);
}
else {
Object containersObj = json.get("containers");
JSONArray containers;
if (containersObj instanceof JSONArray) {
containers = (JSONArray) containersObj;
}
else {
containers = new JSONArray();
containers.put(containersObj);
}
if (containersObj == null) {
System.out.println("No containers found!");
}
else {
JSONArray resultContainers = new JSONArray();
for (int o = containers.length(); o-- > 0; ) {
JSONObject container = containers.getJSONObject(o);
String id = container.getString("id");
if (id != null && !id.isEmpty()) {
for (int argc = args.length; argc-- > 1; ) {
String s1 = "0" + args[argc];
String s2 = "_" + args[argc];
if (id.equals(args[argc]) || id.endsWith(s1) || id.endsWith(s2)) {
resultContainers.put(container);
}
}
}
}
printJson(resultContainers, "containers");
}
}
}
}
private class ListOperatorsCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
JSONObject json = getResource(StramWebServices.PATH_PHYSICAL_PLAN_OPERATORS, currentApp);
if (args.length > 1) {
String singleKey = "" + json.keys().next();
JSONArray matches = new JSONArray();
// filter operators
JSONArray arr;
Object obj = json.get(singleKey);
if (obj instanceof JSONArray) {
arr = (JSONArray) obj;
}
else {
arr = new JSONArray();
arr.put(obj);
}
for (int i = 0; i < arr.length(); i++) {
JSONObject oper = arr.getJSONObject(i);
if (StringUtils.isNumeric(args[1])) {
if (oper.getString("id").equals(args[1])) {
matches.put(oper);
break;
}
}
else {
@SuppressWarnings("unchecked")
Iterator<String> keys = oper.keys();
while (keys.hasNext()) {
if (oper.get(keys.next()).toString().toLowerCase().contains(args[1].toLowerCase())) {
matches.put(oper);
break;
}
}
}
}
json.put(singleKey, matches);
}
printJson(json);
}
}
private class ShowPhysicalPlanCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
try {
printJson(getResource(StramWebServices.PATH_SHUTDOWN, currentApp));
} catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
}
}
private class KillContainerCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
for (int i = 1; i < args.length; i++) {
String containerLongId = getContainerLongId(args[i]);
if (containerLongId == null) {
throw new CliException("Container " + args[i] + " not found");
}
try {
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_PHYSICAL_PLAN_CONTAINERS).path(URLEncoder.encode(containerLongId, "UTF-8")).path("kill");
JSONObject response = getResource(uriSpec, currentApp, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(clazz, new JSONObject());
}
});
if (consolePresent) {
System.out.println("Kill container requested: " + response);
}
} catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
}
}
}
private class WaitCommand implements Command
{
@Override
public void execute(String[] args, final ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
int timeout = Integer.valueOf(args[1]);
ClientRMHelper.AppStatusCallback cb = new ClientRMHelper.AppStatusCallback()
{
@Override
public boolean exitLoop(ApplicationReport report)
{
System.out.println("current status is: " + report.getYarnApplicationState());
try {
if (reader.getInput().available() > 0) {
return true;
}
}
catch (IOException e) {
LOG.error("Error checking for input.", e);
}
return false;
}
};
try {
ClientRMHelper clientRMHelper = new ClientRMHelper(yarnClient);
boolean result = clientRMHelper.waitForCompletion(currentApp.getApplicationId(), cb, timeout * 1000);
if (!result) {
System.err.println("Application terminated unsucessful.");
}
}
catch (YarnException e) {
throw new CliException("Failed to kill " + currentApp.getApplicationId(), e);
}
}
}
private class StartRecordingCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String opId = args[1];
String port = null;
long numWindows = 0;
if (args.length >= 3) {
port = args[2];
}
if (args.length >= 4) {
numWindows = Long.valueOf(args[3]);
}
printJson(recordingsAgent.startRecording(currentApp.getApplicationId().toString(), opId, port, numWindows));
}
}
private class StopRecordingCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String opId = args[1];
String port = null;
if (args.length == 3) {
port = args[2];
}
printJson(recordingsAgent.stopRecording(currentApp.getApplicationId().toString(), opId, port));
}
}
private class GetRecordingInfoCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (args.length <= 1) {
List<RecordingInfo> recordingInfo = recordingsAgent.getRecordingInfo(currentApp.getApplicationId().toString());
printJson(recordingInfo, "recordings");
}
else if (args.length <= 2) {
String opId = args[1];
List<RecordingInfo> recordingInfo = recordingsAgent.getRecordingInfo(currentApp.getApplicationId().toString(), opId);
printJson(recordingInfo, "recordings");
}
else {
String opId = args[1];
String id = args[2];
RecordingInfo recordingInfo = recordingsAgent.getRecordingInfo(currentApp.getApplicationId().toString(), opId, id);
printJson(new JSONObject(mapper.writeValueAsString(recordingInfo)));
}
}
}
private class GetAppAttributesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_LOGICAL_PLAN).path("attributes");
if (args.length > 1) {
uriSpec = uriSpec.queryParam("attributeName", args[1]);
}
try {
JSONObject response = getResource(uriSpec, currentApp);
printJson(response);
} catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
}
}
private class GetOperatorAttributesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_LOGICAL_PLAN_OPERATORS).path(URLEncoder.encode(args[1], "UTF-8")).path("attributes");
if (args.length > 2) {
uriSpec = uriSpec.queryParam("attributeName", args[2]);
}
try {
JSONObject response = getResource(uriSpec, currentApp);
printJson(response);
} catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
}
}
private class GetPortAttributesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_LOGICAL_PLAN_OPERATORS).path(URLEncoder.encode(args[1], "UTF-8")).path("ports").path(URLEncoder.encode(args[2], "UTF-8")).path("attributes");
if (args.length > 3) {
uriSpec = uriSpec.queryParam("attributeName", args[3]);
}
try {
JSONObject response = getResource(uriSpec, currentApp);
printJson(response);
} catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
}
}
private class GetOperatorPropertiesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_LOGICAL_PLAN_OPERATORS).path(URLEncoder.encode(args[1], "UTF-8")).path("properties");
if (args.length > 2) {
uriSpec = uriSpec.queryParam("propertyName", args[2]);
}
try {
JSONObject response = getResource(uriSpec, currentApp);
printJson(response);
} catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
}
}
private class GetPhysicalOperatorPropertiesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
if (!NumberUtils.isDigits(args[1])) {
throw new CliException("Operator ID must be a number");
}
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, args.length - 1);
PosixParser parser = new PosixParser();
CommandLine line = parser.parse(GET_PHYSICAL_PROPERTY_OPTIONS.options, newArgs);
String waitTime = line.getOptionValue(GET_PHYSICAL_PROPERTY_OPTIONS.waitTime.getOpt());
String propertyName = line.getOptionValue(GET_PHYSICAL_PROPERTY_OPTIONS.propertyName.getOpt());
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_PHYSICAL_PLAN_OPERATORS).path(args[1]).path("properties");
if (propertyName != null) {
uriSpec = uriSpec.queryParam("propertyName", propertyName);
}
if (waitTime != null) {
uriSpec = uriSpec.queryParam("waitTime", waitTime);
}
try {
JSONObject response = getResource(uriSpec, currentApp);
printJson(response);
} catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
}
}
private class SetOperatorPropertyCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
if (changingLogicalPlan) {
String operatorName = args[1];
String propertyName = args[2];
String propertyValue = args[3];
SetOperatorPropertyRequest request = new SetOperatorPropertyRequest();
request.setOperatorName(operatorName);
request.setPropertyName(propertyName);
request.setPropertyValue(propertyValue);
logicalPlanRequestQueue.add(request);
}
else {
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_LOGICAL_PLAN_OPERATORS).path(URLEncoder.encode(args[1], "UTF-8")).path("properties");
final JSONObject request = new JSONObject();
request.put(args[2], args[3]);
JSONObject response = getResource(uriSpec, currentApp, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(JSONObject.class, request);
}
});
printJson(response);
}
}
}
private class SetPhysicalOperatorPropertyCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
if (!NumberUtils.isDigits(args[1])) {
throw new CliException("Operator ID must be a number");
}
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_PHYSICAL_PLAN_OPERATORS).path(args[1]).path("properties");
final JSONObject request = new JSONObject();
request.put(args[2], args[3]);
JSONObject response = getResource(uriSpec, currentApp, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(JSONObject.class, request);
}
});
printJson(response);
}
}
private class BeginLogicalPlanChangeCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
changingLogicalPlan = true;
reader.setHistory(changingLogicalPlanHistory);
}
}
private class ShowLogicalPlanCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, args.length - 1);
ShowLogicalPlanCommandLineInfo commandLineInfo = getShowLogicalPlanCommandLineInfo(newArgs);
Configuration config = StramClientUtils.addDTSiteResources(new Configuration());
if (commandLineInfo.libjars != null) {
commandLineInfo.libjars = expandCommaSeparatedFiles(commandLineInfo.libjars);
if (commandLineInfo.libjars != null) {
config.set(StramAppLauncher.LIBJARS_CONF_KEY_NAME, commandLineInfo.libjars);
}
}
if (commandLineInfo.args.length >= 2) {
String jarfile = expandFileName(commandLineInfo.args[0], true);
AppPackage ap = null;
// see if the first argument is actually an app package
try {
ap = new AppPackage(new File(jarfile));
}
catch (Exception ex) {
// fall through
}
if (ap != null) {
new ShowLogicalPlanAppPackageCommand().execute(args, reader);
return;
}
String appName = commandLineInfo.args[1];
StramAppLauncher submitApp = getStramAppLauncher(jarfile, config, commandLineInfo.ignorePom);
submitApp.loadDependencies();
List<AppFactory> matchingAppFactories = getMatchingAppFactories(submitApp, appName, commandLineInfo.exactMatch);
if (matchingAppFactories == null || matchingAppFactories.isEmpty()) {
throw new CliException("No application in jar file matches '" + appName + "'");
}
else if (matchingAppFactories.size() > 1) {
throw new CliException("More than one application in jar file match '" + appName + "'");
}
else {
Map<String, Object> map = new HashMap<String, Object>();
PrintStream originalStream = System.out;
AppFactory appFactory = matchingAppFactories.get(0);
try {
if (raw) {
PrintStream dummyStream = new PrintStream(new OutputStream()
{
@Override
public void write(int b)
{
// no-op
}
});
System.setOut(dummyStream);
}
LogicalPlan logicalPlan = appFactory.createApp(submitApp.getLogicalPlanConfiguration());
map.put("applicationName", appFactory.getName());
map.put("logicalPlan", LogicalPlanSerializer.convertToMap(logicalPlan));
}
finally {
if (raw) {
System.setOut(originalStream);
}
}
printJson(map);
}
}
else if (commandLineInfo.args.length == 1) {
String filename = expandFileName(commandLineInfo.args[0], true);
if (filename.endsWith(".json")) {
File file = new File(filename);
StramAppLauncher submitApp = new StramAppLauncher(file.getName(), config);
AppFactory appFactory = new StramAppLauncher.JsonFileAppFactory(file);
LogicalPlan logicalPlan = appFactory.createApp(submitApp.getLogicalPlanConfiguration());
Map<String, Object> map = new HashMap<String, Object>();
map.put("applicationName", appFactory.getName());
map.put("logicalPlan", LogicalPlanSerializer.convertToMap(logicalPlan));
printJson(map);
}
else if (filename.endsWith(".properties")) {
File file = new File(filename);
StramAppLauncher submitApp = new StramAppLauncher(file.getName(), config);
AppFactory appFactory = new StramAppLauncher.PropertyFileAppFactory(file);
LogicalPlan logicalPlan = appFactory.createApp(submitApp.getLogicalPlanConfiguration());
Map<String, Object> map = new HashMap<String, Object>();
map.put("applicationName", appFactory.getName());
map.put("logicalPlan", LogicalPlanSerializer.convertToMap(logicalPlan));
printJson(map);
}
else {
StramAppLauncher submitApp = getStramAppLauncher(filename, config, commandLineInfo.ignorePom);
submitApp.loadDependencies();
List<Map<String, Object>> appList = new ArrayList<Map<String, Object>>();
List<AppFactory> appFactoryList = submitApp.getBundledTopologies();
for (AppFactory appFactory : appFactoryList) {
Map<String, Object> m = new HashMap<String, Object>();
m.put("name", appFactory.getName());
appList.add(m);
}
printJson(appList, "applications");
}
}
else {
if (currentApp == null) {
throw new CliException("No application selected");
}
JSONObject response = getResource(StramWebServices.PATH_LOGICAL_PLAN, currentApp);
printJson(response);
}
}
}
private class ShowLogicalPlanAppPackageCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String jarfile = expandFileName(args[1], true);
AppPackage ap = null;
try {
ap = newAppPackageInstance(new File(jarfile));
List<AppInfo> applications = ap.getApplications();
if (args.length >= 3) {
for (AppInfo appInfo : applications) {
if (args[2].equals(appInfo.name)) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("applicationName", appInfo.name);
if (appInfo.dag != null) {
map.put("logicalPlan", LogicalPlanSerializer.convertToMap(appInfo.dag));
}
if (appInfo.error != null) {
map.put("error", appInfo.error);
}
printJson(map);
}
}
} else {
List<Map<String, Object>> appList = new ArrayList<Map<String, Object>>();
for (AppInfo appInfo : applications) {
Map<String, Object> m = new HashMap<String, Object>();
m.put("name", appInfo.name);
m.put("type", appInfo.type);
appList.add(m);
}
printJson(appList, "applications");
}
} finally {
IOUtils.closeQuietly(ap);
}
}
}
private File copyToLocal(String[] files) throws IOException
{
File tmpDir = new File("/tmp/datatorrent/" + ManagementFactory.getRuntimeMXBean().getName());
tmpDir.mkdirs();
for (int i = 0; i < files.length; i++) {
try {
URI uri = new URI(files[i]);
String scheme = uri.getScheme();
if (scheme == null || scheme.equals("file")) {
files[i] = uri.getPath();
}
else {
FileSystem tmpFs = FileSystem.newInstance(uri, conf);
try {
Path srcPath = new Path(uri.getPath());
Path dstPath = new Path(tmpDir.getAbsolutePath(), String.valueOf(i) + srcPath.getName());
tmpFs.copyToLocalFile(srcPath, dstPath);
files[i] = dstPath.toUri().getPath();
}
finally {
tmpFs.close();
}
}
}
catch (URISyntaxException ex) {
throw new RuntimeException(ex);
}
}
return tmpDir;
}
public static class GetOperatorClassesCommandLineOptions
{
final Options options = new Options();
final Option parent = add(new Option("parent", "Specify the parent class for the operators"));
private Option add(Option opt)
{
this.options.addOption(opt);
return opt;
}
}
private static GetOperatorClassesCommandLineOptions GET_OPERATOR_CLASSES_OPTIONS = new GetOperatorClassesCommandLineOptions();
private static class GetOperatorClassesCommandLineInfo
{
String parent;
String[] args;
}
private static GetOperatorClassesCommandLineInfo getGetOperatorClassesCommandLineInfo(String[] args) throws ParseException
{
CommandLineParser parser = new PosixParser();
GetOperatorClassesCommandLineInfo result = new GetOperatorClassesCommandLineInfo();
CommandLine line = parser.parse(GET_OPERATOR_CLASSES_OPTIONS.options, args);
result.parent = line.getOptionValue("parent");
result.args = line.getArgs();
return result;
}
private class GetJarOperatorClassesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, args.length - 1);
GetOperatorClassesCommandLineInfo commandLineInfo = getGetOperatorClassesCommandLineInfo(newArgs);
String parentName = commandLineInfo.parent != null ? commandLineInfo.parent : Operator.class.getName();
String files = expandCommaSeparatedFiles(commandLineInfo.args[0]);
if (files == null) {
throw new CliException("File " + commandLineInfo.args[0] + " is not found");
}
String[] jarFiles = files.split(",");
File tmpDir = copyToLocal(jarFiles);
try {
ObjectMapper defaultValueMapper = ObjectMapperFactory.getOperatorValueSerializer();
OperatorDiscoverer operatorDiscoverer = new OperatorDiscoverer(jarFiles);
String searchTerm = commandLineInfo.args.length > 1 ? commandLineInfo.args[1] : null;
Set<Class<? extends Operator>> operatorClasses = operatorDiscoverer.getOperatorClasses(parentName, searchTerm);
JSONObject json = new JSONObject();
JSONArray arr = new JSONArray();
JSONObject portClassHier = new JSONObject();
JSONObject failed = new JSONObject();
for (Class<? extends Operator> clazz : operatorClasses) {
try {
JSONObject oper = operatorDiscoverer.describeOperator(clazz);
// add default value
Operator operIns = clazz.newInstance();
String s = defaultValueMapper.writeValueAsString(operIns);
oper.put("defaultValue", new JSONObject(s).get(clazz.getName()));
// add class hier info to portClassHier
operatorDiscoverer.buildPortClassHier(oper, portClassHier);
arr.put(oper);
} catch (Throwable t) {
// ignore this class
final String cls = clazz.getName(), ex = t.toString();
failed.put(cls, ex);
}
}
json.put("operatorClasses", arr);
json.put("portClassHier", portClassHier);
if (failed.length() > 0) {
json.put("failedOperators", failed);
}
printJson(json);
}
finally {
FileUtils.deleteDirectory(tmpDir);
}
}
}
private class GetJarOperatorPropertiesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String files = expandCommaSeparatedFiles(args[1]);
if (files == null) {
throw new CliException("File " + args[1] + " is not found");
}
String[] jarFiles = files.split(",");
File tmpDir = copyToLocal(jarFiles);
try {
OperatorDiscoverer operatorDiscoverer = new OperatorDiscoverer(jarFiles);
Class<? extends Operator> operatorClass = operatorDiscoverer.getOperatorClass(args[2]);
printJson(operatorDiscoverer.describeOperator(operatorClass));
} finally {
FileUtils.deleteDirectory(tmpDir);
}
}
}
private class DumpPropertiesFileCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String outfilename = expandFileName(args[1], false);
if (args.length > 3) {
String jarfile = args[2];
String appName = args[3];
Configuration config = StramClientUtils.addDTSiteResources(new Configuration());
StramAppLauncher submitApp = getStramAppLauncher(jarfile, config, false);
submitApp.loadDependencies();
List<AppFactory> matchingAppFactories = getMatchingAppFactories(submitApp, appName, true);
if (matchingAppFactories == null || matchingAppFactories.isEmpty()) {
throw new CliException("No application in jar file matches '" + appName + "'");
}
else if (matchingAppFactories.size() > 1) {
throw new CliException("More than one application in jar file match '" + appName + "'");
}
else {
AppFactory appFactory = matchingAppFactories.get(0);
LogicalPlan logicalPlan = appFactory.createApp(submitApp.getLogicalPlanConfiguration());
File file = new File(outfilename);
if (!file.exists()) {
file.createNewFile();
}
LogicalPlanSerializer.convertToProperties(logicalPlan).save(file);
}
}
else {
if (currentApp == null) {
throw new CliException("No application selected");
}
JSONObject response = getResource(StramWebServices.PATH_LOGICAL_PLAN, currentApp);
File file = new File(outfilename);
if (!file.exists()) {
file.createNewFile();
}
LogicalPlanSerializer.convertToProperties(response).save(file);
}
System.out.println("Property file is saved at " + outfilename);
}
}
private class CreateOperatorCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String operatorName = args[1];
String className = args[2];
CreateOperatorRequest request = new CreateOperatorRequest();
request.setOperatorName(operatorName);
request.setOperatorFQCN(className);
logicalPlanRequestQueue.add(request);
}
}
private class RemoveOperatorCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String operatorName = args[1];
RemoveOperatorRequest request = new RemoveOperatorRequest();
request.setOperatorName(operatorName);
logicalPlanRequestQueue.add(request);
}
}
private class CreateStreamCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String streamName = args[1];
String sourceOperatorName = args[2];
String sourcePortName = args[3];
String sinkOperatorName = args[4];
String sinkPortName = args[5];
CreateStreamRequest request = new CreateStreamRequest();
request.setStreamName(streamName);
request.setSourceOperatorName(sourceOperatorName);
request.setSinkOperatorName(sinkOperatorName);
request.setSourceOperatorPortName(sourcePortName);
request.setSinkOperatorPortName(sinkPortName);
logicalPlanRequestQueue.add(request);
}
}
private class AddStreamSinkCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String streamName = args[1];
String sinkOperatorName = args[2];
String sinkPortName = args[3];
AddStreamSinkRequest request = new AddStreamSinkRequest();
request.setStreamName(streamName);
request.setSinkOperatorName(sinkOperatorName);
request.setSinkOperatorPortName(sinkPortName);
logicalPlanRequestQueue.add(request);
}
}
private class RemoveStreamCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String streamName = args[1];
RemoveStreamRequest request = new RemoveStreamRequest();
request.setStreamName(streamName);
logicalPlanRequestQueue.add(request);
}
}
private class SetOperatorAttributeCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String operatorName = args[1];
String attributeName = args[2];
String attributeValue = args[3];
SetOperatorAttributeRequest request = new SetOperatorAttributeRequest();
request.setOperatorName(operatorName);
request.setAttributeName(attributeName);
request.setAttributeValue(attributeValue);
logicalPlanRequestQueue.add(request);
}
}
private class SetStreamAttributeCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String streamName = args[1];
String attributeName = args[2];
String attributeValue = args[3];
SetStreamAttributeRequest request = new SetStreamAttributeRequest();
request.setStreamName(streamName);
request.setAttributeName(attributeName);
request.setAttributeValue(attributeValue);
logicalPlanRequestQueue.add(request);
}
}
private class SetPortAttributeCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String operatorName = args[1];
String attributeName = args[2];
String attributeValue = args[3];
SetPortAttributeRequest request = new SetPortAttributeRequest();
request.setOperatorName(operatorName);
request.setAttributeName(attributeName);
request.setAttributeValue(attributeValue);
logicalPlanRequestQueue.add(request);
}
}
private class AbortCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
logicalPlanRequestQueue.clear();
changingLogicalPlan = false;
reader.setHistory(topLevelHistory);
}
}
private class SubmitCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (logicalPlanRequestQueue.isEmpty()) {
throw new CliException("Nothing to submit. Type \"abort\" to abort change");
}
StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec();
uriSpec = uriSpec.path(StramWebServices.PATH_LOGICAL_PLAN);
try {
final Map<String, Object> m = new HashMap<String, Object>();
ObjectMapper mapper = new ObjectMapper();
m.put("requests", logicalPlanRequestQueue);
final JSONObject jsonRequest = new JSONObject(mapper.writeValueAsString(m));
JSONObject response = getResource(uriSpec, currentApp, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(JSONObject.class, jsonRequest);
}
});
printJson(response);
}
catch (Exception e) {
throw new CliException("Failed web service request for appid " + currentApp.getApplicationId().toString(), e);
}
logicalPlanRequestQueue.clear();
changingLogicalPlan = false;
reader.setHistory(topLevelHistory);
}
}
private class ShowQueueCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
printJson(logicalPlanRequestQueue, "queue");
if (consolePresent) {
System.out.println("Total operations in queue: " + logicalPlanRequestQueue.size());
}
}
}
private class BeginMacroCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String name = args[1];
if (macros.containsKey(name) || aliases.containsKey(name)) {
System.err.println("Name '" + name + "' already exists.");
return;
}
try {
List<String> commands = new ArrayList<String>();
while (true) {
String line;
if (consolePresent) {
line = reader.readLine("macro def (" + name + ") > ");
}
else {
line = reader.readLine("", (char) 0);
}
if (line.equals("end")) {
macros.put(name, commands);
updateCompleter(reader);
if (consolePresent) {
System.out.println("Macro '" + name + "' created.");
}
return;
}
else if (line.equals("abort")) {
System.err.println("Aborted");
return;
}
else {
commands.add(line);
}
}
}
catch (IOException ex) {
System.err.println("Aborted");
}
}
}
private class SetPagerCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (args[1].equals("off")) {
pagerCommand = null;
}
else if (args[1].equals("on")) {
if (consolePresent) {
pagerCommand = "less -F -X -r";
}
}
else {
throw new CliException("set-pager parameter is either on or off.");
}
}
}
private class GetAppInfoCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
ApplicationReport appReport;
if (args.length > 1) {
appReport = getApplication(args[1]);
if (appReport == null) {
throw new CliException("Streaming application with id " + args[1] + " is not found.");
}
}
else {
if (currentApp == null) {
throw new CliException("No application selected");
}
// refresh the state in currentApp
currentApp = yarnClient.getApplicationReport(currentApp.getApplicationId());
appReport = currentApp;
}
JSONObject response;
try {
response = getResource(StramWebServices.PATH_INFO, currentApp);
}
catch (Exception ex) {
response = new JSONObject();
response.put("startTime", appReport.getStartTime());
response.put("id", appReport.getApplicationId().toString());
response.put("name", appReport.getName());
response.put("user", appReport.getUser());
}
response.put("state", appReport.getYarnApplicationState().name());
response.put("trackingUrl", appReport.getTrackingUrl());
response.put("finalStatus", appReport.getFinalApplicationStatus());
printJson(response);
}
}
private class GetAppPackageInfoCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
AppPackage ap = null;
try {
ap = newAppPackageInstance(new File(expandFileName(args[1], true)));
JSONSerializationProvider jomp = new JSONSerializationProvider();
JSONObject apInfo = new JSONObject(jomp.getContext(null).writeValueAsString(ap));
apInfo.remove("name");
printJson(apInfo);
}
finally {
IOUtils.closeQuietly(ap);
}
}
}
private void checkCompatible(AppPackage ap, ConfigPackage cp)
{
if (cp == null) {
return;
}
String requiredAppPackageName = cp.getAppPackageName();
if (requiredAppPackageName != null && !requiredAppPackageName.equals(ap.getAppPackageName())) {
throw new CliException("Config package requires an app package name of \"" + requiredAppPackageName + "\". The app package given has the name of \"" + ap.getAppPackageName() + "\"");
}
String requiredAppPackageMinVersion = cp.getAppPackageMinVersion();
if (requiredAppPackageMinVersion != null && VersionInfo.compare(requiredAppPackageMinVersion, ap.getAppPackageVersion()) > 0) {
throw new CliException("Config package requires an app package minimum version of \"" + requiredAppPackageMinVersion + "\". The app package given is of version \"" + ap.getAppPackageVersion() + "\"");
}
String requiredAppPackageMaxVersion = cp.getAppPackageMaxVersion();
if (requiredAppPackageMaxVersion != null && VersionInfo.compare(requiredAppPackageMaxVersion, ap.getAppPackageVersion()) < 0) {
throw new CliException("Config package requires an app package maximum version of \"" + requiredAppPackageMaxVersion + "\". The app package given is of version \"" + ap.getAppPackageVersion() + "\"");
}
}
private void launchAppPackage(AppPackage ap, ConfigPackage cp, LaunchCommandLineInfo commandLineInfo, ConsoleReader reader) throws Exception
{
new LaunchCommand().execute(getLaunchAppPackageArgs(ap, cp, commandLineInfo, reader), reader);
}
String[] getLaunchAppPackageArgs(AppPackage ap, ConfigPackage cp, LaunchCommandLineInfo commandLineInfo, ConsoleReader reader) throws Exception
{
String matchAppName = null;
if (commandLineInfo.args.length > 1) {
matchAppName = commandLineInfo.args[1];
}
List<AppInfo> applications = new ArrayList<AppInfo>(ap.getApplications());
if (matchAppName != null) {
Iterator<AppInfo> it = applications.iterator();
while (it.hasNext()) {
AppInfo ai = it.next();
if ((commandLineInfo.exactMatch && !ai.name.equals(matchAppName))
|| !ai.name.toLowerCase().matches(".*" + matchAppName.toLowerCase() + ".*")) {
it.remove();
}
}
}
AppInfo selectedApp = null;
if (applications.isEmpty()) {
throw new CliException("No applications in Application Package" + (matchAppName != null ? " matching \"" + matchAppName + "\"" : ""));
} else if (applications.size() == 1) {
selectedApp = applications.get(0);
} else {
//Store the appNames sorted in alphabetical order and their position in matchingAppFactories list
TreeMap<String, Integer> appNamesInAlphabeticalOrder = new TreeMap<String, Integer>();
// Display matching applications
for (int i = 0; i < applications.size(); i++) {
String appName = applications.get(i).name;
appNamesInAlphabeticalOrder.put(appName, i);
}
//Create a mapping between the app display number and original index at matchingAppFactories
int index = 1;
HashMap<Integer, Integer> displayIndexToOriginalUnsortedIndexMap = new HashMap<Integer, Integer>();
for (Map.Entry<String, Integer> entry : appNamesInAlphabeticalOrder.entrySet()) {
//Map display number of the app to original unsorted index
displayIndexToOriginalUnsortedIndexMap.put(index, entry.getValue());
//Display the app names
System.out.printf("%3d. %s\n", index++, entry.getKey());
}
// Exit if not in interactive mode
if (!consolePresent) {
throw new CliException("More than one application in Application Package match '" + matchAppName + "'");
} else {
boolean useHistory = reader.isHistoryEnabled();
reader.setHistoryEnabled(false);
History previousHistory = reader.getHistory();
History dummyHistory = new MemoryHistory();
reader.setHistory(dummyHistory);
List<Completer> completers = new ArrayList<Completer>(reader.getCompleters());
for (Completer c : completers) {
reader.removeCompleter(c);
}
reader.setHandleUserInterrupt(true);
String optionLine;
try {
optionLine = reader.readLine("Choose application: ");
} finally {
reader.setHandleUserInterrupt(false);
reader.setHistoryEnabled(useHistory);
reader.setHistory(previousHistory);
for (Completer c : completers) {
reader.addCompleter(c);
}
}
try {
int option = Integer.parseInt(optionLine);
if (0 < option && option <= applications.size()) {
int appIndex = displayIndexToOriginalUnsortedIndexMap.get(option);
selectedApp = applications.get(appIndex);
}
} catch (Exception ex) {
// ignore
}
}
}
if (selectedApp == null) {
throw new CliException("No application selected");
}
DTConfiguration launchProperties = getLaunchAppPackageProperties(ap, cp, commandLineInfo, selectedApp.name);
String appFile = ap.tempDirectory() + "/app/" + selectedApp.file;
List<String> launchArgs = new ArrayList<String>();
launchArgs.add("launch");
launchArgs.add("-exactMatch");
List<String> absClassPath = new ArrayList<String>(ap.getClassPath());
for (int i = 0; i < absClassPath.size(); i++) {
String path = absClassPath.get(i);
if (!path.startsWith("/")) {
absClassPath.set(i, ap.tempDirectory() + "/" + path);
}
}
if (cp != null) {
StringBuilder files = new StringBuilder();
for (String file : cp.getClassPath()) {
if (files.length() != 0) {
files.append(',');
}
files.append(cp.tempDirectory()).append(File.separatorChar).append(file);
}
if (!StringUtils.isBlank(files.toString())) {
if (commandLineInfo.libjars != null) {
commandLineInfo.libjars = files.toString() + "," + commandLineInfo.libjars;
} else {
commandLineInfo.libjars = files.toString();
}
}
files.setLength(0);
for (String file : cp.getFiles()) {
if (files.length() != 0) {
files.append(',');
}
files.append(cp.tempDirectory()).append(File.separatorChar).append(file);
}
if (!StringUtils.isBlank(files.toString())) {
if (commandLineInfo.files != null) {
commandLineInfo.files = files.toString() + "," + commandLineInfo.files;
} else {
commandLineInfo.files = files.toString();
}
}
}
StringBuilder libjarsVal = new StringBuilder();
if (!absClassPath.isEmpty() || commandLineInfo.libjars != null) {
if (!absClassPath.isEmpty()) {
libjarsVal.append(org.apache.commons.lang3.StringUtils.join(absClassPath, ','));
}
if (commandLineInfo.libjars != null) {
if (libjarsVal.length() > 0) {
libjarsVal.append(",");
}
libjarsVal.append(commandLineInfo.libjars);
}
}
if (appFile.endsWith(".json") || appFile.endsWith(".properties")) {
if (libjarsVal.length() > 0) {
libjarsVal.append(",");
}
libjarsVal.append(ap.tempDirectory()).append("/app/*.jar");
}
if (libjarsVal.length() > 0) {
launchArgs.add("-libjars");
launchArgs.add(libjarsVal.toString());
}
File launchPropertiesFile = new File(ap.tempDirectory(), "launch.xml");
launchProperties.writeToFile(launchPropertiesFile, "");
launchArgs.add("-conf");
launchArgs.add(launchPropertiesFile.getCanonicalPath());
if (commandLineInfo.localMode) {
launchArgs.add("-local");
}
if (commandLineInfo.archives != null) {
launchArgs.add("-archives");
launchArgs.add(commandLineInfo.archives);
}
if (commandLineInfo.files != null) {
launchArgs.add("-files");
launchArgs.add(commandLineInfo.files);
}
if (commandLineInfo.origAppId != null) {
launchArgs.add("-originalAppId");
launchArgs.add(commandLineInfo.origAppId);
}
if (commandLineInfo.queue != null) {
launchArgs.add("-queue");
launchArgs.add(commandLineInfo.queue);
}
launchArgs.add(appFile);
if (!appFile.endsWith(".json") && !appFile.endsWith(".properties")) {
launchArgs.add(selectedApp.name);
}
LOG.debug("Launch command: {}", StringUtils.join(launchArgs, " "));
return launchArgs.toArray(new String[]{});
}
DTConfiguration getLaunchAppPackageProperties(AppPackage ap, ConfigPackage cp, LaunchCommandLineInfo commandLineInfo, String appName) throws Exception
{
DTConfiguration launchProperties = new DTConfiguration();
List<AppInfo> applications = ap.getApplications();
AppInfo selectedApp = null;
for (AppInfo app : applications) {
if (app.name.equals(appName)) {
selectedApp = app;
break;
}
}
Map<String, String> defaultProperties = selectedApp == null ? ap.getDefaultProperties() : selectedApp.defaultProperties;
Set<String> requiredProperties = new TreeSet<String>(selectedApp == null ? ap.getRequiredProperties() : selectedApp.requiredProperties);
for (Map.Entry<String, String> entry : defaultProperties.entrySet()) {
launchProperties.set(entry.getKey(), entry.getValue(), Scope.TRANSIENT, null);
requiredProperties.remove(entry.getKey());
}
// settings specified in the user's environment take precedence over defaults in package.
// since both are merged into a single -conf option below, apply them on top of the defaults here.
File confFile = new File(StramClientUtils.getUserDTDirectory(), StramClientUtils.DT_SITE_XML_FILE);
if (confFile.exists()) {
Configuration userConf = new Configuration(false);
userConf.addResource(new Path(confFile.toURI()));
Iterator<Entry<String, String>> it = userConf.iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
// filter relevant entries
if (entry.getKey().startsWith(StreamingApplication.DT_PREFIX)) {
launchProperties.set(entry.getKey(), entry.getValue(), Scope.TRANSIENT, null);
requiredProperties.remove(entry.getKey());
}
}
}
if (commandLineInfo.apConfigFile != null) {
DTConfiguration givenConfig = new DTConfiguration();
givenConfig.loadFile(new File(ap.tempDirectory() + "/conf/" + commandLineInfo.apConfigFile));
for (Map.Entry<String, String> entry : givenConfig) {
launchProperties.set(entry.getKey(), entry.getValue(), Scope.TRANSIENT, null);
requiredProperties.remove(entry.getKey());
}
}
if (cp != null) {
Map<String, String> properties = cp.getProperties(appName);
for (Map.Entry<String, String> entry : properties.entrySet()) {
launchProperties.set(entry.getKey(), entry.getValue(), Scope.TRANSIENT, null);
requiredProperties.remove(entry.getKey());
}
} else if (commandLineInfo.configFile != null) {
DTConfiguration givenConfig = new DTConfiguration();
givenConfig.loadFile(new File(commandLineInfo.configFile));
for (Map.Entry<String, String> entry : givenConfig) {
launchProperties.set(entry.getKey(), entry.getValue(), Scope.TRANSIENT, null);
requiredProperties.remove(entry.getKey());
}
}
if (commandLineInfo.overrideProperties != null) {
for (Map.Entry<String, String> entry : commandLineInfo.overrideProperties.entrySet()) {
launchProperties.set(entry.getKey(), entry.getValue(), Scope.TRANSIENT, null);
requiredProperties.remove(entry.getKey());
}
}
// now look at whether it is in default configuration
for (Map.Entry<String, String> entry : conf) {
if (StringUtils.isNotBlank(entry.getValue())) {
requiredProperties.remove(entry.getKey());
}
}
if (!requiredProperties.isEmpty()) {
throw new CliException("Required properties not set: " + StringUtils.join(requiredProperties, ", "));
}
//StramClientUtils.evalProperties(launchProperties);
return launchProperties;
}
private class GetAppPackageOperatorsCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String[] tmpArgs = new String[args.length - 1];
System.arraycopy(args, 1, tmpArgs, 0, args.length - 1);
GetOperatorClassesCommandLineInfo commandLineInfo = getGetOperatorClassesCommandLineInfo(tmpArgs);
AppPackage ap = null;
try {
ap = newAppPackageInstance(new File(expandFileName(commandLineInfo.args[0], true)));
List<String> newArgs = new ArrayList<String>();
List<String> jars = new ArrayList<String>();
for (String jar : ap.getAppJars()) {
jars.add(ap.tempDirectory() + "/app/" + jar);
}
for (String libJar : ap.getClassPath()) {
jars.add(ap.tempDirectory() + "/" + libJar);
}
newArgs.add("get-jar-operator-classes");
if (commandLineInfo.parent != null) {
newArgs.add("-parent");
newArgs.add(commandLineInfo.parent);
}
newArgs.add(StringUtils.join(jars, ","));
for (int i = 1; i < commandLineInfo.args.length; i++) {
newArgs.add(commandLineInfo.args[i]);
}
LOG.debug("Executing: " + newArgs);
new GetJarOperatorClassesCommand().execute(newArgs.toArray(new String[]{}), reader);
}
finally {
IOUtils.closeQuietly(ap);
}
}
}
private class GetAppPackageOperatorPropertiesCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
AppPackage ap = null;
try {
ap = newAppPackageInstance(new File(expandFileName(args[1], true)));
List<String> newArgs = new ArrayList<String>();
List<String> jars = new ArrayList<String>();
for (String jar : ap.getAppJars()) {
jars.add(ap.tempDirectory() + "/app/" + jar);
}
for (String libJar : ap.getClassPath()) {
jars.add(ap.tempDirectory() + "/" + libJar);
}
newArgs.add("get-jar-operator-properties");
newArgs.add(StringUtils.join(jars, ","));
newArgs.add(args[2]);
new GetJarOperatorPropertiesCommand().execute(newArgs.toArray(new String[]{}), reader);
}
finally {
IOUtils.closeQuietly(ap);
}
}
}
private enum AttributesType
{
APPLICATION, OPERATOR, PORT
}
private class ListAttributesCommand implements Command
{
private final AttributesType type;
protected ListAttributesCommand(@NotNull AttributesType type)
{
this.type = Preconditions.checkNotNull(type);
}
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
JSONObject result;
if (type == AttributesType.APPLICATION) {
result = TypeDiscoverer.getAppAttributes();
}
else if (type == AttributesType.OPERATOR) {
result = TypeDiscoverer.getOperatorAttributes();
}
else {
//get port attributes
result = TypeDiscoverer.getPortAttributes();
}
printJson(result);
}
}
@SuppressWarnings("static-access")
public static class GetPhysicalPropertiesCommandLineOptions
{
final Options options = new Options();
final Option propertyName = add(OptionBuilder.withArgName("property name").hasArg().withDescription("The name of the property whose value needs to be retrieved").create("propertyName"));
final Option waitTime = add (OptionBuilder.withArgName("wait time").hasArg().withDescription("How long to wait to get the result").create("waitTime"));
private Option add(Option opt)
{
this.options.addOption(opt);
return opt;
}
}
private static GetPhysicalPropertiesCommandLineOptions GET_PHYSICAL_PROPERTY_OPTIONS = new GetPhysicalPropertiesCommandLineOptions();
@SuppressWarnings("static-access")
public static class LaunchCommandLineOptions
{
final Options options = new Options();
final Option local = add(new Option("local", "Run application in local mode."));
final Option configFile = add(OptionBuilder.withArgName("configuration file").hasArg().withDescription("Specify an application configuration file.").create("conf"));
final Option apConfigFile = add(OptionBuilder.withArgName("app package configuration file").hasArg().withDescription("Specify an application configuration file within the app package if launching an app package.").create("apconf"));
final Option defProperty = add(OptionBuilder.withArgName("property=value").hasArg().withDescription("Use value for given property.").create("D"));
final Option libjars = add(OptionBuilder.withArgName("comma separated list of libjars").hasArg().withDescription("Specify comma separated jar files or other resource files to include in the classpath.").create("libjars"));
final Option files = add(OptionBuilder.withArgName("comma separated list of files").hasArg().withDescription("Specify comma separated files to be copied on the compute machines.").create("files"));
final Option archives = add(OptionBuilder.withArgName("comma separated list of archives").hasArg().withDescription("Specify comma separated archives to be unarchived on the compute machines.").create("archives"));
final Option ignorePom = add(new Option("ignorepom", "Do not run maven to find the dependency"));
final Option originalAppID = add(OptionBuilder.withArgName("application id").hasArg().withDescription("Specify original application identifier for restart.").create("originalAppId"));
final Option exactMatch = add(new Option("exactMatch", "Only consider applications with exact app name"));
final Option queue = add(OptionBuilder.withArgName("queue name").hasArg().withDescription("Specify the queue to launch the application").create("queue"));
private Option add(Option opt)
{
this.options.addOption(opt);
return opt;
}
}
private static LaunchCommandLineOptions LAUNCH_OPTIONS = new LaunchCommandLineOptions();
static LaunchCommandLineInfo getLaunchCommandLineInfo(String[] args) throws ParseException
{
CommandLineParser parser = new PosixParser();
LaunchCommandLineInfo result = new LaunchCommandLineInfo();
CommandLine line = parser.parse(LAUNCH_OPTIONS.options, args);
result.localMode = line.hasOption(LAUNCH_OPTIONS.local.getOpt());
result.configFile = line.getOptionValue(LAUNCH_OPTIONS.configFile.getOpt());
result.apConfigFile = line.getOptionValue(LAUNCH_OPTIONS.apConfigFile.getOpt());
result.ignorePom = line.hasOption(LAUNCH_OPTIONS.ignorePom.getOpt());
String[] defs = line.getOptionValues(LAUNCH_OPTIONS.defProperty.getOpt());
if (defs != null) {
result.overrideProperties = new HashMap<String, String>();
for (String def : defs) {
int equal = def.indexOf('=');
if (equal < 0) {
result.overrideProperties.put(def, null);
}
else {
result.overrideProperties.put(def.substring(0, equal), def.substring(equal + 1));
}
}
}
result.libjars = line.getOptionValue(LAUNCH_OPTIONS.libjars.getOpt());
result.archives = line.getOptionValue(LAUNCH_OPTIONS.archives.getOpt());
result.files = line.getOptionValue(LAUNCH_OPTIONS.files.getOpt());
result.queue = line.getOptionValue(LAUNCH_OPTIONS.queue.getOpt());
result.args = line.getArgs();
result.origAppId = line.getOptionValue(LAUNCH_OPTIONS.originalAppID.getOpt());
result.exactMatch = line.hasOption("exactMatch");
return result;
}
static class LaunchCommandLineInfo
{
boolean localMode;
boolean ignorePom;
String configFile;
String apConfigFile;
Map<String, String> overrideProperties;
String libjars;
String files;
String queue;
String archives;
String origAppId;
boolean exactMatch;
String[] args;
}
@SuppressWarnings("static-access")
public static Options getShowLogicalPlanCommandLineOptions()
{
Options options = new Options();
Option libjars = OptionBuilder.withArgName("comma separated list of jars").hasArg().withDescription("Specify comma separated jar/resource files to include in the classpath.").create("libjars");
Option ignorePom = new Option("ignorepom", "Do not run maven to find the dependency");
Option exactMatch = new Option("exactMatch", "Only consider exact match for app name");
options.addOption(libjars);
options.addOption(ignorePom);
options.addOption(exactMatch);
return options;
}
private static ShowLogicalPlanCommandLineInfo getShowLogicalPlanCommandLineInfo(String[] args) throws ParseException
{
CommandLineParser parser = new PosixParser();
ShowLogicalPlanCommandLineInfo result = new ShowLogicalPlanCommandLineInfo();
CommandLine line = parser.parse(getShowLogicalPlanCommandLineOptions(), args);
result.libjars = line.getOptionValue("libjars");
result.ignorePom = line.hasOption("ignorepom");
result.args = line.getArgs();
result.exactMatch = line.hasOption("exactMatch");
return result;
}
private static class ShowLogicalPlanCommandLineInfo
{
String libjars;
boolean ignorePom;
String[] args;
boolean exactMatch;
}
public void mainHelper() throws Exception
{
init();
run();
System.exit(lastCommandError ? 1 : 0);
}
public static void main(final String[] args) throws Exception
{
final DTCli shell = new DTCli();
shell.preImpersonationInit(args);
String hadoopUserName = System.getenv("HADOOP_USER_NAME");
if (UserGroupInformation.isSecurityEnabled()
&& StringUtils.isNotBlank(hadoopUserName)
&& !hadoopUserName.equals(UserGroupInformation.getLoginUser().getUserName())) {
LOG.info("You ({}) are running as user {}", UserGroupInformation.getLoginUser().getUserName(), hadoopUserName);
UserGroupInformation ugi
= UserGroupInformation.createProxyUser(hadoopUserName, UserGroupInformation.getLoginUser());
ugi.doAs(new PrivilegedExceptionAction<Void>()
{
@Override
public Void run() throws Exception
{
shell.mainHelper();
return null;
}
});
}
else {
shell.mainHelper();
}
}
}
|
SPOI-5385 Print stack trace when exception occurs
|
engine/src/main/java/com/datatorrent/stram/cli/DTCli.java
|
SPOI-5385 Print stack trace when exception occurs
|
|
Java
|
apache-2.0
|
f9ff233350f3b1cb9ebbb6187059f0f74c9f1f9e
| 0
|
i-net-software/JWebAssembly,i-net-software/JWebAssembly
|
/*
* Copyright 2017 Volker Berlin (i-net software)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.inetsoftware.jwebassembly.binary;
import java.util.ArrayList;
import java.util.List;
import de.inetsoftware.jwebassembly.module.ValueType;
/**
* An entry in the type section of the WebAssembly.
*
* @author Volker Berlin
*/
class FunctionType {
List<ValueType> params = new ArrayList<>();
ValueType result; // Java has only one return parameter
}
|
src/de/inetsoftware/jwebassembly/binary/FunctionType.java
|
/*
* Copyright 2017 Volker Berlin (i-net software)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.inetsoftware.jwebassembly.binary;
import java.util.ArrayList;
import java.util.List;
import de.inetsoftware.jwebassembly.module.ValueType;
/**
* An entry in the type section of the WebAssembly.
*
* @author Volker Berlin
*/
class FunctionType {
List<ValueType> params = new ArrayList<>();
ValueType result; // Java has only one return parameter
}
|
line encoding
|
src/de/inetsoftware/jwebassembly/binary/FunctionType.java
|
line encoding
|
|
Java
|
apache-2.0
|
e1eaaf406f7125bd699a764e101798beb6557bb3
| 0
|
pmlopes/yoke,tietang/yoke,tietang/yoke,tietang/yoke,valerinistor/yoke,pac4j/yoke,pmlopes/yoke,pac4j/yoke,valerinistor/yoke,valerinistor/yoke,pac4j/yoke
|
package com.jetdrone.vertx.yoke.test.middleware;
import com.jetdrone.vertx.yoke.Middleware;
import com.jetdrone.vertx.yoke.Yoke;
import com.jetdrone.vertx.yoke.annotations.GET;
import com.jetdrone.vertx.yoke.annotations.Produces;
import com.jetdrone.vertx.yoke.middleware.YokeRequest;
import com.jetdrone.vertx.yoke.test.Response;
import com.jetdrone.vertx.yoke.test.YokeTester;
import org.junit.Test;
import org.vertx.java.core.Handler;
import org.vertx.java.core.json.JsonObject;
import org.vertx.testtools.TestVerticle;
import java.util.regex.Pattern;
import static org.vertx.testtools.VertxAssert.*;
public class Router extends TestVerticle {
public static class TestRouter {
@GET("/ws")
public void get(YokeRequest request) {
request.response().end("Hello ws!");
}
}
@Test
public void testAnnotatedRouter() {
Yoke yoke = new Yoke(this);
yoke.use(com.jetdrone.vertx.yoke.middleware.Router.from(new TestRouter()));
new YokeTester(vertx, yoke).request("GET", "/ws", new Handler<Response>() {
@Override
public void handle(Response resp) {
assertEquals(200, resp.getStatusCode());
assertEquals("Hello ws!", resp.body.toString());
testComplete();
}
});
}
public static class TestRouter2 {
@GET("/ws")
@Produces({"text/plain"})
public void get(YokeRequest request) {
request.response().end("Hello ws!");
}
}
@Test
public void testAnnotatedRouter2() {
Yoke yoke = new Yoke(this);
yoke.use(com.jetdrone.vertx.yoke.middleware.Router.from(new TestRouter2()));
new YokeTester(vertx, yoke).request("GET", "/ws", new Handler<Response>() {
@Override
public void handle(Response resp) {
assertEquals(200, resp.getStatusCode());
assertEquals("Hello ws!", resp.body.toString());
testComplete();
}
});
}
@Test
public void testRouterWithParams() {
Yoke yoke = new Yoke(this);
yoke.use(new com.jetdrone.vertx.yoke.middleware.Router() {{
get("/api/:userId", new Middleware() {
@Override
public void handle(YokeRequest request, Handler<Object> next) {
assertNotNull(request.get("user"));
assertTrue(request.get("user") instanceof JsonObject);
request.response().end("OK");
}
});
param("userId", new Middleware() {
@Override
public void handle(YokeRequest request, Handler<Object> next) {
assertEquals("1", request.params().get("userId"));
// pretend that we went on some DB and got a json object representing the user
request.put("user", new JsonObject("{\"id\":" + request.params().get("userId") + "}"));
next.handle(null);
}
});
}});
new YokeTester(vertx, yoke).request("GET", "/api/1", new Handler<Response>() {
@Override
public void handle(Response resp) {
assertEquals(200, resp.getStatusCode());
assertEquals("OK", resp.body.toString());
testComplete();
}
});
}
@Test
public void testRouterWithRegExParamsFail() {
Yoke yoke = new Yoke(this);
yoke.use(new com.jetdrone.vertx.yoke.middleware.Router() {{
get("/api/:userId", new Middleware() {
@Override
public void handle(YokeRequest request, Handler<Object> next) {
request.response().end("OK");
}
});
param("userId", Pattern.compile("[1-9][0-9]"));
}});
// the pattern expects 2 digits
new YokeTester(vertx, yoke).request("GET", "/api/1", new Handler<Response>() {
@Override
public void handle(Response resp) {
assertEquals(400, resp.getStatusCode());
testComplete();
}
});
}
@Test
public void testRouterWithRegExParamsPass() {
Yoke yoke = new Yoke(this);
yoke.use(new com.jetdrone.vertx.yoke.middleware.Router() {{
get("/api/:userId", new Middleware() {
@Override
public void handle(YokeRequest request, Handler<Object> next) {
request.response().end("OK");
}
});
param("userId", Pattern.compile("[1-9][0-9]"));
}});
// the pattern expects 2 digits
new YokeTester(vertx, yoke).request("GET", "/api/10", new Handler<Response>() {
@Override
public void handle(Response resp) {
assertEquals(200, resp.getStatusCode());
testComplete();
}
});
}
@Test
public void testTrailingSlashes() {
final Yoke yoke = new Yoke(this);
yoke.use(new com.jetdrone.vertx.yoke.middleware.Router() {{
get("/api", new Middleware() {
@Override
public void handle(YokeRequest request, Handler<Object> next) {
request.response().end("OK");
}
});
}});
final YokeTester yokeAssert = new YokeTester(vertx, yoke);
yokeAssert.request("GET", "/api", new Handler<Response>() {
@Override
public void handle(Response resp) {
assertEquals(200, resp.getStatusCode());
yokeAssert.request("GET", "/api/", new Handler<Response>() {
@Override
public void handle(Response resp) {
assertEquals(200, resp.getStatusCode());
testComplete();
}
});
}
});
}
@Test
public void testDash() {
final Yoke yoke = new Yoke(this);
yoke.use(new com.jetdrone.vertx.yoke.middleware.Router() {{
get("/api-stable", new Middleware() {
@Override
public void handle(YokeRequest request, Handler<Object> next) {
request.response().end("OK");
}
});
}});
final YokeTester yokeAssert = new YokeTester(vertx, yoke);
yokeAssert.request("GET", "/api-stable", new Handler<Response>() {
@Override
public void handle(Response resp) {
assertEquals(200, resp.getStatusCode());
testComplete();
}
});
}
}
|
framework/src/test/java/com/jetdrone/vertx/yoke/test/middleware/Router.java
|
package com.jetdrone.vertx.yoke.test.middleware;
import com.jetdrone.vertx.yoke.Middleware;
import com.jetdrone.vertx.yoke.Yoke;
import com.jetdrone.vertx.yoke.annotations.GET;
import com.jetdrone.vertx.yoke.annotations.Produces;
import com.jetdrone.vertx.yoke.middleware.YokeRequest;
import com.jetdrone.vertx.yoke.test.Response;
import com.jetdrone.vertx.yoke.test.YokeTester;
import org.junit.Test;
import org.vertx.java.core.Handler;
import org.vertx.java.core.json.JsonObject;
import org.vertx.testtools.TestVerticle;
import java.util.regex.Pattern;
import static org.vertx.testtools.VertxAssert.*;
public class Router extends TestVerticle {
public static class TestRouter {
@GET("/ws")
public void get(YokeRequest request) {
request.response().end("Hello ws!");
}
}
@Test
public void testAnnotatedRouter() {
Yoke yoke = new Yoke(this);
yoke.use(com.jetdrone.vertx.yoke.middleware.Router.from(new TestRouter()));
new YokeTester(vertx, yoke).request("GET", "/ws", new Handler<Response>() {
@Override
public void handle(Response resp) {
assertEquals(200, resp.getStatusCode());
assertEquals("Hello ws!", resp.body.toString());
testComplete();
}
});
}
public static class TestRouter2 {
@GET("/ws")
@Produces({"text/plain"})
public void get(YokeRequest request) {
request.response().end("Hello ws!");
}
}
@Test
public void testAnnotatedRouter2() {
Yoke yoke = new Yoke(this);
yoke.use(com.jetdrone.vertx.yoke.middleware.Router.from(new TestRouter2()));
new YokeTester(vertx, yoke).request("GET", "/ws", new Handler<Response>() {
@Override
public void handle(Response resp) {
assertEquals(200, resp.getStatusCode());
assertEquals("Hello ws!", resp.body.toString());
testComplete();
}
});
}
@Test
public void testRouterWithParams() {
Yoke yoke = new Yoke(this);
yoke.use(new com.jetdrone.vertx.yoke.middleware.Router() {{
get("/api/:userId", new Middleware() {
@Override
public void handle(YokeRequest request, Handler<Object> next) {
assertNotNull(request.get("user"));
assertTrue(request.get("user") instanceof JsonObject);
request.response().end("OK");
}
});
param("userId", new Middleware() {
@Override
public void handle(YokeRequest request, Handler<Object> next) {
assertEquals("1", request.params().get("userId"));
// pretend that we went on some DB and got a json object representing the user
request.put("user", new JsonObject("{\"id\":" + request.params().get("userId") + "}"));
next.handle(null);
}
});
}});
new YokeTester(vertx, yoke).request("GET", "/api/1", new Handler<Response>() {
@Override
public void handle(Response resp) {
assertEquals(200, resp.getStatusCode());
assertEquals("OK", resp.body.toString());
testComplete();
}
});
}
@Test
public void testRouterWithRegExParamsFail() {
Yoke yoke = new Yoke(this);
yoke.use(new com.jetdrone.vertx.yoke.middleware.Router() {{
get("/api/:userId", new Middleware() {
@Override
public void handle(YokeRequest request, Handler<Object> next) {
request.response().end("OK");
}
});
param("userId", Pattern.compile("[1-9][0-9]"));
}});
// the pattern expects 2 digits
new YokeTester(vertx, yoke).request("GET", "/api/1", new Handler<Response>() {
@Override
public void handle(Response resp) {
assertEquals(400, resp.getStatusCode());
testComplete();
}
});
}
@Test
public void testRouterWithRegExParamsPass() {
Yoke yoke = new Yoke(this);
yoke.use(new com.jetdrone.vertx.yoke.middleware.Router() {{
get("/api/:userId", new Middleware() {
@Override
public void handle(YokeRequest request, Handler<Object> next) {
request.response().end("OK");
}
});
param("userId", Pattern.compile("[1-9][0-9]"));
}});
// the pattern expects 2 digits
new YokeTester(vertx, yoke).request("GET", "/api/10", new Handler<Response>() {
@Override
public void handle(Response resp) {
assertEquals(200, resp.getStatusCode());
testComplete();
}
});
}
@Test
public void testTrailingSlashes() {
final Yoke yoke = new Yoke(this);
yoke.use(new com.jetdrone.vertx.yoke.middleware.Router() {{
get("/api", new Middleware() {
@Override
public void handle(YokeRequest request, Handler<Object> next) {
request.response().end("OK");
}
});
}});
final YokeTester yokeAssert = new YokeTester(vertx, yoke);
yokeAssert.request("GET", "/api", new Handler<Response>() {
@Override
public void handle(Response resp) {
assertEquals(200, resp.getStatusCode());
yokeAssert.request("GET", "/api/", new Handler<Response>() {
@Override
public void handle(Response resp) {
assertEquals(200, resp.getStatusCode());
testComplete();
}
});
}
});
}
}
|
confirm that - is not a problem
|
framework/src/test/java/com/jetdrone/vertx/yoke/test/middleware/Router.java
|
confirm that - is not a problem
|
|
Java
|
apache-2.0
|
d4fcf46dedd6a52429e537c6f188a0b15d734a47
| 0
|
SingingTree/hapi-fhir,aemay2/hapi-fhir,eug48/hapi-fhir,eug48/hapi-fhir,jamesagnew/hapi-fhir,aemay2/hapi-fhir,jamesagnew/hapi-fhir,eug48/hapi-fhir,jamesagnew/hapi-fhir,aemay2/hapi-fhir,aemay2/hapi-fhir,eug48/hapi-fhir,jamesagnew/hapi-fhir,jamesagnew/hapi-fhir,SingingTree/hapi-fhir,eug48/hapi-fhir,SingingTree/hapi-fhir,SingingTree/hapi-fhir,SingingTree/hapi-fhir,aemay2/hapi-fhir,jamesagnew/hapi-fhir,aemay2/hapi-fhir,SingingTree/hapi-fhir
|
package ca.uhn.fhir.to;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.FhirVersionEnum;
import ca.uhn.fhir.context.RuntimeResourceDefinition;
import ca.uhn.fhir.model.api.Bundle;
import ca.uhn.fhir.model.api.ExtensionDt;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.dstu.resource.Conformance;
import ca.uhn.fhir.model.dstu.resource.Conformance.Rest;
import ca.uhn.fhir.model.primitive.DecimalDt;
import ca.uhn.fhir.rest.client.GenericClient;
import ca.uhn.fhir.rest.client.IClientInterceptor;
import ca.uhn.fhir.rest.client.api.IHttpRequest;
import ca.uhn.fhir.rest.client.api.IHttpResponse;
import ca.uhn.fhir.rest.server.Constants;
import ca.uhn.fhir.rest.server.EncodingEnum;
import ca.uhn.fhir.to.model.HomeRequest;
import ca.uhn.fhir.util.ExtensionConstants;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicHeader;
import org.hl7.fhir.dstu3.model.CapabilityStatement;
import org.hl7.fhir.dstu3.model.CapabilityStatement.CapabilityStatementRestComponent;
import org.hl7.fhir.dstu3.model.CapabilityStatement.CapabilityStatementRestResourceComponent;
import org.hl7.fhir.dstu3.model.DecimalType;
import org.hl7.fhir.dstu3.model.Extension;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IDomainResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.thymeleaf.TemplateEngine;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import static org.apache.commons.lang3.StringUtils.defaultString;
public class BaseController {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BaseController.class);
static final String PARAM_RESOURCE = "resource";
static final String RESOURCE_COUNT_EXT_URL = "http://hl7api.sourceforge.net/hapi-fhir/res/extdefs.html#resourceCount";
@Autowired
protected TesterConfig myConfig;
private Map<FhirVersionEnum, FhirContext> myContexts = new HashMap<FhirVersionEnum, FhirContext>();
private List<String> myFilterHeaders;
@Autowired
private TemplateEngine myTemplateEngine;
public BaseController() {
super();
}
protected IBaseResource addCommonParams(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
if (myConfig.getDebugTemplatesMode()) {
myTemplateEngine.getCacheManager().clearAllCaches();
}
final String serverId = theRequest.getServerIdWithDefault(myConfig);
final String serverBase = theRequest.getServerBase(theServletRequest, myConfig);
final String serverName = theRequest.getServerName(myConfig);
final String apiKey = theRequest.getApiKey(theServletRequest, myConfig);
theModel.put("serverId", serverId);
theModel.put("base", serverBase);
theModel.put("baseName", serverName);
theModel.put("apiKey", apiKey);
theModel.put("resourceName", defaultString(theRequest.getResource()));
theModel.put("encoding", theRequest.getEncoding());
theModel.put("pretty", theRequest.getPretty());
theModel.put("_summary", theRequest.get_summary());
theModel.put("serverEntries", myConfig.getIdToServerName());
return loadAndAddConf(theServletRequest, theRequest, theModel);
}
private Header[] applyHeaderFilters(Header[] theAllHeaders) {
if (myFilterHeaders == null || myFilterHeaders.isEmpty()) {
return theAllHeaders;
}
ArrayList<Header> retVal = new ArrayList<Header>();
for (Header next : theAllHeaders) {
if (!myFilterHeaders.contains(next.getName().toLowerCase())) {
retVal.add(next);
}
}
return retVal.toArray(new Header[retVal.size()]);
}
private Header[] applyHeaderFilters(Map<String, List<String>> theAllHeaders) {
ArrayList<Header> retVal = new ArrayList<Header>();
for (String nextKey : theAllHeaders.keySet()) {
for (String nextValue : theAllHeaders.get(nextKey)) {
if (myFilterHeaders == null || !myFilterHeaders.contains(nextKey.toLowerCase())) {
retVal.add(new BasicHeader(nextKey, nextValue));
}
}
}
return retVal.toArray(new Header[retVal.size()]);
}
private String format(String theResultBody, EncodingEnum theEncodingEnum) {
String str = StringEscapeUtils.escapeHtml4(theResultBody);
if (str == null || theEncodingEnum == null) {
return str;
}
StringBuilder b = new StringBuilder();
if (theEncodingEnum == EncodingEnum.JSON) {
boolean inValue = false;
boolean inQuote = false;
for (int i = 0; i < str.length(); i++) {
char prevChar = (i > 0) ? str.charAt(i - 1) : ' ';
char nextChar = str.charAt(i);
char nextChar2 = (i + 1) < str.length() ? str.charAt(i + 1) : ' ';
char nextChar3 = (i + 2) < str.length() ? str.charAt(i + 2) : ' ';
char nextChar4 = (i + 3) < str.length() ? str.charAt(i + 3) : ' ';
char nextChar5 = (i + 4) < str.length() ? str.charAt(i + 4) : ' ';
char nextChar6 = (i + 5) < str.length() ? str.charAt(i + 5) : ' ';
if (inQuote) {
b.append(nextChar);
if (prevChar != '\\' && nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
b.append("quot;</span>");
i += 5;
inQuote = false;
} else if (nextChar == '\\' && nextChar2 == '"') {
b.append("quot;</span>");
i += 5;
inQuote = false;
}
} else {
if (nextChar == ':') {
inValue = true;
b.append(nextChar);
} else if (nextChar == '[' || nextChar == '{') {
b.append("<span class='hlControl'>");
b.append(nextChar);
b.append("</span>");
inValue = false;
} else if (nextChar == '{' || nextChar == '}' || nextChar == ',') {
b.append("<span class='hlControl'>");
b.append(nextChar);
b.append("</span>");
inValue = false;
} else if (nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
if (inValue) {
b.append("<span class='hlQuot'>"");
} else {
b.append("<span class='hlTagName'>"");
}
inQuote = true;
i += 5;
} else if (nextChar == ':') {
b.append("<span class='hlControl'>");
b.append(nextChar);
b.append("</span>");
inValue = true;
} else {
b.append(nextChar);
}
}
}
} else {
boolean inQuote = false;
boolean inTag = false;
for (int i = 0; i < str.length(); i++) {
char nextChar = str.charAt(i);
char nextChar2 = (i + 1) < str.length() ? str.charAt(i + 1) : ' ';
char nextChar3 = (i + 2) < str.length() ? str.charAt(i + 2) : ' ';
char nextChar4 = (i + 3) < str.length() ? str.charAt(i + 3) : ' ';
char nextChar5 = (i + 4) < str.length() ? str.charAt(i + 4) : ' ';
char nextChar6 = (i + 5) < str.length() ? str.charAt(i + 5) : ' ';
if (inQuote) {
b.append(nextChar);
if (nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
b.append("quot;</span>");
i += 5;
inQuote = false;
}
} else if (inTag) {
if (nextChar == '&' && nextChar2 == 'g' && nextChar3 == 't' && nextChar4 == ';') {
b.append("</span><span class='hlControl'>></span>");
inTag = false;
i += 3;
} else if (nextChar == ' ') {
b.append("</span><span class='hlAttr'>");
b.append(nextChar);
} else if (nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
b.append("<span class='hlQuot'>"");
inQuote = true;
i += 5;
} else {
b.append(nextChar);
}
} else {
if (nextChar == '&' && nextChar2 == 'l' && nextChar3 == 't' && nextChar4 == ';') {
b.append("<span class='hlControl'><</span><span class='hlTagName'>");
inTag = true;
i += 3;
} else {
b.append(nextChar);
}
}
}
}
return b.toString();
}
private String formatUrl(String theUrlBase, String theResultBody) {
String str = theResultBody;
if (str == null) {
return str;
}
try {
str = URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
ourLog.error("Should not happen", e);
}
StringBuilder b = new StringBuilder();
b.append("<span class='hlUrlBase'>");
boolean inParams = false;
for (int i = 0; i < str.length(); i++) {
char nextChar = str.charAt(i);
// char nextChar2 = i < str.length()-2 ? str.charAt(i+1):' ';
// char nextChar3 = i < str.length()-2 ? str.charAt(i+2):' ';
if (!inParams) {
if (nextChar == '?') {
inParams = true;
b.append("</span><wbr /><span class='hlControl'>?</span><span class='hlTagName'>");
} else {
if (i == theUrlBase.length()) {
b.append("</span><wbr /><span class='hlText'>");
}
b.append(nextChar);
}
} else {
if (nextChar == '&') {
b.append("</span><wbr /><span class='hlControl'>&</span><span class='hlTagName'>");
} else if (nextChar == '=') {
b.append("</span><span class='hlControl'>=</span><span class='hlAttr'>");
// }else if (nextChar=='%' && Character.isLetterOrDigit(nextChar2)&& Character.isLetterOrDigit(nextChar3)) {
// URLDecoder.decode(s, enc)
} else {
b.append(nextChar);
}
}
}
if (inParams) {
b.append("</span>");
}
return b.toString();
}
protected FhirContext getContext(HomeRequest theRequest) {
FhirVersionEnum version = theRequest.getFhirVersion(myConfig);
FhirContext retVal = myContexts.get(version);
if (retVal == null) {
retVal = newContext(version);
myContexts.put(version, retVal);
}
return retVal;
}
protected RuntimeResourceDefinition getResourceType(HomeRequest theRequest, HttpServletRequest theReq) throws ServletException {
String resourceName = StringUtils.defaultString(theReq.getParameter(PARAM_RESOURCE));
RuntimeResourceDefinition def = getContext(theRequest).getResourceDefinition(resourceName);
if (def == null) {
throw new ServletException("Invalid resourceName: " + resourceName);
}
return def;
}
protected ResultType handleClientException(GenericClient theClient, Exception e, ModelMap theModel) {
ResultType returnsResource;
returnsResource = ResultType.NONE;
ourLog.warn("Failed to invoke server", e);
if (e != null) {
theModel.put("errorMsg", toDisplayError("Error: " + e.getMessage(), e));
}
return returnsResource;
}
private IBaseResource loadAndAddConf(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
switch (theRequest.getFhirVersion(myConfig)) {
case DSTU1:
return loadAndAddConfDstu1(theServletRequest, theRequest, theModel);
case DSTU2:
return loadAndAddConfDstu2(theServletRequest, theRequest, theModel);
case DSTU3:
return loadAndAddConfDstu3(theServletRequest, theRequest, theModel);
case DSTU2_1:
case DSTU2_HL7ORG:
break;
}
throw new IllegalStateException("Unknown version: " + theRequest.getFhirVersion(myConfig));
}
private Conformance loadAndAddConfDstu1(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
CaptureInterceptor interceptor = new CaptureInterceptor();
GenericClient client = theRequest.newClient(theServletRequest, getContext(theRequest), myConfig, interceptor);
Conformance conformance;
try {
conformance = (Conformance) client.conformance();
} catch (Exception e) {
ourLog.warn("Failed to load conformance statement, error was: {}", e.toString());
theModel.put("errorMsg", toDisplayError("Failed to load conformance statement, error was: " + e.toString(), e));
conformance = new Conformance();
}
theModel.put("jsonEncodedConf", getContext(theRequest).newJsonParser().encodeResourceToString(conformance));
Map<String, Number> resourceCounts = new HashMap<String, Number>();
long total = 0;
for (Rest nextRest : conformance.getRest()) {
for (ca.uhn.fhir.model.dstu.resource.Conformance.RestResource nextResource : nextRest.getResource()) {
List<ExtensionDt> exts = nextResource.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (exts != null && exts.size() > 0) {
Number nextCount = ((DecimalDt) (exts.get(0).getValue())).getValueAsNumber();
resourceCounts.put(nextResource.getType().getValue(), nextCount);
total += nextCount.longValue();
}
}
}
theModel.put("resourceCounts", resourceCounts);
if (total > 0) {
for (Rest nextRest : conformance.getRest()) {
Collections.sort(nextRest.getResource(), new Comparator<ca.uhn.fhir.model.dstu.resource.Conformance.RestResource>() {
@Override
public int compare(ca.uhn.fhir.model.dstu.resource.Conformance.RestResource theO1, ca.uhn.fhir.model.dstu.resource.Conformance.RestResource theO2) {
DecimalDt count1 = new DecimalDt();
List<ExtensionDt> count1exts = theO1.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count1exts != null && count1exts.size() > 0) {
count1 = (DecimalDt) count1exts.get(0).getValue();
}
DecimalDt count2 = new DecimalDt();
List<ExtensionDt> count2exts = theO2.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count2exts != null && count2exts.size() > 0) {
count2 = (DecimalDt) count2exts.get(0).getValue();
}
int retVal = count2.compareTo(count1);
if (retVal == 0) {
retVal = theO1.getType().getValue().compareTo(theO2.getType().getValue());
}
return retVal;
}
});
}
}
theModel.put("conf", conformance);
theModel.put("requiredParamExtension", ExtensionConstants.PARAM_IS_REQUIRED);
return conformance;
}
private IResource loadAndAddConfDstu2(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
CaptureInterceptor interceptor = new CaptureInterceptor();
GenericClient client = theRequest.newClient(theServletRequest, getContext(theRequest), myConfig, interceptor);
ca.uhn.fhir.model.dstu2.resource.Conformance conformance;
try {
conformance = (ca.uhn.fhir.model.dstu2.resource.Conformance) client.conformance();
} catch (Exception e) {
ourLog.warn("Failed to load conformance statement, error was: {}", e.toString());
theModel.put("errorMsg", toDisplayError("Failed to load conformance statement, error was: " + e.toString(), e));
conformance = new ca.uhn.fhir.model.dstu2.resource.Conformance();
}
theModel.put("jsonEncodedConf", getContext(theRequest).newJsonParser().encodeResourceToString(conformance));
Map<String, Number> resourceCounts = new HashMap<String, Number>();
long total = 0;
for (ca.uhn.fhir.model.dstu2.resource.Conformance.Rest nextRest : conformance.getRest()) {
for (ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource nextResource : nextRest.getResource()) {
List<ExtensionDt> exts = nextResource.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (exts != null && exts.size() > 0) {
Number nextCount = ((DecimalDt) (exts.get(0).getValue())).getValueAsNumber();
resourceCounts.put(nextResource.getTypeElement().getValue(), nextCount);
total += nextCount.longValue();
}
}
}
theModel.put("resourceCounts", resourceCounts);
if (total > 0) {
for (ca.uhn.fhir.model.dstu2.resource.Conformance.Rest nextRest : conformance.getRest()) {
Collections.sort(nextRest.getResource(), new Comparator<ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource>() {
@Override
public int compare(ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource theO1, ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource theO2) {
DecimalDt count1 = new DecimalDt();
List<ExtensionDt> count1exts = theO1.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count1exts != null && count1exts.size() > 0) {
count1 = (DecimalDt) count1exts.get(0).getValue();
}
DecimalDt count2 = new DecimalDt();
List<ExtensionDt> count2exts = theO2.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count2exts != null && count2exts.size() > 0) {
count2 = (DecimalDt) count2exts.get(0).getValue();
}
int retVal = count2.compareTo(count1);
if (retVal == 0) {
retVal = theO1.getTypeElement().getValue().compareTo(theO2.getTypeElement().getValue());
}
return retVal;
}
});
}
}
theModel.put("conf", conformance);
theModel.put("requiredParamExtension", ExtensionConstants.PARAM_IS_REQUIRED);
return conformance;
}
private IBaseResource loadAndAddConfDstu3(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
CaptureInterceptor interceptor = new CaptureInterceptor();
GenericClient client = theRequest.newClient(theServletRequest, getContext(theRequest), myConfig, interceptor);
org.hl7.fhir.dstu3.model.CapabilityStatement capabilityStatement = new CapabilityStatement();
try {
capabilityStatement = client.fetchConformance().ofType(org.hl7.fhir.dstu3.model.CapabilityStatement.class).execute();
} catch (Exception ex) {
ourLog.warn("Failed to load conformance statement, error was: {}", ex.toString());
theModel.put("errorMsg", toDisplayError("Failed to load conformance statement, error was: " + ex.toString(), ex));
}
theModel.put("jsonEncodedConf", getContext(theRequest).newJsonParser().encodeResourceToString(capabilityStatement));
Map<String, Number> resourceCounts = new HashMap<String, Number>();
long total = 0;
for (CapabilityStatementRestComponent nextRest : capabilityStatement.getRest()) {
for (CapabilityStatementRestResourceComponent nextResource : nextRest.getResource()) {
List<Extension> exts = nextResource.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (exts != null && exts.size() > 0) {
Number nextCount = ((DecimalType) (exts.get(0).getValue())).getValueAsNumber();
resourceCounts.put(nextResource.getTypeElement().getValue(), nextCount);
total += nextCount.longValue();
}
}
}
theModel.put("resourceCounts", resourceCounts);
if (total > 0) {
for (CapabilityStatementRestComponent nextRest : capabilityStatement.getRest()) {
Collections.sort(nextRest.getResource(), new Comparator<CapabilityStatementRestResourceComponent>() {
@Override
public int compare(CapabilityStatementRestResourceComponent theO1, CapabilityStatementRestResourceComponent theO2) {
DecimalType count1 = new DecimalType();
List<Extension> count1exts = theO1.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count1exts != null && count1exts.size() > 0) {
count1 = (DecimalType) count1exts.get(0).getValue();
}
DecimalType count2 = new DecimalType();
List<Extension> count2exts = theO2.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count2exts != null && count2exts.size() > 0) {
count2 = (DecimalType) count2exts.get(0).getValue();
}
int retVal = count2.compareTo(count1);
if (retVal == 0) {
retVal = theO1.getTypeElement().getValue().compareTo(theO2.getTypeElement().getValue());
}
return retVal;
}
});
}
}
theModel.put("requiredParamExtension", ExtensionConstants.PARAM_IS_REQUIRED);
theModel.put("conf", capabilityStatement);
return capabilityStatement;
}
protected String logPrefix(ModelMap theModel) {
return "[server=" + theModel.get("serverId") + "] - ";
}
protected FhirContext newContext(FhirVersionEnum version) {
FhirContext retVal;
retVal = new FhirContext(version);
return retVal;
}
private String parseNarrative(HomeRequest theRequest, EncodingEnum theCtEnum, String theResultBody) {
try {
IBaseResource par = theCtEnum.newParser(getContext(theRequest)).parseResource(theResultBody);
String retVal;
if (par instanceof IResource) {
IResource resource = (IResource) par;
retVal = resource.getText().getDiv().getValueAsString();
} else if (par instanceof IDomainResource) {
retVal = ((IDomainResource) par).getText().getDivAsString();
} else {
retVal = null;
}
return StringUtils.defaultString(retVal);
} catch (Exception e) {
ourLog.error("Failed to parse resource", e);
return "";
}
}
protected String preProcessMessageBody(String theBody) {
if (theBody == null) {
return "";
}
String retVal = theBody.trim();
StringBuilder b = new StringBuilder();
for (int i = 0; i < retVal.length(); i++) {
char nextChar = retVal.charAt(i);
int nextCharI = nextChar;
if (nextCharI == 65533) {
b.append(' ');
continue;
}
if (nextCharI == 160) {
b.append(' ');
continue;
}
if (nextCharI == 194) {
b.append(' ');
continue;
}
b.append(nextChar);
}
retVal = b.toString();
return retVal;
}
protected void processAndAddLastClientInvocation(GenericClient theClient, ResultType theResultType, ModelMap theModelMap, long theLatency, String outcomeDescription,
CaptureInterceptor theInterceptor, HomeRequest theRequest) {
try {
// ApacheHttpRequest lastRequest = theInterceptor.getLastRequest();
// HttpResponse lastResponse = theInterceptor.getLastResponse();
// String requestBody = null;
// String requestUrl = lastRequest != null ? lastRequest.getApacheRequest().getURI().toASCIIString() : null;
// String action = lastRequest != null ? lastRequest.getApacheRequest().getMethod() : null;
// String resultStatus = lastResponse != null ? lastResponse.getStatusLine().toString() : null;
// String resultBody = StringUtils.defaultString(theInterceptor.getLastResponseBody());
//
// if (lastRequest instanceof HttpEntityEnclosingRequest) {
// HttpEntity entity = ((HttpEntityEnclosingRequest) lastRequest).getEntity();
// if (entity.isRepeatable()) {
// requestBody = IOUtils.toString(entity.getContent());
// }
// }
//
// ContentType ct = lastResponse != null ? ContentType.get(lastResponse.getEntity()) : null;
// String mimeType = ct != null ? ct.getMimeType() : null;
IHttpRequest lastRequest = theInterceptor.getLastRequest();
IHttpResponse lastResponse = theInterceptor.getLastResponse();
String requestBody = null;
String requestUrl = null;
String action = null;
String resultStatus = null;
String resultBody = null;
String mimeType = null;
ContentType ct = null;
if (lastRequest != null) {
requestBody = lastRequest.getRequestBodyFromStream();
requestUrl = lastRequest.getUri();
action = lastRequest.getHttpVerbName();
}
if (lastResponse != null) {
resultStatus = "HTTP " + lastResponse.getStatus() + " " + lastResponse.getStatusInfo();
lastResponse.bufferEntity();
resultBody = IOUtils.toString(lastResponse.readEntity(), Constants.CHARSET_UTF8);
List<String> ctStrings = lastResponse.getHeaders(Constants.HEADER_CONTENT_TYPE);
if (ctStrings != null && ctStrings.isEmpty() == false) {
ct = ContentType.parse(ctStrings.get(0));
mimeType = ct.getMimeType();
}
}
EncodingEnum ctEnum = EncodingEnum.forContentType(mimeType);
String narrativeString = "";
StringBuilder resultDescription = new StringBuilder();
Bundle bundle = null;
IBaseResource riBundle = null;
FhirContext context = getContext(theRequest);
if (ctEnum == null) {
resultDescription.append("Non-FHIR response");
} else {
switch (ctEnum) {
case JSON:
if (theResultType == ResultType.RESOURCE) {
narrativeString = parseNarrative(theRequest, ctEnum, resultBody);
resultDescription.append("JSON resource");
} else if (theResultType == ResultType.BUNDLE) {
resultDescription.append("JSON bundle");
if (context.getVersion().getVersion().isRi()) {
riBundle = context.newJsonParser().parseResource(resultBody);
} else {
bundle = context.newJsonParser().parseBundle(resultBody);
}
}
break;
case XML:
default:
if (theResultType == ResultType.RESOURCE) {
narrativeString = parseNarrative(theRequest, ctEnum, resultBody);
resultDescription.append("XML resource");
} else if (theResultType == ResultType.BUNDLE) {
resultDescription.append("XML bundle");
if (context.getVersion().getVersion().isRi()) {
riBundle = context.newXmlParser().parseResource(resultBody);
} else {
bundle = context.newXmlParser().parseBundle(resultBody);
}
}
break;
}
}
resultDescription.append(" (").append(resultBody.length() + " bytes)");
Header[] requestHeaders = lastRequest != null ? applyHeaderFilters(lastRequest.getAllHeaders()) : new Header[0];
Header[] responseHeaders = lastResponse != null ? applyHeaderFilters(lastResponse.getAllHeaders()) : new Header[0];
theModelMap.put("outcomeDescription", outcomeDescription);
theModelMap.put("resultDescription", resultDescription.toString());
theModelMap.put("action", action);
theModelMap.put("bundle", bundle);
theModelMap.put("riBundle", riBundle);
theModelMap.put("resultStatus", resultStatus);
theModelMap.put("requestUrl", requestUrl);
theModelMap.put("requestUrlText", formatUrl(theClient.getUrlBase(), requestUrl));
String requestBodyText = format(requestBody, ctEnum);
theModelMap.put("requestBody", requestBodyText);
String resultBodyText = format(resultBody, ctEnum);
theModelMap.put("resultBody", resultBodyText);
theModelMap.put("resultBodyIsLong", resultBodyText.length() > 1000);
theModelMap.put("requestHeaders", requestHeaders);
theModelMap.put("responseHeaders", responseHeaders);
theModelMap.put("narrative", narrativeString);
theModelMap.put("latencyMs", theLatency);
} catch (Exception e) {
ourLog.error("Failure during processing", e);
theModelMap.put("errorMsg", toDisplayError("Error during processing: " + e.getMessage(), e));
}
}
public static class CaptureInterceptor implements IClientInterceptor {
private IHttpRequest myLastRequest;
private IHttpResponse myLastResponse;
// private String myResponseBody;
public IHttpRequest getLastRequest() {
return myLastRequest;
}
public IHttpResponse getLastResponse() {
return myLastResponse;
}
// public String getLastResponseBody() {
// return myResponseBody;
// }
@Override
public void interceptRequest(IHttpRequest theRequest) {
assert myLastRequest == null;
myLastRequest = theRequest;
}
@Override
public void interceptResponse(IHttpResponse theResponse) throws IOException {
assert myLastResponse == null;
myLastResponse = theResponse;
// myLastResponse = ((ApacheHttpResponse) theResponse).getResponse();
//
// HttpEntity respEntity = myLastResponse.getEntity();
// if (respEntity != null) {
// final byte[] bytes;
// try {
// bytes = IOUtils.toByteArray(respEntity.getContent());
// } catch (IllegalStateException e) {
// throw new InternalErrorException(e);
// }
//
// myResponseBody = new String(bytes, "UTF-8");
// myLastResponse.setEntity(new MyEntityWrapper(respEntity, bytes));
// }
}
// private static class MyEntityWrapper extends HttpEntityWrapper {
//
// private byte[] myBytes;
//
// public MyEntityWrapper(HttpEntity theWrappedEntity, byte[] theBytes) {
// super(theWrappedEntity);
// myBytes = theBytes;
// }
//
// @Override
// public InputStream getContent() throws IOException {
// return new ByteArrayInputStream(myBytes);
// }
//
// @Override
// public void writeTo(OutputStream theOutstream) throws IOException {
// theOutstream.write(myBytes);
// }
//
// }
}
protected enum ResultType {
BUNDLE, NONE, RESOURCE, TAGLIST
}
/**
* A hook to be overridden by subclasses. The overriding method can modify the error message
* based on its content and/or the related exception.
*
* @param theErrorMsg The original error message to be displayed to the user.
* @param theException The exception that occurred. May be null.
* @return The modified error message to be displayed to the user.
*/
protected String toDisplayError(String theErrorMsg, Exception theException) {
return theErrorMsg;
}
}
|
hapi-fhir-testpage-overlay/src/main/java/ca/uhn/fhir/to/BaseController.java
|
package ca.uhn.fhir.to;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.FhirVersionEnum;
import ca.uhn.fhir.context.RuntimeResourceDefinition;
import ca.uhn.fhir.model.api.Bundle;
import ca.uhn.fhir.model.api.ExtensionDt;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.dstu.resource.Conformance;
import ca.uhn.fhir.model.dstu.resource.Conformance.Rest;
import ca.uhn.fhir.model.primitive.DecimalDt;
import ca.uhn.fhir.rest.client.GenericClient;
import ca.uhn.fhir.rest.client.IClientInterceptor;
import ca.uhn.fhir.rest.client.api.IHttpRequest;
import ca.uhn.fhir.rest.client.api.IHttpResponse;
import ca.uhn.fhir.rest.server.Constants;
import ca.uhn.fhir.rest.server.EncodingEnum;
import ca.uhn.fhir.to.model.HomeRequest;
import ca.uhn.fhir.util.ExtensionConstants;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicHeader;
import org.hl7.fhir.dstu3.model.CapabilityStatement;
import org.hl7.fhir.dstu3.model.CapabilityStatement.CapabilityStatementRestComponent;
import org.hl7.fhir.dstu3.model.CapabilityStatement.CapabilityStatementRestResourceComponent;
import org.hl7.fhir.dstu3.model.DecimalType;
import org.hl7.fhir.dstu3.model.Extension;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IDomainResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.thymeleaf.TemplateEngine;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import static org.apache.commons.lang3.StringUtils.defaultString;
public class BaseController {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BaseController.class);
static final String PARAM_RESOURCE = "resource";
static final String RESOURCE_COUNT_EXT_URL = "http://hl7api.sourceforge.net/hapi-fhir/res/extdefs.html#resourceCount";
@Autowired
protected TesterConfig myConfig;
private Map<FhirVersionEnum, FhirContext> myContexts = new HashMap<FhirVersionEnum, FhirContext>();
private List<String> myFilterHeaders;
@Autowired
private TemplateEngine myTemplateEngine;
public BaseController() {
super();
}
protected IBaseResource addCommonParams(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
if (myConfig.getDebugTemplatesMode()) {
myTemplateEngine.getCacheManager().clearAllCaches();
}
final String serverId = theRequest.getServerIdWithDefault(myConfig);
final String serverBase = theRequest.getServerBase(theServletRequest, myConfig);
final String serverName = theRequest.getServerName(myConfig);
final String apiKey = theRequest.getApiKey(theServletRequest, myConfig);
theModel.put("serverId", serverId);
theModel.put("base", serverBase);
theModel.put("baseName", serverName);
theModel.put("apiKey", apiKey);
theModel.put("resourceName", defaultString(theRequest.getResource()));
theModel.put("encoding", theRequest.getEncoding());
theModel.put("pretty", theRequest.getPretty());
theModel.put("_summary", theRequest.get_summary());
theModel.put("serverEntries", myConfig.getIdToServerName());
return loadAndAddConf(theServletRequest, theRequest, theModel);
}
private Header[] applyHeaderFilters(Header[] theAllHeaders) {
if (myFilterHeaders == null || myFilterHeaders.isEmpty()) {
return theAllHeaders;
}
ArrayList<Header> retVal = new ArrayList<Header>();
for (Header next : theAllHeaders) {
if (!myFilterHeaders.contains(next.getName().toLowerCase())) {
retVal.add(next);
}
}
return retVal.toArray(new Header[retVal.size()]);
}
private Header[] applyHeaderFilters(Map<String, List<String>> theAllHeaders) {
ArrayList<Header> retVal = new ArrayList<Header>();
for (String nextKey : theAllHeaders.keySet()) {
for (String nextValue : theAllHeaders.get(nextKey)) {
if (myFilterHeaders == null || !myFilterHeaders.contains(nextKey.toLowerCase())) {
retVal.add(new BasicHeader(nextKey, nextValue));
}
}
}
return retVal.toArray(new Header[retVal.size()]);
}
private String format(String theResultBody, EncodingEnum theEncodingEnum) {
String str = StringEscapeUtils.escapeHtml4(theResultBody);
if (str == null || theEncodingEnum == null) {
return str;
}
StringBuilder b = new StringBuilder();
if (theEncodingEnum == EncodingEnum.JSON) {
boolean inValue = false;
boolean inQuote = false;
for (int i = 0; i < str.length(); i++) {
char prevChar = (i > 0) ? str.charAt(i - 1) : ' ';
char nextChar = str.charAt(i);
char nextChar2 = (i + 1) < str.length() ? str.charAt(i + 1) : ' ';
char nextChar3 = (i + 2) < str.length() ? str.charAt(i + 2) : ' ';
char nextChar4 = (i + 3) < str.length() ? str.charAt(i + 3) : ' ';
char nextChar5 = (i + 4) < str.length() ? str.charAt(i + 4) : ' ';
char nextChar6 = (i + 5) < str.length() ? str.charAt(i + 5) : ' ';
if (inQuote) {
b.append(nextChar);
if (prevChar != '\\' && nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
b.append("quot;</span>");
i += 5;
inQuote = false;
} else if (nextChar == '\\' && nextChar2 == '"') {
b.append("quot;</span>");
i += 5;
inQuote = false;
}
} else {
if (nextChar == ':') {
inValue = true;
b.append(nextChar);
} else if (nextChar == '[' || nextChar == '{') {
b.append("<span class='hlControl'>");
b.append(nextChar);
b.append("</span>");
inValue = false;
} else if (nextChar == '{' || nextChar == '}' || nextChar == ',') {
b.append("<span class='hlControl'>");
b.append(nextChar);
b.append("</span>");
inValue = false;
} else if (nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
if (inValue) {
b.append("<span class='hlQuot'>"");
} else {
b.append("<span class='hlTagName'>"");
}
inQuote = true;
i += 5;
} else if (nextChar == ':') {
b.append("<span class='hlControl'>");
b.append(nextChar);
b.append("</span>");
inValue = true;
} else {
b.append(nextChar);
}
}
}
} else {
boolean inQuote = false;
boolean inTag = false;
for (int i = 0; i < str.length(); i++) {
char nextChar = str.charAt(i);
char nextChar2 = (i + 1) < str.length() ? str.charAt(i + 1) : ' ';
char nextChar3 = (i + 2) < str.length() ? str.charAt(i + 2) : ' ';
char nextChar4 = (i + 3) < str.length() ? str.charAt(i + 3) : ' ';
char nextChar5 = (i + 4) < str.length() ? str.charAt(i + 4) : ' ';
char nextChar6 = (i + 5) < str.length() ? str.charAt(i + 5) : ' ';
if (inQuote) {
b.append(nextChar);
if (nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
b.append("quot;</span>");
i += 5;
inQuote = false;
}
} else if (inTag) {
if (nextChar == '&' && nextChar2 == 'g' && nextChar3 == 't' && nextChar4 == ';') {
b.append("</span><span class='hlControl'>></span>");
inTag = false;
i += 3;
} else if (nextChar == ' ') {
b.append("</span><span class='hlAttr'>");
b.append(nextChar);
} else if (nextChar == '&' && nextChar2 == 'q' && nextChar3 == 'u' && nextChar4 == 'o' && nextChar5 == 't' && nextChar6 == ';') {
b.append("<span class='hlQuot'>"");
inQuote = true;
i += 5;
} else {
b.append(nextChar);
}
} else {
if (nextChar == '&' && nextChar2 == 'l' && nextChar3 == 't' && nextChar4 == ';') {
b.append("<span class='hlControl'><</span><span class='hlTagName'>");
inTag = true;
i += 3;
} else {
b.append(nextChar);
}
}
}
}
return b.toString();
}
private String formatUrl(String theUrlBase, String theResultBody) {
String str = theResultBody;
if (str == null) {
return str;
}
try {
str = URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
ourLog.error("Should not happen", e);
}
StringBuilder b = new StringBuilder();
b.append("<span class='hlUrlBase'>");
boolean inParams = false;
for (int i = 0; i < str.length(); i++) {
char nextChar = str.charAt(i);
// char nextChar2 = i < str.length()-2 ? str.charAt(i+1):' ';
// char nextChar3 = i < str.length()-2 ? str.charAt(i+2):' ';
if (!inParams) {
if (nextChar == '?') {
inParams = true;
b.append("</span><wbr /><span class='hlControl'>?</span><span class='hlTagName'>");
} else {
if (i == theUrlBase.length()) {
b.append("</span><wbr /><span class='hlText'>");
}
b.append(nextChar);
}
} else {
if (nextChar == '&') {
b.append("</span><wbr /><span class='hlControl'>&</span><span class='hlTagName'>");
} else if (nextChar == '=') {
b.append("</span><span class='hlControl'>=</span><span class='hlAttr'>");
// }else if (nextChar=='%' && Character.isLetterOrDigit(nextChar2)&& Character.isLetterOrDigit(nextChar3)) {
// URLDecoder.decode(s, enc)
} else {
b.append(nextChar);
}
}
}
if (inParams) {
b.append("</span>");
}
return b.toString();
}
protected FhirContext getContext(HomeRequest theRequest) {
FhirVersionEnum version = theRequest.getFhirVersion(myConfig);
FhirContext retVal = myContexts.get(version);
if (retVal == null) {
retVal = newContext(version);
myContexts.put(version, retVal);
}
return retVal;
}
protected RuntimeResourceDefinition getResourceType(HomeRequest theRequest, HttpServletRequest theReq) throws ServletException {
String resourceName = StringUtils.defaultString(theReq.getParameter(PARAM_RESOURCE));
RuntimeResourceDefinition def = getContext(theRequest).getResourceDefinition(resourceName);
if (def == null) {
throw new ServletException("Invalid resourceName: " + resourceName);
}
return def;
}
protected ResultType handleClientException(GenericClient theClient, Exception e, ModelMap theModel) {
ResultType returnsResource;
returnsResource = ResultType.NONE;
ourLog.warn("Failed to invoke server", e);
if (e != null) {
theModel.put("errorMsg", toDisplayError("Error: " + e.getMessage(), e));
}
return returnsResource;
}
private IBaseResource loadAndAddConf(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
switch (theRequest.getFhirVersion(myConfig)) {
case DSTU1:
return loadAndAddConfDstu1(theServletRequest, theRequest, theModel);
case DSTU2:
return loadAndAddConfDstu2(theServletRequest, theRequest, theModel);
case DSTU3:
return loadAndAddConfDstu3(theServletRequest, theRequest, theModel);
case DSTU2_1:
case DSTU2_HL7ORG:
break;
}
throw new IllegalStateException("Unknown version: " + theRequest.getFhirVersion(myConfig));
}
private Conformance loadAndAddConfDstu1(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
CaptureInterceptor interceptor = new CaptureInterceptor();
GenericClient client = theRequest.newClient(theServletRequest, getContext(theRequest), myConfig, interceptor);
Conformance conformance;
try {
conformance = (Conformance) client.conformance();
} catch (Exception e) {
ourLog.warn("Failed to load conformance statement", e);
theModel.put("errorMsg", toDisplayError("Failed to load conformance statement, error was: " + e.toString(), e));
conformance = new Conformance();
}
theModel.put("jsonEncodedConf", getContext(theRequest).newJsonParser().encodeResourceToString(conformance));
Map<String, Number> resourceCounts = new HashMap<String, Number>();
long total = 0;
for (Rest nextRest : conformance.getRest()) {
for (ca.uhn.fhir.model.dstu.resource.Conformance.RestResource nextResource : nextRest.getResource()) {
List<ExtensionDt> exts = nextResource.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (exts != null && exts.size() > 0) {
Number nextCount = ((DecimalDt) (exts.get(0).getValue())).getValueAsNumber();
resourceCounts.put(nextResource.getType().getValue(), nextCount);
total += nextCount.longValue();
}
}
}
theModel.put("resourceCounts", resourceCounts);
if (total > 0) {
for (Rest nextRest : conformance.getRest()) {
Collections.sort(nextRest.getResource(), new Comparator<ca.uhn.fhir.model.dstu.resource.Conformance.RestResource>() {
@Override
public int compare(ca.uhn.fhir.model.dstu.resource.Conformance.RestResource theO1, ca.uhn.fhir.model.dstu.resource.Conformance.RestResource theO2) {
DecimalDt count1 = new DecimalDt();
List<ExtensionDt> count1exts = theO1.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count1exts != null && count1exts.size() > 0) {
count1 = (DecimalDt) count1exts.get(0).getValue();
}
DecimalDt count2 = new DecimalDt();
List<ExtensionDt> count2exts = theO2.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count2exts != null && count2exts.size() > 0) {
count2 = (DecimalDt) count2exts.get(0).getValue();
}
int retVal = count2.compareTo(count1);
if (retVal == 0) {
retVal = theO1.getType().getValue().compareTo(theO2.getType().getValue());
}
return retVal;
}
});
}
}
theModel.put("conf", conformance);
theModel.put("requiredParamExtension", ExtensionConstants.PARAM_IS_REQUIRED);
return conformance;
}
private IResource loadAndAddConfDstu2(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
CaptureInterceptor interceptor = new CaptureInterceptor();
GenericClient client = theRequest.newClient(theServletRequest, getContext(theRequest), myConfig, interceptor);
ca.uhn.fhir.model.dstu2.resource.Conformance conformance;
try {
conformance = (ca.uhn.fhir.model.dstu2.resource.Conformance) client.conformance();
} catch (Exception e) {
ourLog.warn("Failed to load conformance statement", e);
theModel.put("errorMsg", toDisplayError("Failed to load conformance statement, error was: " + e.toString(), e));
conformance = new ca.uhn.fhir.model.dstu2.resource.Conformance();
}
theModel.put("jsonEncodedConf", getContext(theRequest).newJsonParser().encodeResourceToString(conformance));
Map<String, Number> resourceCounts = new HashMap<String, Number>();
long total = 0;
for (ca.uhn.fhir.model.dstu2.resource.Conformance.Rest nextRest : conformance.getRest()) {
for (ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource nextResource : nextRest.getResource()) {
List<ExtensionDt> exts = nextResource.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (exts != null && exts.size() > 0) {
Number nextCount = ((DecimalDt) (exts.get(0).getValue())).getValueAsNumber();
resourceCounts.put(nextResource.getTypeElement().getValue(), nextCount);
total += nextCount.longValue();
}
}
}
theModel.put("resourceCounts", resourceCounts);
if (total > 0) {
for (ca.uhn.fhir.model.dstu2.resource.Conformance.Rest nextRest : conformance.getRest()) {
Collections.sort(nextRest.getResource(), new Comparator<ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource>() {
@Override
public int compare(ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource theO1, ca.uhn.fhir.model.dstu2.resource.Conformance.RestResource theO2) {
DecimalDt count1 = new DecimalDt();
List<ExtensionDt> count1exts = theO1.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count1exts != null && count1exts.size() > 0) {
count1 = (DecimalDt) count1exts.get(0).getValue();
}
DecimalDt count2 = new DecimalDt();
List<ExtensionDt> count2exts = theO2.getUndeclaredExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count2exts != null && count2exts.size() > 0) {
count2 = (DecimalDt) count2exts.get(0).getValue();
}
int retVal = count2.compareTo(count1);
if (retVal == 0) {
retVal = theO1.getTypeElement().getValue().compareTo(theO2.getTypeElement().getValue());
}
return retVal;
}
});
}
}
theModel.put("conf", conformance);
theModel.put("requiredParamExtension", ExtensionConstants.PARAM_IS_REQUIRED);
return conformance;
}
private IBaseResource loadAndAddConfDstu3(HttpServletRequest theServletRequest, final HomeRequest theRequest, final ModelMap theModel) {
CaptureInterceptor interceptor = new CaptureInterceptor();
GenericClient client = theRequest.newClient(theServletRequest, getContext(theRequest), myConfig, interceptor);
org.hl7.fhir.dstu3.model.CapabilityStatement capabilityStatement = new CapabilityStatement();
try {
capabilityStatement = client.fetchConformance().ofType(org.hl7.fhir.dstu3.model.CapabilityStatement.class).execute();
} catch (Exception ex) {
ourLog.warn("Failed to load conformance statement", ex);
theModel.put("errorMsg", toDisplayError("Failed to load conformance statement, error was: " + ex.toString(), ex));
}
theModel.put("jsonEncodedConf", getContext(theRequest).newJsonParser().encodeResourceToString(capabilityStatement));
Map<String, Number> resourceCounts = new HashMap<String, Number>();
long total = 0;
for (CapabilityStatementRestComponent nextRest : capabilityStatement.getRest()) {
for (CapabilityStatementRestResourceComponent nextResource : nextRest.getResource()) {
List<Extension> exts = nextResource.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (exts != null && exts.size() > 0) {
Number nextCount = ((DecimalType) (exts.get(0).getValue())).getValueAsNumber();
resourceCounts.put(nextResource.getTypeElement().getValue(), nextCount);
total += nextCount.longValue();
}
}
}
theModel.put("resourceCounts", resourceCounts);
if (total > 0) {
for (CapabilityStatementRestComponent nextRest : capabilityStatement.getRest()) {
Collections.sort(nextRest.getResource(), new Comparator<CapabilityStatementRestResourceComponent>() {
@Override
public int compare(CapabilityStatementRestResourceComponent theO1, CapabilityStatementRestResourceComponent theO2) {
DecimalType count1 = new DecimalType();
List<Extension> count1exts = theO1.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count1exts != null && count1exts.size() > 0) {
count1 = (DecimalType) count1exts.get(0).getValue();
}
DecimalType count2 = new DecimalType();
List<Extension> count2exts = theO2.getExtensionsByUrl(RESOURCE_COUNT_EXT_URL);
if (count2exts != null && count2exts.size() > 0) {
count2 = (DecimalType) count2exts.get(0).getValue();
}
int retVal = count2.compareTo(count1);
if (retVal == 0) {
retVal = theO1.getTypeElement().getValue().compareTo(theO2.getTypeElement().getValue());
}
return retVal;
}
});
}
}
theModel.put("requiredParamExtension", ExtensionConstants.PARAM_IS_REQUIRED);
theModel.put("conf", capabilityStatement);
return capabilityStatement;
}
protected String logPrefix(ModelMap theModel) {
return "[server=" + theModel.get("serverId") + "] - ";
}
protected FhirContext newContext(FhirVersionEnum version) {
FhirContext retVal;
retVal = new FhirContext(version);
return retVal;
}
private String parseNarrative(HomeRequest theRequest, EncodingEnum theCtEnum, String theResultBody) {
try {
IBaseResource par = theCtEnum.newParser(getContext(theRequest)).parseResource(theResultBody);
String retVal;
if (par instanceof IResource) {
IResource resource = (IResource) par;
retVal = resource.getText().getDiv().getValueAsString();
} else if (par instanceof IDomainResource) {
retVal = ((IDomainResource) par).getText().getDivAsString();
} else {
retVal = null;
}
return StringUtils.defaultString(retVal);
} catch (Exception e) {
ourLog.error("Failed to parse resource", e);
return "";
}
}
protected String preProcessMessageBody(String theBody) {
if (theBody == null) {
return "";
}
String retVal = theBody.trim();
StringBuilder b = new StringBuilder();
for (int i = 0; i < retVal.length(); i++) {
char nextChar = retVal.charAt(i);
int nextCharI = nextChar;
if (nextCharI == 65533) {
b.append(' ');
continue;
}
if (nextCharI == 160) {
b.append(' ');
continue;
}
if (nextCharI == 194) {
b.append(' ');
continue;
}
b.append(nextChar);
}
retVal = b.toString();
return retVal;
}
protected void processAndAddLastClientInvocation(GenericClient theClient, ResultType theResultType, ModelMap theModelMap, long theLatency, String outcomeDescription,
CaptureInterceptor theInterceptor, HomeRequest theRequest) {
try {
// ApacheHttpRequest lastRequest = theInterceptor.getLastRequest();
// HttpResponse lastResponse = theInterceptor.getLastResponse();
// String requestBody = null;
// String requestUrl = lastRequest != null ? lastRequest.getApacheRequest().getURI().toASCIIString() : null;
// String action = lastRequest != null ? lastRequest.getApacheRequest().getMethod() : null;
// String resultStatus = lastResponse != null ? lastResponse.getStatusLine().toString() : null;
// String resultBody = StringUtils.defaultString(theInterceptor.getLastResponseBody());
//
// if (lastRequest instanceof HttpEntityEnclosingRequest) {
// HttpEntity entity = ((HttpEntityEnclosingRequest) lastRequest).getEntity();
// if (entity.isRepeatable()) {
// requestBody = IOUtils.toString(entity.getContent());
// }
// }
//
// ContentType ct = lastResponse != null ? ContentType.get(lastResponse.getEntity()) : null;
// String mimeType = ct != null ? ct.getMimeType() : null;
IHttpRequest lastRequest = theInterceptor.getLastRequest();
IHttpResponse lastResponse = theInterceptor.getLastResponse();
String requestBody = null;
String requestUrl = null;
String action = null;
String resultStatus = null;
String resultBody = null;
String mimeType = null;
ContentType ct = null;
if (lastRequest != null) {
requestBody = lastRequest.getRequestBodyFromStream();
requestUrl = lastRequest.getUri();
action = lastRequest.getHttpVerbName();
}
if (lastResponse != null) {
resultStatus = "HTTP " + lastResponse.getStatus() + " " + lastResponse.getStatusInfo();
lastResponse.bufferEntity();
resultBody = IOUtils.toString(lastResponse.readEntity(), Constants.CHARSET_UTF8);
List<String> ctStrings = lastResponse.getHeaders(Constants.HEADER_CONTENT_TYPE);
if (ctStrings != null && ctStrings.isEmpty() == false) {
ct = ContentType.parse(ctStrings.get(0));
mimeType = ct.getMimeType();
}
}
EncodingEnum ctEnum = EncodingEnum.forContentType(mimeType);
String narrativeString = "";
StringBuilder resultDescription = new StringBuilder();
Bundle bundle = null;
IBaseResource riBundle = null;
FhirContext context = getContext(theRequest);
if (ctEnum == null) {
resultDescription.append("Non-FHIR response");
} else {
switch (ctEnum) {
case JSON:
if (theResultType == ResultType.RESOURCE) {
narrativeString = parseNarrative(theRequest, ctEnum, resultBody);
resultDescription.append("JSON resource");
} else if (theResultType == ResultType.BUNDLE) {
resultDescription.append("JSON bundle");
if (context.getVersion().getVersion().isRi()) {
riBundle = context.newJsonParser().parseResource(resultBody);
} else {
bundle = context.newJsonParser().parseBundle(resultBody);
}
}
break;
case XML:
default:
if (theResultType == ResultType.RESOURCE) {
narrativeString = parseNarrative(theRequest, ctEnum, resultBody);
resultDescription.append("XML resource");
} else if (theResultType == ResultType.BUNDLE) {
resultDescription.append("XML bundle");
if (context.getVersion().getVersion().isRi()) {
riBundle = context.newXmlParser().parseResource(resultBody);
} else {
bundle = context.newXmlParser().parseBundle(resultBody);
}
}
break;
}
}
resultDescription.append(" (").append(resultBody.length() + " bytes)");
Header[] requestHeaders = lastRequest != null ? applyHeaderFilters(lastRequest.getAllHeaders()) : new Header[0];
Header[] responseHeaders = lastResponse != null ? applyHeaderFilters(lastResponse.getAllHeaders()) : new Header[0];
theModelMap.put("outcomeDescription", outcomeDescription);
theModelMap.put("resultDescription", resultDescription.toString());
theModelMap.put("action", action);
theModelMap.put("bundle", bundle);
theModelMap.put("riBundle", riBundle);
theModelMap.put("resultStatus", resultStatus);
theModelMap.put("requestUrl", requestUrl);
theModelMap.put("requestUrlText", formatUrl(theClient.getUrlBase(), requestUrl));
String requestBodyText = format(requestBody, ctEnum);
theModelMap.put("requestBody", requestBodyText);
String resultBodyText = format(resultBody, ctEnum);
theModelMap.put("resultBody", resultBodyText);
theModelMap.put("resultBodyIsLong", resultBodyText.length() > 1000);
theModelMap.put("requestHeaders", requestHeaders);
theModelMap.put("responseHeaders", responseHeaders);
theModelMap.put("narrative", narrativeString);
theModelMap.put("latencyMs", theLatency);
} catch (Exception e) {
ourLog.error("Failure during processing", e);
theModelMap.put("errorMsg", toDisplayError("Error during processing: " + e.getMessage(), e));
}
}
public static class CaptureInterceptor implements IClientInterceptor {
private IHttpRequest myLastRequest;
private IHttpResponse myLastResponse;
// private String myResponseBody;
public IHttpRequest getLastRequest() {
return myLastRequest;
}
public IHttpResponse getLastResponse() {
return myLastResponse;
}
// public String getLastResponseBody() {
// return myResponseBody;
// }
@Override
public void interceptRequest(IHttpRequest theRequest) {
assert myLastRequest == null;
myLastRequest = theRequest;
}
@Override
public void interceptResponse(IHttpResponse theResponse) throws IOException {
assert myLastResponse == null;
myLastResponse = theResponse;
// myLastResponse = ((ApacheHttpResponse) theResponse).getResponse();
//
// HttpEntity respEntity = myLastResponse.getEntity();
// if (respEntity != null) {
// final byte[] bytes;
// try {
// bytes = IOUtils.toByteArray(respEntity.getContent());
// } catch (IllegalStateException e) {
// throw new InternalErrorException(e);
// }
//
// myResponseBody = new String(bytes, "UTF-8");
// myLastResponse.setEntity(new MyEntityWrapper(respEntity, bytes));
// }
}
// private static class MyEntityWrapper extends HttpEntityWrapper {
//
// private byte[] myBytes;
//
// public MyEntityWrapper(HttpEntity theWrappedEntity, byte[] theBytes) {
// super(theWrappedEntity);
// myBytes = theBytes;
// }
//
// @Override
// public InputStream getContent() throws IOException {
// return new ByteArrayInputStream(myBytes);
// }
//
// @Override
// public void writeTo(OutputStream theOutstream) throws IOException {
// theOutstream.write(myBytes);
// }
//
// }
}
protected enum ResultType {
BUNDLE, NONE, RESOURCE, TAGLIST
}
/**
* A hook to be overridden by subclasses. The overriding method can modify the error message
* based on its content and/or the related exception.
*
* @param theErrorMsg The original error message to be displayed to the user.
* @param theException The exception that occurred. May be null.
* @return The modified error message to be displayed to the user.
*/
protected String toDisplayError(String theErrorMsg, Exception theException) {
return theErrorMsg;
}
}
|
Removed annoying stacktrace from logs for failed conformance statements. (#692)
* Removed annoying stacktrace from logs for failed conformance statements.
* Minor tweak for consistency with slf4j.
|
hapi-fhir-testpage-overlay/src/main/java/ca/uhn/fhir/to/BaseController.java
|
Removed annoying stacktrace from logs for failed conformance statements. (#692)
|
|
Java
|
apache-2.0
|
0280b53e2d626f2aaa15265eb3e7050153a532b0
| 0
|
apache/commons-math,Hipparchus-Math/hipparchus,apache/commons-math,sdinot/hipparchus,sdinot/hipparchus,sdinot/hipparchus,apache/commons-math,Hipparchus-Math/hipparchus,Hipparchus-Math/hipparchus,apache/commons-math,Hipparchus-Math/hipparchus,sdinot/hipparchus
|
/*
* 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.commons.math.transform;
import java.io.Serializable;
import java.lang.reflect.Array;
import org.apache.commons.math.analysis.FunctionUtils;
import org.apache.commons.math.analysis.UnivariateFunction;
import org.apache.commons.math.complex.Complex;
import org.apache.commons.math.complex.RootsOfUnity;
import org.apache.commons.math.exception.DimensionMismatchException;
import org.apache.commons.math.exception.MathIllegalArgumentException;
import org.apache.commons.math.exception.util.LocalizedFormats;
import org.apache.commons.math.util.ArithmeticUtils;
import org.apache.commons.math.util.FastMath;
/**
* <p>
* Implements the Fast Fourier Transform for transformation of one-dimensional
* real or complex data sets. For reference, see <em>Applied Numerical Linear
* Algebra</em>, ISBN 0898713897, chapter 6.
* </p>
* <p>
* There are several variants of the discrete Fourier transform, with various
* normalization conventions, which are described below.
* </p>
* <p>
* The current implementation of the discrete Fourier transform as a fast
* Fourier transform requires the length of the data set to be a power of 2.
* This greatly simplifies and speeds up the code. Users can pad the data with
* zeros to meet this requirement. There are other flavors of FFT, for
* reference, see S. Winograd,
* <i>On computing the discrete Fourier transform</i>, Mathematics of
* Computation, 32 (1978), 175 - 199.
* </p>
* <h3><a id="standard">Standard DFT</a></h3>
* <p>
* The standard normalization convention is defined as follows
* <ul>
* <li>forward transform: y<sub>n</sub> = ∑<sub>k=0</sub><sup>N-1</sup>
* x<sub>k</sub> exp(-2πi n k / N),</li>
* <li>inverse transform: x<sub>k</sub> = N<sup>-1</sup>
* ∑<sub>n=0</sub><sup>N-1</sup> y<sub>n</sub> exp(2πi n k / N),</li>
* </ul>
* where N is the size of the data sample.
* </p>
* <p>
* {@link FastFourierTransformer}s following this convention are returned by the
* factory method {@link #create()}.
* </p>
* <h3><a id="unitary">Unitary DFT</a></h3>
* <p>
* The unitary normalization convention is defined as follows
* <ul>
* <li>forward transform: y<sub>n</sub> = (1 / √N)
* ∑<sub>k=0</sub><sup>N-1</sup> x<sub>k</sub> exp(-2πi n k / N),</li>
* <li>inverse transform: x<sub>k</sub> = (1 / √N)
* ∑<sub>n=0</sub><sup>N-1</sup> y<sub>n</sub> exp(2πi n k / N),</li>
* </ul>
* which makes the transform unitary. N is the size of the data sample.
* </p>
* <p>
* {@link FastFourierTransformer}s following this convention are returned by the
* factory method {@link #createUnitary()}.
* </p>
*
* @version $Id$
* @since 1.2
*/
public class FastFourierTransformer implements Serializable {
/** Serializable version identifier. */
static final long serialVersionUID = 20120501L;
/**
* {@code true} if the unitary version of the DFT should be used.
*
* @see #create()
* @see #createUnitary()
*/
private final boolean unitary;
/** The roots of unity. */
private RootsOfUnity roots = new RootsOfUnity();
/**
* Creates a new instance of this class, with various normalization
* conventions.
*
* @param unitary {@code false} if the DFT is <em>not</em> to be scaled,
* {@code true} if it is to be scaled so as to make the transform unitary.
* @see #create()
* @see #createUnitary()
*/
private FastFourierTransformer(final boolean unitary) {
this.unitary = unitary;
}
/**
* <p>
* Returns a new instance of this class. The returned transformer uses the
* <a href="#standard">standard normalizing conventions</a>.
* </p>
*
* @return a new DFT transformer, with standard normalizing conventions
*/
public static FastFourierTransformer create() {
return new FastFourierTransformer(false);
}
/**
* <p>
* Returns a new instance of this class. The returned transformer uses the
* <a href="#unitary">unitary normalizing conventions</a>.
* </p>
*
* @return a new DFT transformer, with unitary normalizing conventions
*/
public static FastFourierTransformer createUnitary() {
return new FastFourierTransformer(true);
}
/**
* Returns the forward transform of the specified real data set.
*
* @param f the real data array to be transformed
* @return the complex transformed array
* @throws MathIllegalArgumentException if the length of the data array is
* not a power of two
*/
public Complex[] transform(double[] f) {
if (unitary) {
final double s = 1.0 / FastMath.sqrt(f.length);
return TransformUtils.scaleArray(fft(f, false), s);
}
return fft(f, false);
}
/**
* Returns the forward transform of the specified real function, sampled on
* the specified interval.
*
* @param f the function to be sampled and transformed
* @param min the (inclusive) lower bound for the interval
* @param max the (exclusive) upper bound for the interval
* @param n the number of sample points
* @return the complex transformed array
* @throws org.apache.commons.math.exception.NumberIsTooLargeException
* if the lower bound is greater than, or equal to the upper bound
* @throws org.apache.commons.math.exception.NotStrictlyPositiveException
* if the number of sample points {@code n} is negative
* @throws MathIllegalArgumentException if the number of sample points
* {@code n} is not a power of two
*/
public Complex[] transform(UnivariateFunction f,
double min, double max, int n) {
final double[] data = FunctionUtils.sample(f, min, max, n);
if (unitary) {
final double s = 1.0 / FastMath.sqrt(n);
return TransformUtils.scaleArray(fft(data, false), s);
}
return fft(data, false);
}
/**
* Returns the forward transform of the specified complex data set.
*
* @param f the complex data array to be transformed
* @return the complex transformed array
* @throws MathIllegalArgumentException if the length of the data array is
* not a power of two
*/
public Complex[] transform(Complex[] f) {
roots.computeRoots(-f.length);
if (unitary) {
final double s = 1.0 / FastMath.sqrt(f.length);
return TransformUtils.scaleArray(fft(f), s);
}
return fft(f);
}
/**
* Returns the inverse transform of the specified real data set.
*
* @param f the real data array to be inversely transformed
* @return the complex inversely transformed array
* @throws MathIllegalArgumentException if the length of the data array is
* not a power of two
*/
public Complex[] inverseTransform(double[] f) {
final double s = 1.0 / (unitary ? FastMath.sqrt(f.length) : f.length);
return TransformUtils.scaleArray(fft(f, true), s);
}
/**
* Returns the inverse transform of the specified real function, sampled
* on the given interval.
*
* @param f the function to be sampled and inversely transformed
* @param min the (inclusive) lower bound for the interval
* @param max the (exclusive) upper bound for the interval
* @param n the number of sample points
* @return the complex inversely transformed array
* @throws org.apache.commons.math.exception.NumberIsTooLargeException
* if the lower bound is greater than, or equal to the upper bound
* @throws org.apache.commons.math.exception.NotStrictlyPositiveException
* if the number of sample points {@code n} is negative
* @throws MathIllegalArgumentException if the number of sample points
* {@code n} is not a power of two
*/
public Complex[] inverseTransform(UnivariateFunction f,
double min, double max, int n) {
final double[] data = FunctionUtils.sample(f, min, max, n);
final double s = 1.0 / (unitary ? FastMath.sqrt(n) : n);
return TransformUtils.scaleArray(fft(data, true), s);
}
/**
* Returns the inverse transform of the specified complex data set.
*
* @param f the complex data array to be inversely transformed
* @return the complex inversely transformed array
* @throws MathIllegalArgumentException if the length of the data array is
* not a power of two
*/
public Complex[] inverseTransform(Complex[] f) {
roots.computeRoots(f.length);
final double s = 1.0 / (unitary ? FastMath.sqrt(f.length) : f.length);
return TransformUtils.scaleArray(fft(f), s);
}
/**
* Returns the FFT of the specified real data set. Performs the base-4
* Cooley-Tukey FFT algorithm.
*
* @param f the real data array to be transformed
* @param isInverse {@code true} if inverse transform is to be carried out
* @return the complex transformed array
* @throws MathIllegalArgumentException if the length of the data array is
* not a power of two
*/
protected Complex[] fft(double[] f, boolean isInverse) {
if (!ArithmeticUtils.isPowerOfTwo(f.length)) {
throw new MathIllegalArgumentException(
LocalizedFormats.NOT_POWER_OF_TWO_CONSIDER_PADDING,
Integer.valueOf(f.length));
}
Complex[] transformed = new Complex[f.length];
if (f.length == 1) {
transformed[0] = new Complex(f[0], 0.0);
return transformed;
}
// Rather than the naive real to complex conversion, pack 2N
// real numbers into N complex numbers for better performance.
int n = f.length >> 1;
Complex[] repacked = new Complex[n];
for (int i = 0; i < n; i++) {
repacked[i] = new Complex(f[2 * i], f[2 * i + 1]);
}
roots.computeRoots(isInverse ? n : -n);
Complex[] z = fft(repacked);
// reconstruct the FFT result for the original array
roots.computeRoots(isInverse ? 2 * n : -2 * n);
transformed[0] = new Complex(2 * (z[0].getReal() + z[0].getImaginary()), 0.0);
transformed[n] = new Complex(2 * (z[0].getReal() - z[0].getImaginary()), 0.0);
for (int i = 1; i < n; i++) {
Complex a = z[n - i].conjugate();
Complex b = z[i].add(a);
Complex c = z[i].subtract(a);
//Complex D = roots.getOmega(i).multiply(Complex.I);
Complex d = new Complex(-roots.getImaginary(i),
roots.getReal(i));
transformed[i] = b.subtract(c.multiply(d));
transformed[2 * n - i] = transformed[i].conjugate();
}
return TransformUtils.scaleArray(transformed, 0.5);
}
/**
* Returns the FFT of the specified complex data set. Performs the base-4
* Cooley-Tukey FFT algorithm.
*
* @param data the complex data array to be transformed
* @return the complex transformed array
* @throws MathIllegalArgumentException if the length of the data array is
* not a power of two
*/
protected Complex[] fft(Complex[] data) {
if (!ArithmeticUtils.isPowerOfTwo(data.length)) {
throw new MathIllegalArgumentException(
LocalizedFormats.NOT_POWER_OF_TWO_CONSIDER_PADDING,
Integer.valueOf(data.length));
}
final int n = data.length;
final Complex[] f = new Complex[n];
// initial simple cases
if (n == 1) {
f[0] = data[0];
return f;
}
if (n == 2) {
f[0] = data[0].add(data[1]);
f[1] = data[0].subtract(data[1]);
return f;
}
// permute original data array in bit-reversal order
int ii = 0;
for (int i = 0; i < n; i++) {
f[i] = data[ii];
int k = n >> 1;
while (ii >= k && k > 0) {
ii -= k; k >>= 1;
}
ii += k;
}
// the bottom base-4 round
for (int i = 0; i < n; i += 4) {
final Complex a = f[i].add(f[i + 1]);
final Complex b = f[i + 2].add(f[i + 3]);
final Complex c = f[i].subtract(f[i + 1]);
final Complex d = f[i + 2].subtract(f[i + 3]);
final Complex e1 = c.add(d.multiply(Complex.I));
final Complex e2 = c.subtract(d.multiply(Complex.I));
f[i] = a.add(b);
f[i + 2] = a.subtract(b);
// omegaCount indicates forward or inverse transform
f[i + 1] = roots.isCounterClockWise() ? e1 : e2;
f[i + 3] = roots.isCounterClockWise() ? e2 : e1;
}
// iterations from bottom to top take O(N*logN) time
for (int i = 4; i < n; i <<= 1) {
final int m = n / (i << 1);
for (int j = 0; j < n; j += i << 1) {
for (int k = 0; k < i; k++) {
//z = f[i+j+k].multiply(roots.getOmega(k*m));
final int km = k * m;
final double omegaKmReal = roots.getReal(km);
final double omegaKmImag = roots.getImaginary(km);
//z = f[i+j+k].multiply(omega[k*m]);
final Complex z = new Complex(
f[i + j + k].getReal() * omegaKmReal -
f[i + j + k].getImaginary() * omegaKmImag,
f[i + j + k].getReal() * omegaKmImag +
f[i + j + k].getImaginary() * omegaKmReal);
f[i + j + k] = f[j + k].subtract(z);
f[j + k] = f[j + k].add(z);
}
}
}
return f;
}
/**
* Performs a multi-dimensional Fourier transform on a given array. Use
* {@link #transform(Complex[])} and {@link #inverseTransform(Complex[])} in
* a row-column implementation in any number of dimensions with
* O(N×log(N)) complexity with
* N = n<sub>1</sub> × n<sub>2</sub> ×n<sub>3</sub> × ...
* × n<sub>d</sub>, where n<sub>k</sub> is the number of elements in
* dimension k, and d is the total number of dimensions.
*
* @param mdca Multi-Dimensional Complex Array id est
* {@code Complex[][][][]}
* @param forward {@link #inverseTransform} is performed if this is
* {@code false}
* @return transform of {@code mdca} as a Multi-Dimensional Complex Array
* id est {@code Complex[][][][]}
* @throws IllegalArgumentException if any dimension is not a power of two
* @deprecated see
* <a href="https://issues.apache.org/jira/browse/MATH-736">MATH-736</a>
*/
@Deprecated
public Object mdfft(Object mdca, boolean forward) {
MultiDimensionalComplexMatrix mdcm = (MultiDimensionalComplexMatrix)
new MultiDimensionalComplexMatrix(mdca).clone();
int[] dimensionSize = mdcm.getDimensionSizes();
//cycle through each dimension
for (int i = 0; i < dimensionSize.length; i++) {
mdfft(mdcm, forward, i, new int[0]);
}
return mdcm.getArray();
}
/**
* Performs one dimension of a multi-dimensional Fourier transform.
*
* @param mdcm input matrix
* @param forward {@link #inverseTransform} is performed if this is
* {@code false}
* @param d index of the dimension to process
* @param subVector recursion subvector
* @throws IllegalArgumentException if any dimension is not a power of two
*/
private void mdfft(MultiDimensionalComplexMatrix mdcm,
boolean forward, int d, int[] subVector) {
int[] dimensionSize = mdcm.getDimensionSizes();
//if done
if (subVector.length == dimensionSize.length) {
Complex[] temp = new Complex[dimensionSize[d]];
for (int i = 0; i < dimensionSize[d]; i++) {
//fft along dimension d
subVector[d] = i;
temp[i] = mdcm.get(subVector);
}
if (forward) {
temp = transform(temp);
} else {
temp = inverseTransform(temp);
}
for (int i = 0; i < dimensionSize[d]; i++) {
subVector[d] = i;
mdcm.set(temp[i], subVector);
}
} else {
int[] vector = new int[subVector.length + 1];
System.arraycopy(subVector, 0, vector, 0, subVector.length);
if (subVector.length == d) {
//value is not important once the recursion is done.
//then an fft will be applied along the dimension d.
vector[d] = 0;
mdfft(mdcm, forward, d, vector);
} else {
for (int i = 0; i < dimensionSize[subVector.length]; i++) {
vector[subVector.length] = i;
//further split along the next dimension
mdfft(mdcm, forward, d, vector);
}
}
}
return;
}
/**
* Complex matrix implementation. Not designed for synchronized access may
* eventually be replaced by jsr-83 of the java community process
* http://jcp.org/en/jsr/detail?id=83
* may require additional exception throws for other basic requirements.
*
* @deprecated see MATH-736
*/
@Deprecated
private static class MultiDimensionalComplexMatrix
implements Cloneable {
/** Size in all dimensions. */
protected int[] dimensionSize;
/** Storage array. */
protected Object multiDimensionalComplexArray;
/**
* Simple constructor.
*
* @param multiDimensionalComplexArray array containing the matrix
* elements
*/
public MultiDimensionalComplexMatrix(
Object multiDimensionalComplexArray) {
this.multiDimensionalComplexArray = multiDimensionalComplexArray;
// count dimensions
int numOfDimensions = 0;
for (Object lastDimension = multiDimensionalComplexArray;
lastDimension instanceof Object[];) {
final Object[] array = (Object[]) lastDimension;
numOfDimensions++;
lastDimension = array[0];
}
// allocate array with exact count
dimensionSize = new int[numOfDimensions];
// fill array
numOfDimensions = 0;
for (Object lastDimension = multiDimensionalComplexArray;
lastDimension instanceof Object[];) {
final Object[] array = (Object[]) lastDimension;
dimensionSize[numOfDimensions++] = array.length;
lastDimension = array[0];
}
}
/**
* Get a matrix element.
*
* @param vector indices of the element
* @return matrix element
* @exception DimensionMismatchException if dimensions do not match
*/
public Complex get(int... vector)
throws DimensionMismatchException {
if (vector == null) {
if (dimensionSize.length > 0) {
throw new DimensionMismatchException(
0,
dimensionSize.length);
}
return null;
}
if (vector.length != dimensionSize.length) {
throw new DimensionMismatchException(
vector.length,
dimensionSize.length);
}
Object lastDimension = multiDimensionalComplexArray;
for (int i = 0; i < dimensionSize.length; i++) {
lastDimension = ((Object[]) lastDimension)[vector[i]];
}
return (Complex) lastDimension;
}
/**
* Set a matrix element.
*
* @param magnitude magnitude of the element
* @param vector indices of the element
* @return the previous value
* @exception DimensionMismatchException if dimensions do not match
*/
public Complex set(Complex magnitude, int... vector)
throws DimensionMismatchException {
if (vector == null) {
if (dimensionSize.length > 0) {
throw new DimensionMismatchException(
0,
dimensionSize.length);
}
return null;
}
if (vector.length != dimensionSize.length) {
throw new DimensionMismatchException(
vector.length,
dimensionSize.length);
}
Object[] lastDimension = (Object[]) multiDimensionalComplexArray;
for (int i = 0; i < dimensionSize.length - 1; i++) {
lastDimension = (Object[]) lastDimension[vector[i]];
}
Complex lastValue = (Complex) lastDimension[vector[dimensionSize.length - 1]];
lastDimension[vector[dimensionSize.length - 1]] = magnitude;
return lastValue;
}
/**
* Get the size in all dimensions.
*
* @return size in all dimensions
*/
public int[] getDimensionSizes() {
return dimensionSize.clone();
}
/**
* Get the underlying storage array.
*
* @return underlying storage array
*/
public Object getArray() {
return multiDimensionalComplexArray;
}
/** {@inheritDoc} */
@Override
public Object clone() {
MultiDimensionalComplexMatrix mdcm =
new MultiDimensionalComplexMatrix(Array.newInstance(
Complex.class, dimensionSize));
clone(mdcm);
return mdcm;
}
/**
* Copy contents of current array into mdcm.
*
* @param mdcm array where to copy data
*/
private void clone(MultiDimensionalComplexMatrix mdcm) {
int[] vector = new int[dimensionSize.length];
int size = 1;
for (int i = 0; i < dimensionSize.length; i++) {
size *= dimensionSize[i];
}
int[][] vectorList = new int[size][dimensionSize.length];
for (int[] nextVector : vectorList) {
System.arraycopy(vector, 0, nextVector, 0,
dimensionSize.length);
for (int i = 0; i < dimensionSize.length; i++) {
vector[i]++;
if (vector[i] < dimensionSize[i]) {
break;
} else {
vector[i] = 0;
}
}
}
for (int[] nextVector : vectorList) {
mdcm.set(get(nextVector), nextVector);
}
}
}
}
|
src/main/java/org/apache/commons/math/transform/FastFourierTransformer.java
|
/*
* 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.commons.math.transform;
import java.io.Serializable;
import java.lang.reflect.Array;
import org.apache.commons.math.analysis.FunctionUtils;
import org.apache.commons.math.analysis.UnivariateFunction;
import org.apache.commons.math.complex.Complex;
import org.apache.commons.math.complex.RootsOfUnity;
import org.apache.commons.math.exception.DimensionMismatchException;
import org.apache.commons.math.exception.MathIllegalArgumentException;
import org.apache.commons.math.exception.util.LocalizedFormats;
import org.apache.commons.math.util.ArithmeticUtils;
import org.apache.commons.math.util.FastMath;
/**
* <p>
* Implements the Fast Fourier Transform for transformation of one-dimensional
* real or complex data sets. For reference, see <em>Applied Numerical Linear
* Algebra</em>, ISBN 0898713897, chapter 6.
* </p>
* <p>
* There are several variants of the discrete Fourier transform, with various
* normalization conventions, which are described below.
* </p>
* <p>
* The current implementation of the discrete Fourier transform as a fast
* Fourier transform requires the length of the data set to be a power of 2.
* This greatly simplifies and speeds up the code. Users can pad the data with
* zeros to meet this requirement. There are other flavors of FFT, for
* reference, see S. Winograd,
* <i>On computing the discrete Fourier transform</i>, Mathematics of
* Computation, 32 (1978), 175 - 199.
* </p>
* <h3><a id="standard">Standard DFT</a></h3>
* <p>
* The standard normalization convention is defined as follows
* <ul>
* <li>forward transform: y<sub>n</sub> = ∑<sub>k=0</sub><sup>N-1</sup>
* x<sub>k</sub> exp(-2πi n k / N),</li>
* <li>inverse transform: x<sub>k</sub> = N<sup>-1</sup>
* ∑<sub>n=0</sub><sup>N-1</sup> y<sub>n</sub> exp(2πi n k / N),</li>
* </ul>
* where N is the size of the data sample.
* </p>
* <p>
* {@link FastFourierTransformer}s following this convention are returned by the
* factory method {@link #create()}.
* </p>
* <h3><a id="unitary">Unitary DFT</a></h3>
* <p>
* The unitary normalization convention is defined as follows
* <ul>
* <li>forward transform: y<sub>n</sub> = (1 / √N)
* ∑<sub>k=0</sub><sup>N-1</sup> x<sub>k</sub> exp(-2πi n k / N),</li>
* <li>inverse transform: x<sub>k</sub> = (1 / √N)
* ∑<sub>n=0</sub><sup>N-1</sup> y<sub>n</sub> exp(2πi n k / N),</li>
* </ul>
* which makes the transform unitary. N is the size of the data sample.
* </p>
* <p>
* {@link FastFourierTransformer}s following this convention are returned by the
* factory method {@link #createUnitary()}.
* </p>
*
* @version $Id$
* @since 1.2
*/
public class FastFourierTransformer implements Serializable {
/** Serializable version identifier. */
static final long serialVersionUID = 20120501L;
/**
* {@code true} if the unitary version of the DFT should be used.
*
* @see #create()
* @see #createUnitary()
*/
private final boolean unitary;
/** The roots of unity. */
private RootsOfUnity roots = new RootsOfUnity();
/**
* Creates a new instance of this class, with various normalization
* conventions.
*
* @param unitary {@code false} if the DFT is <em>not</em> to be scaled,
* {@code true} if it is to be scaled so as to make the transform unitary.
* @see #create()
* @see #createUnitary()
*/
private FastFourierTransformer(final boolean unitary) {
this.unitary = unitary;
}
/**
* <p>
* Returns a new instance of this class. The returned transformer uses the
* <a href="#standard">standard normalizing conventions</a>.
* </p>
*
* @return a new DFT transformer, with standard normalizing conventions
*/
public static FastFourierTransformer create() {
return new FastFourierTransformer(false);
}
/**
* <p>
* Returns a new instance of this class. The returned transformer uses the
* <a href="#unitary">unitary normalizing conventions</a>.
* </p>
*
* @return a new DFT transformer, with unitary normalizing conventions
*/
public static FastFourierTransformer createUnitary() {
return new FastFourierTransformer(true);
}
/**
* Returns the forward transform of the specified real data set.
*
* @param f the real data array to be transformed
* @return the complex transformed array
* @throws MathIllegalArgumentException if the length of the data array is
* not a power of two
*/
public Complex[] transform(double[] f) {
if (unitary) {
final double s = 1.0 / FastMath.sqrt(f.length);
return TransformUtils.scaleArray(fft(f, false), s);
}
return fft(f, false);
}
/**
* Returns the forward transform of the specified real function, sampled on
* the specified interval.
*
* @param f the function to be sampled and transformed
* @param min the (inclusive) lower bound for the interval
* @param max the (exclusive) upper bound for the interval
* @param n the number of sample points
* @return the complex transformed array
* @throws org.apache.commons.math.exception.NumberIsTooLargeException
* if the lower bound is greater than, or equal to the upper bound
* @throws org.apache.commons.math.exception.NotStrictlyPositiveException
* if the number of sample points {@code n} is negative
* @throws MathIllegalArgumentException if the number of sample points
* {@code n} is not a power of two
*/
public Complex[] transform(UnivariateFunction f,
double min, double max, int n) {
final double[] data = FunctionUtils.sample(f, min, max, n);
if (unitary) {
final double s = 1.0 / FastMath.sqrt(n);
return TransformUtils.scaleArray(fft(data, false), s);
}
return fft(data, false);
}
/**
* Returns the forward transform of the specified complex data set.
*
* @param f the complex data array to be transformed
* @return the complex transformed array
* @throws MathIllegalArgumentException if the length of the data array is
* not a power of two
*/
public Complex[] transform(Complex[] f) {
roots.computeRoots(-f.length);
if (unitary) {
final double s = 1.0 / FastMath.sqrt(f.length);
return TransformUtils.scaleArray(fft(f), s);
}
return fft(f);
}
/**
* Returns the inverse transform of the specified real data set.
*
* @param f the real data array to be inversely transformed
* @return the complex inversely transformed array
* @throws MathIllegalArgumentException if the length of the data array is
* not a power of two
*/
public Complex[] inverseTransform(double[] f) {
final double s = 1.0 / (unitary ? FastMath.sqrt(f.length) : f.length);
return TransformUtils.scaleArray(fft(f, true), s);
}
/**
* Returns the inverse transform of the specified real function, sampled
* on the given interval.
*
* @param f the function to be sampled and inversely transformed
* @param min the (inclusive) lower bound for the interval
* @param max the (exclusive) upper bound for the interval
* @param n the number of sample points
* @return the complex inversely transformed array
* @throws org.apache.commons.math.exception.NumberIsTooLargeException
* if the lower bound is greater than, or equal to the upper bound
* @throws org.apache.commons.math.exception.NotStrictlyPositiveException
* if the number of sample points {@code n} is negative
* @throws MathIllegalArgumentException if the number of sample points
* {@code n} is not a power of two
*/
public Complex[] inverseTransform(UnivariateFunction f,
double min, double max, int n) {
final double[] data = FunctionUtils.sample(f, min, max, n);
final double s = 1.0 / (unitary ? FastMath.sqrt(n) : n);
return TransformUtils.scaleArray(fft(data, true), s);
}
/**
* Returns the inverse transform of the specified complex data set.
*
* @param f the complex data array to be inversely transformed
* @return the complex inversely transformed array
* @throws MathIllegalArgumentException if the length of the data array is
* not a power of two
*/
public Complex[] inverseTransform(Complex[] f) {
roots.computeRoots(f.length);
final double s = 1.0 / (unitary ? FastMath.sqrt(f.length) : f.length);
return TransformUtils.scaleArray(fft(f), s);
}
/**
* Returns the FFT of the specified real data set. Performs the base-4
* Cooley-Tukey FFT algorithm.
*
* @param f the real data array to be transformed
* @param isInverse {@code true} if inverse transform is to be carried out
* @return the complex transformed array
* @throws MathIllegalArgumentException if the length of the data array is
* not a power of two
*/
protected Complex[] fft(double[] f, boolean isInverse) {
if (!ArithmeticUtils.isPowerOfTwo(f.length)) {
throw new MathIllegalArgumentException(
LocalizedFormats.NOT_POWER_OF_TWO_CONSIDER_PADDING,
Integer.valueOf(f.length));
}
Complex[] transformed = new Complex[f.length];
if (f.length == 1) {
transformed[0] = new Complex(f[0], 0.0);
return transformed;
}
// Rather than the naive real to complex conversion, pack 2N
// real numbers into N complex numbers for better performance.
int n = f.length >> 1;
Complex[] repacked = new Complex[n];
for (int i = 0; i < n; i++) {
repacked[i] = new Complex(f[2 * i], f[2 * i + 1]);
}
roots.computeRoots(isInverse ? n : -n);
Complex[] z = fft(repacked);
// reconstruct the FFT result for the original array
roots.computeRoots(isInverse ? 2 * n : -2 * n);
transformed[0] = new Complex(2 * (z[0].getReal() + z[0].getImaginary()), 0.0);
transformed[n] = new Complex(2 * (z[0].getReal() - z[0].getImaginary()), 0.0);
for (int i = 1; i < n; i++) {
Complex a = z[n - i].conjugate();
Complex b = z[i].add(a);
Complex c = z[i].subtract(a);
//Complex D = roots.getOmega(i).multiply(Complex.I);
Complex d = new Complex(-roots.getImaginary(i),
roots.getReal(i));
transformed[i] = b.subtract(c.multiply(d));
transformed[2 * n - i] = transformed[i].conjugate();
}
return TransformUtils.scaleArray(transformed, 0.5);
}
/**
* Returns the FFT of the specified complex data set. Performs the base-4
* Cooley-Tukey FFT algorithm.
*
* @param data the complex data array to be transformed
* @return the complex transformed array
* @throws MathIllegalArgumentException if the length of the data array is
* not a power of two
*/
protected Complex[] fft(Complex[] data) {
if (!ArithmeticUtils.isPowerOfTwo(data.length)) {
throw new MathIllegalArgumentException(
LocalizedFormats.NOT_POWER_OF_TWO_CONSIDER_PADDING,
Integer.valueOf(data.length));
}
final int n = data.length;
final Complex[] f = new Complex[n];
// initial simple cases
if (n == 1) {
f[0] = data[0];
return f;
}
if (n == 2) {
f[0] = data[0].add(data[1]);
f[1] = data[0].subtract(data[1]);
return f;
}
// permute original data array in bit-reversal order
int ii = 0;
for (int i = 0; i < n; i++) {
f[i] = data[ii];
int k = n >> 1;
while (ii >= k && k > 0) {
ii -= k; k >>= 1;
}
ii += k;
}
// the bottom base-4 round
for (int i = 0; i < n; i += 4) {
final Complex a = f[i].add(f[i + 1]);
final Complex b = f[i + 2].add(f[i + 3]);
final Complex c = f[i].subtract(f[i + 1]);
final Complex d = f[i + 2].subtract(f[i + 3]);
final Complex e1 = c.add(d.multiply(Complex.I));
final Complex e2 = c.subtract(d.multiply(Complex.I));
f[i] = a.add(b);
f[i + 2] = a.subtract(b);
// omegaCount indicates forward or inverse transform
f[i + 1] = roots.isCounterClockWise() ? e1 : e2;
f[i + 3] = roots.isCounterClockWise() ? e2 : e1;
}
// iterations from bottom to top take O(N*logN) time
for (int i = 4; i < n; i <<= 1) {
final int m = n / (i << 1);
for (int j = 0; j < n; j += i << 1) {
for (int k = 0; k < i; k++) {
//z = f[i+j+k].multiply(roots.getOmega(k*m));
final int km = k * m;
final double omegaKmReal = roots.getReal(km);
final double omegaKmImag = roots.getImaginary(km);
//z = f[i+j+k].multiply(omega[k*m]);
final Complex z = new Complex(
f[i + j + k].getReal() * omegaKmReal -
f[i + j + k].getImaginary() * omegaKmImag,
f[i + j + k].getReal() * omegaKmImag +
f[i + j + k].getImaginary() * omegaKmReal);
f[i + j + k] = f[j + k].subtract(z);
f[j + k] = f[j + k].add(z);
}
}
}
return f;
}
/**
* Performs a multi-dimensional Fourier transform on a given array. Use
* {@link #transform(Complex[])} and {@link #inverseTransform(Complex[])} in
* a row-column implementation in any number of dimensions with
* O(N×log(N)) complexity with
* N = n<sub>1</sub> × n<sub>2</sub> ×n<sub>3</sub> × ...
* × n<sub>d</sub>, where n<sub>k</sub> is the number of elements in
* dimension k, and d is the total number of dimensions.
*
* @param mdca Multi-Dimensional Complex Array id est
* {@code Complex[][][][]}
* @param forward {@link #inverseTransform} is performed if this is
* {@code false}
* @return transform of {@code mdca} as a Multi-Dimensional Complex Array
* id est {@code Complex[][][][]}
* @throws IllegalArgumentException if any dimension is not a power of two
*/
public Object mdfft(Object mdca, boolean forward) {
MultiDimensionalComplexMatrix mdcm = (MultiDimensionalComplexMatrix)
new MultiDimensionalComplexMatrix(mdca).clone();
int[] dimensionSize = mdcm.getDimensionSizes();
//cycle through each dimension
for (int i = 0; i < dimensionSize.length; i++) {
mdfft(mdcm, forward, i, new int[0]);
}
return mdcm.getArray();
}
/**
* Performs one dimension of a multi-dimensional Fourier transform.
*
* @param mdcm input matrix
* @param forward {@link #inverseTransform} is performed if this is
* {@code false}
* @param d index of the dimension to process
* @param subVector recursion subvector
* @throws IllegalArgumentException if any dimension is not a power of two
*/
private void mdfft(MultiDimensionalComplexMatrix mdcm,
boolean forward, int d, int[] subVector) {
int[] dimensionSize = mdcm.getDimensionSizes();
//if done
if (subVector.length == dimensionSize.length) {
Complex[] temp = new Complex[dimensionSize[d]];
for (int i = 0; i < dimensionSize[d]; i++) {
//fft along dimension d
subVector[d] = i;
temp[i] = mdcm.get(subVector);
}
if (forward) {
temp = transform(temp);
} else {
temp = inverseTransform(temp);
}
for (int i = 0; i < dimensionSize[d]; i++) {
subVector[d] = i;
mdcm.set(temp[i], subVector);
}
} else {
int[] vector = new int[subVector.length + 1];
System.arraycopy(subVector, 0, vector, 0, subVector.length);
if (subVector.length == d) {
//value is not important once the recursion is done.
//then an fft will be applied along the dimension d.
vector[d] = 0;
mdfft(mdcm, forward, d, vector);
} else {
for (int i = 0; i < dimensionSize[subVector.length]; i++) {
vector[subVector.length] = i;
//further split along the next dimension
mdfft(mdcm, forward, d, vector);
}
}
}
return;
}
/**
* Complex matrix implementation. Not designed for synchronized access may
* eventually be replaced by jsr-83 of the java community process
* http://jcp.org/en/jsr/detail?id=83
* may require additional exception throws for other basic requirements.
*/
private static class MultiDimensionalComplexMatrix
implements Cloneable {
/** Size in all dimensions. */
protected int[] dimensionSize;
/** Storage array. */
protected Object multiDimensionalComplexArray;
/**
* Simple constructor.
*
* @param multiDimensionalComplexArray array containing the matrix
* elements
*/
public MultiDimensionalComplexMatrix(
Object multiDimensionalComplexArray) {
this.multiDimensionalComplexArray = multiDimensionalComplexArray;
// count dimensions
int numOfDimensions = 0;
for (Object lastDimension = multiDimensionalComplexArray;
lastDimension instanceof Object[];) {
final Object[] array = (Object[]) lastDimension;
numOfDimensions++;
lastDimension = array[0];
}
// allocate array with exact count
dimensionSize = new int[numOfDimensions];
// fill array
numOfDimensions = 0;
for (Object lastDimension = multiDimensionalComplexArray;
lastDimension instanceof Object[];) {
final Object[] array = (Object[]) lastDimension;
dimensionSize[numOfDimensions++] = array.length;
lastDimension = array[0];
}
}
/**
* Get a matrix element.
*
* @param vector indices of the element
* @return matrix element
* @exception DimensionMismatchException if dimensions do not match
*/
public Complex get(int... vector)
throws DimensionMismatchException {
if (vector == null) {
if (dimensionSize.length > 0) {
throw new DimensionMismatchException(
0,
dimensionSize.length);
}
return null;
}
if (vector.length != dimensionSize.length) {
throw new DimensionMismatchException(
vector.length,
dimensionSize.length);
}
Object lastDimension = multiDimensionalComplexArray;
for (int i = 0; i < dimensionSize.length; i++) {
lastDimension = ((Object[]) lastDimension)[vector[i]];
}
return (Complex) lastDimension;
}
/**
* Set a matrix element.
*
* @param magnitude magnitude of the element
* @param vector indices of the element
* @return the previous value
* @exception DimensionMismatchException if dimensions do not match
*/
public Complex set(Complex magnitude, int... vector)
throws DimensionMismatchException {
if (vector == null) {
if (dimensionSize.length > 0) {
throw new DimensionMismatchException(
0,
dimensionSize.length);
}
return null;
}
if (vector.length != dimensionSize.length) {
throw new DimensionMismatchException(
vector.length,
dimensionSize.length);
}
Object[] lastDimension = (Object[]) multiDimensionalComplexArray;
for (int i = 0; i < dimensionSize.length - 1; i++) {
lastDimension = (Object[]) lastDimension[vector[i]];
}
Complex lastValue = (Complex) lastDimension[vector[dimensionSize.length - 1]];
lastDimension[vector[dimensionSize.length - 1]] = magnitude;
return lastValue;
}
/**
* Get the size in all dimensions.
*
* @return size in all dimensions
*/
public int[] getDimensionSizes() {
return dimensionSize.clone();
}
/**
* Get the underlying storage array.
*
* @return underlying storage array
*/
public Object getArray() {
return multiDimensionalComplexArray;
}
/** {@inheritDoc} */
@Override
public Object clone() {
MultiDimensionalComplexMatrix mdcm =
new MultiDimensionalComplexMatrix(Array.newInstance(
Complex.class, dimensionSize));
clone(mdcm);
return mdcm;
}
/**
* Copy contents of current array into mdcm.
*
* @param mdcm array where to copy data
*/
private void clone(MultiDimensionalComplexMatrix mdcm) {
int[] vector = new int[dimensionSize.length];
int size = 1;
for (int i = 0; i < dimensionSize.length; i++) {
size *= dimensionSize[i];
}
int[][] vectorList = new int[size][dimensionSize.length];
for (int[] nextVector : vectorList) {
System.arraycopy(vector, 0, nextVector, 0,
dimensionSize.length);
for (int i = 0; i < dimensionSize.length; i++) {
vector[i]++;
if (vector[i] < dimensionSize[i]) {
break;
} else {
vector[i] = 0;
}
}
}
for (int[] nextVector : vectorList) {
mdcm.set(get(nextVector), nextVector);
}
}
}
}
|
- deprecated o.a.c.m.transform.FastFourierTransformer.mdfft(Object, boolean)
- deprecated o.a.c.m.transform.FastFourierTransformer.MultiDimensionalComplexMatrix
see MATH-736
git-svn-id: 80d496c472b8b763a5e941dba212da9bf48aeceb@1240012 13f79535-47bb-0310-9956-ffa450edef68
|
src/main/java/org/apache/commons/math/transform/FastFourierTransformer.java
|
- deprecated o.a.c.m.transform.FastFourierTransformer.mdfft(Object, boolean) - deprecated o.a.c.m.transform.FastFourierTransformer.MultiDimensionalComplexMatrix see MATH-736
|
|
Java
|
apache-2.0
|
8004df9f47d2741b4fec4b37752b0bb76d2b3cd1
| 0
|
rolandkrueger/uri-fragment-routing
|
/*
* Copyright (C) 2007 - 2010 Roland Krueger
* Created on 02.03.2010
*
* Author: Roland Krueger (www.rolandkrueger.info)
*
* This file is part of RoKlib.
*
* 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.roklib.webapps.uridispatching.parameter;
import org.roklib.webapps.uridispatching.URIActionCommand;
import org.roklib.webapps.uridispatching.mapper.AbstractURIPathSegmentActionMapper;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
public interface URIParameter<V> extends Serializable {
boolean consume(Map<String, List<String>> parameters);
boolean consumeList(String[] values);
V getValue();
void setValue(V value);
@Deprecated
void clearValue();
URIActionCommand getErrorCommandIfInvalid();
EnumURIParameterErrors getError();
void parameterizeURIHandler(AbstractURIPathSegmentActionMapper handler);
void setValueAndParameterizeURIHandler(V value, AbstractURIPathSegmentActionMapper handler);
boolean hasValue();
void setOptional(boolean optional);
boolean isOptional();
int getSingleValueCount();
List<String> getParameterNames();
}
|
src/main/java/org/roklib/webapps/uridispatching/parameter/URIParameter.java
|
/*
* Copyright (C) 2007 - 2010 Roland Krueger
* Created on 02.03.2010
*
* Author: Roland Krueger (www.rolandkrueger.info)
*
* This file is part of RoKlib.
*
* 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.roklib.webapps.uridispatching.parameter;
import org.roklib.webapps.uridispatching.URIActionCommand;
import org.roklib.webapps.uridispatching.mapper.AbstractURIPathSegmentActionMapper;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
public interface URIParameter<V> extends Serializable {
boolean consume(Map<String, List<String>> parameters);
boolean consumeList(String[] values);
V getValue();
void setValue(V value);
void clearValue();
URIActionCommand getErrorCommandIfInvalid();
EnumURIParameterErrors getError();
void parameterizeURIHandler(AbstractURIPathSegmentActionMapper handler);
void setValueAndParameterizeURIHandler(V value, AbstractURIPathSegmentActionMapper handler);
boolean hasValue();
void setOptional(boolean optional);
boolean isOptional();
int getSingleValueCount();
List<String> getParameterNames();
}
|
Deprecate clearValue()
|
src/main/java/org/roklib/webapps/uridispatching/parameter/URIParameter.java
|
Deprecate clearValue()
|
|
Java
|
apache-2.0
|
b12a354d55153891154df0c7af7e03a3c9cc0a75
| 0
|
monetate/closure-compiler,mcanthony/closure-compiler,jimmytuc/closure-compiler,mcanthony/closure-compiler,jaen/closure-compiler,Yannic/closure-compiler,shantanusharma/closure-compiler,Yannic/closure-compiler,tiobe/closure-compiler,dlochrie/closure-compiler,vobruba-martin/closure-compiler,pr4v33n/closure-compiler,fvigotti/closure-compiler,nawawi/closure-compiler,MatrixFrog/closure-compiler,lgeorgieff/closure-compiler,anomaly/closure-compiler,rintaro/closure-compiler,mbebenita/closure-compiler,neraliu/closure-compiler,visokio/closure-compiler,monetate/closure-compiler,ochafik/closure-compiler,rintaro/closure-compiler,BladeRunnerJS/closure-compiler,tsdl2013/closure-compiler,mediogre/closure-compiler,Yannic/closure-compiler,vobruba-martin/closure-compiler,concavelenz/closure-compiler,GerHobbelt/closure-compiler,Dominator008/closure-compiler,MatrixFrog/closure-compiler,savelichalex/closure-compiler,tiobe/closure-compiler,superkonduktr/closure-compiler,Medium/closure-compiler,shantanusharma/closure-compiler,LorenzoDV/closure-compiler,lgeorgieff/closure-compiler,thurday/closure-compiler,ralic/closure-compiler,ChadKillingsworth/closure-compiler,thurday/closure-compiler,pr4v33n/closure-compiler,nawawi/closure-compiler,rintaro/closure-compiler,dlochrie/closure-compiler,rockyzh/closure-compiler,monetate/closure-compiler,mbebenita/closure-compiler,anomaly/closure-compiler,vobruba-martin/closure-compiler,visokio/closure-compiler,pauldraper/closure-compiler,anneupsc/closure-compiler,superkonduktr/closure-compiler,jimmytuc/closure-compiler,tiobe/closure-compiler,tdelmas/closure-compiler,ChadKillingsworth/closure-compiler,Dominator008/closure-compiler,anneupsc/closure-compiler,Dominator008/closure-compiler,mweissbacher/closure-compiler,mprobst/closure-compiler,fvigotti/closure-compiler,mprobst/closure-compiler,tdelmas/closure-compiler,tiobe/closure-compiler,GerHobbelt/closure-compiler,shantanusharma/closure-compiler,visokio/closure-compiler,rockyzh/closure-compiler,brad4d/closure-compiler,Pimm/closure-compiler,fvigotti/closure-compiler,ChadKillingsworth/closure-compiler,lgeorgieff/closure-compiler,google/closure-compiler,thurday/closure-compiler,MatrixFrog/closure-compiler,pauldraper/closure-compiler,mweissbacher/closure-compiler,mbrukman/closure-compiler,GerHobbelt/closure-compiler,redforks/closure-compiler,superkonduktr/closure-compiler,GerHobbelt/closure-compiler,concavelenz/closure-compiler,ralic/closure-compiler,nawawi/closure-compiler,lgeorgieff/closure-compiler,selkhateeb/closure-compiler,Yannic/closure-compiler,tsdl2013/closure-compiler,mediogre/closure-compiler,nawawi/closure-compiler,Medium/closure-compiler,mbrukman/closure-compiler,neraliu/closure-compiler,savelichalex/closure-compiler,tsdl2013/closure-compiler,redforks/closure-compiler,rockyzh/closure-compiler,mneise/closure-compiler,jaen/closure-compiler,shantanusharma/closure-compiler,mprobst/closure-compiler,mweissbacher/closure-compiler,ochafik/closure-compiler,LorenzoDV/closure-compiler,savelichalex/closure-compiler,LorenzoDV/closure-compiler,anomaly/closure-compiler,BladeRunnerJS/closure-compiler,mprobst/closure-compiler,mneise/closure-compiler,mneise/closure-compiler,neraliu/closure-compiler,google/closure-compiler,dlochrie/closure-compiler,TomK/closure-compiler,mediogre/closure-compiler,MatrixFrog/closure-compiler,brad4d/closure-compiler,Pimm/closure-compiler,superkonduktr/closure-compiler,ChadKillingsworth/closure-compiler,ralic/closure-compiler,tdelmas/closure-compiler,tdelmas/closure-compiler,TomK/closure-compiler,anneupsc/closure-compiler,vobruba-martin/closure-compiler,jimmytuc/closure-compiler,pr4v33n/closure-compiler,Medium/closure-compiler,mcanthony/closure-compiler,BladeRunnerJS/closure-compiler,brad4d/closure-compiler,mweissbacher/closure-compiler,concavelenz/closure-compiler,TomK/closure-compiler,redforks/closure-compiler,anomaly/closure-compiler,ochafik/closure-compiler,monetate/closure-compiler,google/closure-compiler,Pimm/closure-compiler,selkhateeb/closure-compiler,selkhateeb/closure-compiler,mbrukman/closure-compiler,mbebenita/closure-compiler,pauldraper/closure-compiler,google/closure-compiler,jaen/closure-compiler
|
/*
* Copyright 2009 The Closure Compiler 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 com.google.javascript.jscomp;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Files;
import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage;
import com.google.javascript.jscomp.CompilerOptions.ExtractPrototypeMemberDeclarationsMode;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.jscomp.CoverageInstrumentationPass.CoverageReach;
import com.google.javascript.jscomp.ExtractPrototypeMemberDeclarations.Pattern;
import com.google.javascript.jscomp.NodeTraversal.Callback;
import com.google.javascript.jscomp.lint.CheckEmptyStatements;
import com.google.javascript.jscomp.lint.CheckEnums;
import com.google.javascript.jscomp.lint.CheckInterfaces;
import com.google.javascript.jscomp.lint.CheckJSDocStyle;
import com.google.javascript.jscomp.lint.CheckNullableReturn;
import com.google.javascript.jscomp.lint.CheckPrototypeProperties;
import com.google.javascript.jscomp.lint.CheckRequiresAndProvidesSorted;
import com.google.javascript.jscomp.parsing.ParserRunner;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Pass factories and meta-data for native JSCompiler passes.
*
* @author nicksantos@google.com (Nick Santos)
*/
// TODO(nicksantos): This needs state for a variety of reasons. Some of it
// is to satisfy the existing API. Some of it is because passes really do
// need to share state in non-trivial ways. This should be audited and
// cleaned up.
public final class DefaultPassConfig extends PassConfig {
/* For the --mark-as-compiled pass */
private static final String COMPILED_CONSTANT_NAME = "COMPILED";
/* Constant name for Closure's locale */
private static final String CLOSURE_LOCALE_CONSTANT_NAME = "goog.LOCALE";
static final DiagnosticType CANNOT_USE_PROTOTYPE_AND_VAR =
DiagnosticType.error("JSC_CANNOT_USE_PROTOTYPE_AND_VAR",
"Rename prototypes and inline variables cannot be used together.");
// Miscellaneous errors.
static final DiagnosticType REPORT_PATH_IO_ERROR =
DiagnosticType.error("JSC_REPORT_PATH_IO_ERROR",
"Error writing compiler report to {0}");
private static final DiagnosticType NAME_REF_GRAPH_FILE_ERROR =
DiagnosticType.error("JSC_NAME_REF_GRAPH_FILE_ERROR",
"Error \"{1}\" writing name reference graph to \"{0}\".");
private static final DiagnosticType NAME_REF_REPORT_FILE_ERROR =
DiagnosticType.error("JSC_NAME_REF_REPORT_FILE_ERROR",
"Error \"{1}\" writing name reference report to \"{0}\".");
private static final java.util.regex.Pattern GLOBAL_SYMBOL_NAMESPACE_PATTERN =
java.util.regex.Pattern.compile("^[a-zA-Z0-9$_]+$");
/**
* A global namespace to share across checking passes.
*/
private GlobalNamespace namespaceForChecks = null;
/**
* A symbol table for registering references that get removed during
* preprocessing.
*/
private PreprocessorSymbolTable preprocessorSymbolTable = null;
/** Names exported by goog.exportSymbol. */
private Set<String> exportedNames = null;
/**
* Ids for cross-module method stubbing, so that each method has
* a unique id.
*/
private CrossModuleMethodMotion.IdGenerator crossModuleIdGenerator =
new CrossModuleMethodMotion.IdGenerator();
/**
* Keys are arguments passed to getCssName() found during compilation; values
* are the number of times the key appeared as an argument to getCssName().
*/
private Map<String, Integer> cssNames = null;
/** The variable renaming map */
private VariableMap variableMap = null;
/** The property renaming map */
private VariableMap propertyMap = null;
/** The naming map for anonymous functions */
private VariableMap anonymousFunctionNameMap = null;
/** Fully qualified function names and globally unique ids */
private FunctionNames functionNames = null;
/** String replacement map */
private VariableMap stringMap = null;
/** Id generator map */
private String idGeneratorMap = null;
/**
* Whether to protect "hidden" side-effects.
* @see CheckSideEffects
*/
private final boolean protectHiddenSideEffects;
public DefaultPassConfig(CompilerOptions options) {
super(options);
// The current approach to protecting "hidden" side-effects is to
// wrap them in a function call that is stripped later, this shouldn't
// be done in IDE mode where AST changes may be unexpected.
protectHiddenSideEffects = options != null &&
options.protectHiddenSideEffects && !options.ideMode;
}
@Override
protected State getIntermediateState() {
return new State(
cssNames == null ? null : new HashMap<>(cssNames),
exportedNames == null ? null :
Collections.unmodifiableSet(exportedNames),
crossModuleIdGenerator, variableMap, propertyMap,
anonymousFunctionNameMap, stringMap, functionNames, idGeneratorMap);
}
@Override
protected void setIntermediateState(State state) {
this.cssNames = state.cssNames == null ? null :
new HashMap<>(state.cssNames);
this.exportedNames = state.exportedNames == null ? null :
new HashSet<>(state.exportedNames);
this.crossModuleIdGenerator = state.crossModuleIdGenerator;
this.variableMap = state.variableMap;
this.propertyMap = state.propertyMap;
this.anonymousFunctionNameMap = state.anonymousFunctionNameMap;
this.stringMap = state.stringMap;
this.functionNames = state.functionNames;
this.idGeneratorMap = state.idGeneratorMap;
}
GlobalNamespace getGlobalNamespace() {
return namespaceForChecks;
}
PreprocessorSymbolTable getPreprocessorSymbolTable() {
return preprocessorSymbolTable;
}
void maybeInitializePreprocessorSymbolTable(AbstractCompiler compiler) {
if (options.ideMode) {
Node root = compiler.getRoot();
if (preprocessorSymbolTable == null ||
preprocessorSymbolTable.getRootNode() != root) {
preprocessorSymbolTable = new PreprocessorSymbolTable(root);
}
}
}
@Override
protected List<PassFactory> getChecks() {
List<PassFactory> checks = new ArrayList<>();
checks.add(createEmptyPass("beforeStandardChecks"));
// Verify JsDoc annotations
checks.add(checkJsDoc);
if (options.getLanguageIn() == LanguageMode.ECMASCRIPT6_TYPED
&& options.getLanguageOut() != LanguageMode.ECMASCRIPT6_TYPED) {
checks.add(convertEs6TypedToEs6);
}
// Early ES6 transpilation.
// Includes ES6 features that are straightforward to transpile.
// We won't handle them natively in the rest of the compiler, so we always
// transpile them, even if the output language is also ES6.
if (options.getLanguageIn().isEs6OrHigher() && !options.skipTranspilationAndCrash) {
checks.add(es6RewriteArrowFunction);
checks.add(es6RenameVariablesInParamLists);
checks.add(es6SplitVariableDeclarations);
checks.add(es6RewriteDestructuring);
}
// goog.module rewrite must happen even if options.skipNonTranspilationPasses is set.
if (options.closurePass) {
checks.add(closureRewriteModule);
}
if (!options.skipNonTranspilationPasses && options.declaredGlobalExternsOnWindow) {
checks.add(declaredGlobalExternsOnWindow);
}
checks.add(checkVariableReferences);
if (!options.skipNonTranspilationPasses && options.closurePass) {
checks.add(closureGoogScopeAliases);
checks.add(closureRewriteClass);
}
if (options.enables(DiagnosticGroups.MISSING_REQUIRE)
|| options.enables(DiagnosticGroups.EXTRA_REQUIRE)) {
checks.add(checkRequires);
}
checks.add(checkSideEffects);
if (options.checkProvides.isOn() || options.enables(DiagnosticGroups.MISSING_PROVIDE)) {
checks.add(checkProvides);
}
if (options.jqueryPass && !options.skipNonTranspilationPasses) {
checks.add(jqueryAliases);
}
if (options.generateExports && !options.skipNonTranspilationPasses) {
checks.add(generateExports);
}
if (options.exportTestFunctions && !options.skipNonTranspilationPasses) {
checks.add(exportTestFunctions);
}
// Late ES6 transpilation.
// Includes ES6 features that are best handled natively by the compiler.
// As we convert more passes to handle these features, we will be moving the transpilation
// later in the compilation, and eventually only transpiling when the output is lower than ES6.
if (options.getLanguageIn().isEs6OrHigher() && !options.skipTranspilationAndCrash) {
checks.add(es6ConvertSuper);
checks.add(convertEs6ToEs3);
checks.add(rewriteLetConst);
checks.add(rewriteGenerators);
checks.add(markTranspilationDone);
}
if (options.raiseToEs6Typed()) {
checks.add(convertToTypedES6);
}
if (options.skipNonTranspilationPasses) {
return checks;
}
if (options.getLanguageIn().isEs6OrHigher()) {
checks.add(es6RuntimeLibrary);
}
checks.add(convertStaticInheritance);
// End of ES6 transpilation passes.
if (options.angularPass) {
checks.add(angularPass);
}
if (options.closurePass) {
checks.add(closurePrimitives);
}
// It's important that the PolymerPass run *after* the ClosurePrimitives rewrite and *before*
// the suspicious code checks.
if (options.polymerPass) {
checks.add(polymerPass);
}
if (options.checkSuspiciousCode
|| options.enables(DiagnosticGroups.GLOBAL_THIS)
|| options.enables(DiagnosticGroups.DEBUGGER_STATEMENT_PRESENT)) {
checks.add(suspiciousCode);
}
if (options.closurePass && options.checkMissingGetCssNameLevel.isOn()) {
checks.add(closureCheckGetCssName);
}
if (options.syntheticBlockStartMarker != null) {
// This pass must run before the first fold constants pass.
checks.add(createSyntheticBlocks);
}
checks.add(checkVars);
if (options.inferConsts) {
checks.add(inferConsts);
}
if (options.computeFunctionSideEffects) {
checks.add(checkRegExp);
}
// This pass should run before types are assigned.
if (options.processObjectPropertyString) {
checks.add(objectPropertyStringPreprocess);
}
checks.add(createEmptyPass("beforeTypeChecking"));
if (options.useNewTypeInference) {
checks.add(symbolTableForNewTypeInference);
checks.add(newTypeInference);
}
if (options.checkTypes || options.inferTypes) {
checks.add(resolveTypes);
checks.add(inferTypes);
if (options.checkTypes) {
checks.add(checkTypes);
} else {
checks.add(inferJsDocInfo);
}
// We assume that only IDE-mode clients will try to query the
// typed scope creator after the compile job.
if (!options.ideMode) {
checks.add(clearTypedScopePass);
}
}
if (!options.disables(DiagnosticGroups.CHECK_USELESS_CODE) ||
options.checkMissingReturn.isOn()) {
checks.add(checkControlFlow);
}
// CheckAccessControls only works if check types is on.
if (options.checkTypes &&
(!options.disables(DiagnosticGroups.ACCESS_CONTROLS)
|| options.enables(DiagnosticGroups.CONSTANT_PROPERTY))) {
checks.add(checkAccessControls);
}
// Lint checks must be run after typechecking.
if (options.enables(DiagnosticGroups.LINT_CHECKS)) {
checks.add(lintChecks);
}
if (options.checkEventfulObjectDisposalPolicy !=
CheckEventfulObjectDisposal.DisposalCheckingPolicy.OFF) {
checks.add(checkEventfulObjectDisposal);
}
if (options.checkGlobalNamesLevel.isOn()) {
checks.add(checkGlobalNames);
}
if (options.enables(DiagnosticGroups.ES5_STRICT)) {
checks.add(checkStrictMode);
}
if (!options.getConformanceConfigs().isEmpty()) {
checks.add(checkConformance);
}
// Replace 'goog.getCssName' before processing defines but after the
// other checks have been done.
if (options.closurePass) {
checks.add(closureReplaceGetCssName);
}
// i18n
// If you want to customize the compiler to use a different i18n pass,
// you can create a PassConfig that calls replacePassFactory
// to replace this.
if (options.replaceMessagesWithChromeI18n) {
checks.add(replaceMessagesForChrome);
} else if (options.messageBundle != null) {
checks.add(replaceMessages);
}
if (options.getTweakProcessing().isOn()) {
checks.add(processTweaks);
}
// Defines in code always need to be processed.
checks.add(processDefines);
if (options.instrumentationTemplate != null ||
options.recordFunctionInformation) {
checks.add(computeFunctionNames);
}
if (options.nameReferenceGraphPath != null &&
!options.nameReferenceGraphPath.isEmpty()) {
checks.add(printNameReferenceGraph);
}
if (options.nameReferenceReportPath != null &&
!options.nameReferenceReportPath.isEmpty()) {
checks.add(printNameReferenceReport);
}
checks.add(createEmptyPass("afterStandardChecks"));
assertAllOneTimePasses(checks);
assertValidOrder(checks);
return checks;
}
@Override
protected List<PassFactory> getOptimizations() {
List<PassFactory> passes = new ArrayList<>();
if (options.skipNonTranspilationPasses) {
return passes;
}
// Gather property names in externs so they can be queried by the
// optimising passes.
passes.add(gatherExternProperties);
passes.add(garbageCollectChecks);
// TODO(nicksantos): The order of these passes makes no sense, and needs
// to be re-arranged.
if (options.instrumentForCoverage) {
passes.add(instrumentForCodeCoverage);
}
if (options.runtimeTypeCheck) {
passes.add(runtimeTypeCheck);
}
passes.add(createEmptyPass("beforeStandardOptimizations"));
if (options.replaceIdGenerators) {
passes.add(replaceIdGenerators);
}
// Optimizes references to the arguments variable.
if (options.optimizeArgumentsArray) {
passes.add(optimizeArgumentsArray);
}
// Abstract method removal works best on minimally modified code, and also
// only needs to run once.
if (options.closurePass &&
(options.removeAbstractMethods || options.removeClosureAsserts)) {
passes.add(closureCodeRemoval);
}
// Property disambiguation should only run once and needs to be done
// soon after type checking, both so that it can make use of type
// information and so that other passes can take advantage of the renamed
// properties.
if (options.disambiguatePrivateProperties) {
passes.add(disambiguatePrivateProperties);
}
// Collapsing properties can undo constant inlining, so we do this before
// the main optimization loop.
if (options.collapseProperties) {
passes.add(collapseProperties);
}
if (options.inferConsts) {
passes.add(inferConsts);
}
// Running this pass before disambiguate properties allow the removing
// unused methods that share the same name as methods called from unused
// code.
if (options.extraSmartNameRemoval && options.smartNameRemoval) {
// These passes remove code that is dead because of define flags.
// If the dead code is weakly typed, running these passes before property
// disambiguation results in more code removal.
// The passes are one-time on purpose. (The later runs are loopable.)
if (options.foldConstants &&
(options.inlineVariables || options.inlineLocalVariables)) {
passes.add(earlyInlineVariables);
passes.add(earlyPeepholeOptimizations);
}
passes.add(smartNamePass);
}
// Property disambiguation should only run once and needs to be done
// soon after type checking, both so that it can make use of type
// information and so that other passes can take advantage of the renamed
// properties.
if (options.disambiguateProperties) {
passes.add(disambiguateProperties);
}
if (options.computeFunctionSideEffects) {
passes.add(markPureFunctions);
} else if (options.markNoSideEffectCalls) {
// TODO(user) The properties that this pass adds to CALL and NEW
// AST nodes increase the AST's in-memory size. Given that we are
// already running close to our memory limits, we could run into
// trouble if we end up using the @nosideeffects annotation a lot
// or compute @nosideeffects annotations by looking at function
// bodies. It should be easy to propagate @nosideeffects
// annotations as part of passes that depend on this property and
// store the result outside the AST (which would allow garbage
// collection once the pass is done).
passes.add(markNoSideEffectCalls);
}
if (options.chainCalls) {
passes.add(chainCalls);
}
// Constant checking must be done after property collapsing because
// property collapsing can introduce new constants (e.g. enum values).
// TODO(johnlenz): make checkConsts namespace aware so it can be run
// as during the checks phase.
passes.add(checkConsts);
// Detects whether invocations of the method goog.string.Const.from are done
// with an argument which is a string literal.
passes.add(checkConstParams);
assertAllOneTimePasses(passes);
if (options.smartNameRemoval || options.reportPath != null) {
passes.addAll(getCodeRemovingPasses());
passes.add(smartNamePass);
}
// This needs to come after the inline constants pass, which is run within
// the code removing passes.
if (options.closurePass) {
passes.add(closureOptimizePrimitives);
}
// ReplaceStrings runs after CollapseProperties in order to simplify
// pulling in values of constants defined in enums structures. It also runs
// after disambiguate properties and smart name removal so that it can
// correctly identify logging types and can replace references to string
// expressions.
if (!options.replaceStringsFunctionDescriptions.isEmpty()) {
passes.add(replaceStrings);
}
// TODO(user): This forces a first crack at crossModuleCodeMotion
// before devirtualization. Once certain functions are devirtualized,
// it confuses crossModuleCodeMotion ability to recognized that
// it is recursive.
// TODO(user): This is meant for a temporary quick win.
// In the future, we might want to improve our analysis in
// CrossModuleCodeMotion so we don't need to do this.
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
// Method devirtualization benefits from property disambiguation so
// it should run after that pass but before passes that do
// optimizations based on global names (like cross module code motion
// and inline functions). Smart Name Removal does better if run before
// this pass.
if (options.devirtualizePrototypeMethods) {
passes.add(devirtualizePrototypeMethods);
}
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP));
}
passes.add(createEmptyPass("beforeMainOptimizations"));
passes.addAll(getMainOptimizationLoop());
passes.add(createEmptyPass("beforeModuleMotion"));
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
if (options.crossModuleMethodMotion) {
passes.add(crossModuleMethodMotion);
}
passes.add(createEmptyPass("afterModuleMotion"));
// Some optimizations belong outside the loop because running them more
// than once would either have no benefit or be incorrect.
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP));
}
if (options.flowSensitiveInlineVariables) {
passes.add(flowSensitiveInlineVariables);
// After inlining some of the variable uses, some variables are unused.
// Re-run remove unused vars to clean it up.
if (options.removeUnusedVars || options.removeUnusedLocalVars) {
passes.add(removeUnusedVars);
}
}
// Running this pass again is required to have goog.events compile down to
// nothing when compiled on its own.
if (options.smartNameRemoval) {
passes.add(smartNamePass2);
}
if (options.collapseAnonymousFunctions) {
passes.add(collapseAnonymousFunctions);
}
// Move functions before extracting prototype member declarations.
if (options.moveFunctionDeclarations ||
// renamePrefixNamescape relies on moveFunctionDeclarations
// to preserve semantics.
options.renamePrefixNamespace != null) {
passes.add(moveFunctionDeclarations);
}
if (options.anonymousFunctionNaming ==
AnonymousFunctionNamingPolicy.MAPPED) {
passes.add(nameMappedAnonymousFunctions);
}
// The mapped name anonymous function pass makes use of information that
// the extract prototype member declarations pass removes so the former
// happens before the latter.
if (options.extractPrototypeMemberDeclarations != ExtractPrototypeMemberDeclarationsMode.OFF) {
passes.add(extractPrototypeMemberDeclarations);
}
if (options.ambiguateProperties &&
(options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) {
passes.add(ambiguateProperties);
}
if (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED) {
passes.add(renameProperties);
}
// Reserve global names added to the "windows" object.
if (options.reserveRawExports) {
passes.add(gatherRawExports);
}
// This comes after property renaming because quoted property names must
// not be renamed.
if (options.convertToDottedProperties) {
passes.add(convertToDottedProperties);
}
// Property renaming must happen before this pass runs since this
// pass may convert dotted properties into quoted properties. It
// is beneficial to run before alias strings, alias keywords and
// variable renaming.
if (options.rewriteFunctionExpressions) {
passes.add(rewriteFunctionExpressions);
}
// This comes after converting quoted property accesses to dotted property
// accesses in order to avoid aliasing property names.
if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) {
passes.add(aliasStrings);
}
if (options.aliasExternals) {
passes.add(aliasExternals);
}
// Passes after this point can no longer depend on normalized AST
// assumptions.
passes.add(markUnnormalized);
if (options.coalesceVariableNames) {
passes.add(coalesceVariableNames);
// coalesceVariables creates identity assignments and more redundant code
// that can be removed, rerun the peephole optimizations to clean them
// up.
if (options.foldConstants) {
passes.add(peepholeOptimizations);
}
}
if (options.collapseVariableDeclarations) {
passes.add(exploitAssign);
passes.add(collapseVariableDeclarations);
}
// This pass works best after collapseVariableDeclarations.
passes.add(denormalize);
if (options.instrumentationTemplate != null) {
passes.add(instrumentFunctions);
}
if (options.variableRenaming != VariableRenamingPolicy.ALL) {
// If we're leaving some (or all) variables with their old names,
// then we need to undo any of the markers we added for distinguishing
// local variables ("$$1").
passes.add(invertContextualRenaming);
}
if (options.variableRenaming != VariableRenamingPolicy.OFF) {
passes.add(renameVars);
}
// This pass should run after names stop changing.
if (options.processObjectPropertyString) {
passes.add(objectPropertyStringPostprocess);
}
if (options.labelRenaming) {
passes.add(renameLabels);
}
if (options.foldConstants) {
passes.add(latePeepholeOptimizations);
}
if (options.anonymousFunctionNaming ==
AnonymousFunctionNamingPolicy.UNMAPPED) {
passes.add(nameUnmappedAnonymousFunctions);
}
if (protectHiddenSideEffects) {
passes.add(stripSideEffectProtection);
}
if (options.renamePrefixNamespace != null) {
if (!GLOBAL_SYMBOL_NAMESPACE_PATTERN.matcher(
options.renamePrefixNamespace).matches()) {
throw new IllegalArgumentException(
"Illegal character in renamePrefixNamespace name: "
+ options.renamePrefixNamespace);
}
passes.add(rescopeGlobalSymbols);
}
// Safety checks
passes.add(sanityCheckAst);
passes.add(sanityCheckVars);
// Raise to ES6, if allowed
if (options.getLanguageOut().isEs6OrHigher()) {
passes.add(optimizeToEs6);
}
return passes;
}
/** Creates the passes for the main optimization loop. */
private List<PassFactory> getMainOptimizationLoop() {
List<PassFactory> passes = new ArrayList<>();
if (options.inlineGetters) {
passes.add(inlineSimpleMethods);
}
passes.addAll(getCodeRemovingPasses());
if (options.inlineFunctions || options.inlineLocalFunctions) {
passes.add(inlineFunctions);
}
if (options.inlineProperties) {
passes.add(inlineProperties);
}
boolean runOptimizeCalls = options.optimizeCalls
|| options.optimizeParameters
|| options.optimizeReturns;
if (options.removeUnusedVars || options.removeUnusedLocalVars) {
if (options.deadAssignmentElimination) {
passes.add(deadAssignmentsElimination);
}
if (!runOptimizeCalls) {
passes.add(removeUnusedVars);
}
}
if (runOptimizeCalls) {
passes.add(optimizeCallsAndRemoveUnusedVars);
}
assertAllLoopablePasses(passes);
return passes;
}
/** Creates several passes aimed at removing code. */
private List<PassFactory> getCodeRemovingPasses() {
List<PassFactory> passes = new ArrayList<>();
if (options.collapseObjectLiterals) {
passes.add(collapseObjectLiterals);
}
if (options.inlineVariables || options.inlineLocalVariables) {
passes.add(inlineVariables);
} else if (options.inlineConstantVars) {
passes.add(inlineConstants);
}
if (options.foldConstants) {
// These used to be one pass.
passes.add(minimizeExitPoints);
passes.add(peepholeOptimizations);
}
if (options.removeDeadCode) {
passes.add(removeUnreachableCode);
}
if (options.removeUnusedPrototypeProperties) {
passes.add(removeUnusedPrototypeProperties);
}
if (options.removeUnusedClassProperties) {
passes.add(removeUnusedClassProperties);
}
assertAllLoopablePasses(passes);
return passes;
}
/**
* Checks for code that is probably wrong (such as stray expressions).
*/
private final HotSwapPassFactory checkSideEffects =
new HotSwapPassFactory("checkSideEffects", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new CheckSideEffects(compiler,
options.checkSuspiciousCode ? CheckLevel.WARNING : CheckLevel.OFF,
protectHiddenSideEffects);
}
};
/**
* Removes the "protector" functions that were added by CheckSideEffects.
*/
private final PassFactory stripSideEffectProtection =
new PassFactory("stripSideEffectProtection", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CheckSideEffects.StripProtection(compiler);
}
};
/**
* Checks for code that is probably wrong (such as stray expressions).
*/
private final HotSwapPassFactory suspiciousCode =
new HotSwapPassFactory("suspiciousCode", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
List<Callback> sharedCallbacks = new ArrayList<>();
if (options.checkSuspiciousCode) {
sharedCallbacks.add(new CheckSuspiciousCode());
}
if (options.enables(DiagnosticGroups.GLOBAL_THIS)) {
sharedCallbacks.add(new CheckGlobalThis(compiler));
}
if (options.enables(DiagnosticGroups.DEBUGGER_STATEMENT_PRESENT)) {
sharedCallbacks.add(new CheckDebuggerStatement(compiler));
}
return combineChecks(compiler, sharedCallbacks);
}
};
/** Verify that all the passes are one-time passes. */
private static void assertAllOneTimePasses(List<PassFactory> passes) {
for (PassFactory pass : passes) {
Preconditions.checkState(pass.isOneTimePass());
}
}
/** Verify that all the passes are multi-run passes. */
private static void assertAllLoopablePasses(List<PassFactory> passes) {
for (PassFactory pass : passes) {
Preconditions.checkState(!pass.isOneTimePass());
}
}
/**
* Certain checks need to run in a particular order. For example, the PolymerPass
* will not work correctly unless it runs after the goog.provide() processing.
* This enforces those constraints.
* @param checks The list of check passes
*/
private void assertValidOrder(List<PassFactory> checks) {
int polymerIndex = checks.indexOf(polymerPass);
int closureIndex = checks.indexOf(closurePrimitives);
int suspiciousCodeIndex = checks.indexOf(suspiciousCode);
int checkVarsIndex = checks.indexOf(checkVariableReferences);
int googScopeIndex = checks.indexOf(closureGoogScopeAliases);
if (polymerIndex != -1 && closureIndex != -1) {
Preconditions.checkState(polymerIndex > closureIndex,
"The Polymer pass must run after goog.provide processing.");
}
if (polymerIndex != -1 && suspiciousCodeIndex != -1) {
Preconditions.checkState(polymerIndex < suspiciousCodeIndex,
"The Polymer pass must run befor suspiciousCode processing.");
}
if (googScopeIndex != -1) {
Preconditions.checkState(checkVarsIndex != -1,
"goog.scope processing requires variable checking");
Preconditions.checkState(checkVarsIndex < googScopeIndex,
"Variable checking must happen before goog.scope processing.");
}
}
/** Checks that all constructed classes are goog.require()d. */
private final HotSwapPassFactory checkRequires =
new HotSwapPassFactory("checkRequires", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckRequiresForConstructors(compiler);
}
};
/** Makes sure @constructor is paired with goog.provides(). */
private final HotSwapPassFactory checkProvides =
new HotSwapPassFactory("checkProvides", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckProvides(compiler, options.checkProvides);
}
};
private static final DiagnosticType GENERATE_EXPORTS_ERROR =
DiagnosticType.error(
"JSC_GENERATE_EXPORTS_ERROR",
"Exports can only be generated if export symbol/property " +
"functions are set.");
/** Verifies JSDoc annotations are used properly. */
private final PassFactory checkJsDoc = new PassFactory("checkJsDoc", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CheckJSDoc(compiler);
}
};
/** Generates exports for @export annotations. */
private final PassFactory generateExports = new PassFactory("generateExports", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
CodingConvention convention = compiler.getCodingConvention();
if (convention.getExportSymbolFunction() != null &&
convention.getExportPropertyFunction() != null) {
return new GenerateExports(compiler,
options.exportLocalPropertyDefinitions,
convention.getExportSymbolFunction(),
convention.getExportPropertyFunction());
} else {
return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR);
}
}
};
/** Generates exports for functions associated with JsUnit. */
private final PassFactory exportTestFunctions =
new PassFactory("exportTestFunctions", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
CodingConvention convention = compiler.getCodingConvention();
if (convention.getExportSymbolFunction() != null) {
return new ExportTestFunctions(compiler,
convention.getExportSymbolFunction(),
convention.getExportPropertyFunction());
} else {
return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR);
}
}
};
/** Raw exports processing pass. */
private final PassFactory gatherRawExports =
new PassFactory("gatherRawExports", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
final GatherRawExports pass = new GatherRawExports(
compiler);
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
if (exportedNames == null) {
exportedNames = new HashSet<>();
}
exportedNames.addAll(pass.getExportedVariableNames());
}
};
}
};
/** Closure pre-processing pass. */
private final HotSwapPassFactory closurePrimitives =
new HotSwapPassFactory("closurePrimitives", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
maybeInitializePreprocessorSymbolTable(compiler);
final ProcessClosurePrimitives pass = new ProcessClosurePrimitives(
compiler,
preprocessorSymbolTable,
options.brokenClosureRequiresLevel,
options.preserveGoogRequires);
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
exportedNames = pass.getExportedVariableNames();
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
pass.hotSwapScript(scriptRoot, originalRoot);
}
};
}
};
/** Expand jQuery Primitives and Aliases pass. */
private final PassFactory jqueryAliases = new PassFactory("jqueryAliases", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ExpandJqueryAliases(compiler);
}
};
/** Process AngularJS-specific annotations. */
private final HotSwapPassFactory angularPass =
new HotSwapPassFactory("angularPass", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new AngularPass(compiler);
}
};
/**
* The default i18n pass.
* A lot of the options are not configurable, because ReplaceMessages
* has a lot of legacy logic.
*/
private final PassFactory replaceMessages = new PassFactory("replaceMessages", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ReplaceMessages(compiler,
options.messageBundle,
/* warn about message dupes */
true,
/* allow messages with goog.getMsg */
JsMessage.Style.CLOSURE,
/* if we can't find a translation, don't worry about it. */
false);
}
};
private final PassFactory replaceMessagesForChrome =
new PassFactory("replaceMessages", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ReplaceMessagesForChrome(compiler,
new GoogleJsMessageIdGenerator(options.tcProjectId),
/* warn about message dupes */
true,
/* allow messages with goog.getMsg */
JsMessage.Style.CLOSURE);
}
};
/** Applies aliases and inlines goog.scope. */
private final HotSwapPassFactory closureGoogScopeAliases =
new HotSwapPassFactory("closureGoogScopeAliases", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
maybeInitializePreprocessorSymbolTable(compiler);
return new ScopedAliases(
compiler,
preprocessorSymbolTable,
options.getAliasTransformationHandler());
}
};
private final PassFactory es6RuntimeLibrary =
new PassFactory("Es6RuntimeLibrary", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new InjectEs6RuntimeLibrary(compiler);
}
};
private final PassFactory es6RewriteDestructuring =
new PassFactory("Es6RewriteDestructuring", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new Es6RewriteDestructuring(compiler);
}
};
private final HotSwapPassFactory es6RenameVariablesInParamLists =
new HotSwapPassFactory("Es6RenameVariablesInParamLists", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6RenameVariablesInParamLists(compiler);
}
};
private final PassFactory es6RewriteArrowFunction =
new PassFactory("Es6RewriteArrowFunction", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new Es6RewriteArrowFunction(compiler);
}
};
private final HotSwapPassFactory es6SplitVariableDeclarations =
new HotSwapPassFactory("Es6SplitVariableDeclarations", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6SplitVariableDeclarations(compiler);
}
};
private final HotSwapPassFactory es6ConvertSuper =
new HotSwapPassFactory("es6ConvertSuper", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6ConvertSuper(compiler);
}
};
/**
* Does the main ES6 to ES3 conversion.
* There are a few other passes which run before or after this one,
* to convert constructs which are not converted by this pass.
*/
private final HotSwapPassFactory convertEs6ToEs3 =
new HotSwapPassFactory("convertEs6", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6ToEs3Converter(compiler);
}
};
private final HotSwapPassFactory rewriteLetConst =
new HotSwapPassFactory("Es6RewriteLetConst", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6RewriteLetConst(compiler);
}
};
/**
* Desugars ES6_TYPED features into ES6 code.
*/
final HotSwapPassFactory convertEs6TypedToEs6 =
new HotSwapPassFactory("convertEs6Typed", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6TypedToEs6Converter(compiler);
}
};
private final HotSwapPassFactory rewriteGenerators =
new HotSwapPassFactory("rewriteGenerators", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6RewriteGenerators(compiler);
}
};
private final PassFactory convertStaticInheritance =
new PassFactory("Es6StaticInheritance", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new Es6ToEs3ClassSideInheritance(compiler);
}
};
private final PassFactory convertToTypedES6 =
new PassFactory("ConvertToTypedES6", true) {
@Override
CompilerPass create(AbstractCompiler compiler) {
return new JsdocToEs6TypedConverter(compiler);
}
};
private final PassFactory markTranspilationDone = new PassFactory("setLanguageMode", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
LanguageMode langOut = options.getLanguageOut();
compiler.setLanguageMode(langOut.isEs6OrHigher() ? LanguageMode.ECMASCRIPT5 : langOut);
}
};
}
};
/** Applies aliases and inlines goog.scope. */
private final PassFactory declaredGlobalExternsOnWindow =
new PassFactory("declaredGlobalExternsOnWindow", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DeclaredGlobalExternsOnWindow(compiler);
}
};
/** Rewrites goog.defineClass */
private final HotSwapPassFactory closureRewriteClass =
new HotSwapPassFactory("closureRewriteClass", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new ClosureRewriteClass(compiler);
}
};
/** Rewrites goog.module */
private final HotSwapPassFactory closureRewriteModule =
new HotSwapPassFactory("closureRewriteModule", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new ClosureRewriteModule(compiler);
}
};
/** Checks that CSS class names are wrapped in goog.getCssName */
private final PassFactory closureCheckGetCssName =
new PassFactory("closureCheckGetCssName", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CheckMissingGetCssName(
compiler, options.checkMissingGetCssNameLevel,
options.checkMissingGetCssNameBlacklist);
}
};
/**
* Processes goog.getCssName. The cssRenamingMap is used to lookup
* replacement values for the classnames. If null, the raw class names are
* inlined.
*/
private final PassFactory closureReplaceGetCssName =
new PassFactory("closureReplaceGetCssName", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
Map<String, Integer> newCssNames = null;
if (options.gatherCssNames) {
newCssNames = new HashMap<>();
}
ReplaceCssNames pass = new ReplaceCssNames(
compiler,
newCssNames,
options.cssRenamingWhitelist);
pass.process(externs, jsRoot);
cssNames = newCssNames;
}
};
}
};
/**
* Creates synthetic blocks to prevent FoldConstants from moving code
* past markers in the source.
*/
private final PassFactory createSyntheticBlocks =
new PassFactory("createSyntheticBlocks", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CreateSyntheticBlocks(compiler,
options.syntheticBlockStartMarker,
options.syntheticBlockEndMarker);
}
};
private final PassFactory earlyPeepholeOptimizations =
new PassFactory("earlyPeepholeOptimizations", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new PeepholeOptimizationsPass(compiler,
new PeepholeRemoveDeadCode());
}
};
private final PassFactory earlyInlineVariables =
new PassFactory("earlyInlineVariables", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
InlineVariables.Mode mode;
if (options.inlineVariables) {
mode = InlineVariables.Mode.ALL;
} else if (options.inlineLocalVariables) {
mode = InlineVariables.Mode.LOCALS_ONLY;
} else {
throw new IllegalStateException("No variable inlining option set.");
}
return new InlineVariables(compiler, mode, true);
}
};
/** Various peephole optimizations. */
private final PassFactory peepholeOptimizations =
new PassFactory("peepholeOptimizations", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
final boolean late = false;
return new PeepholeOptimizationsPass(compiler,
new PeepholeMinimizeConditions(late),
new PeepholeSubstituteAlternateSyntax(late),
new PeepholeReplaceKnownMethods(late),
new PeepholeRemoveDeadCode(),
new PeepholeFoldConstants(late),
new PeepholeCollectPropertyAssignments());
}
};
/** Same as peepholeOptimizations but aggressively merges code together */
private final PassFactory latePeepholeOptimizations =
new PassFactory("latePeepholeOptimizations", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
final boolean late = true;
return new PeepholeOptimizationsPass(compiler,
new StatementFusion(options.aggressiveFusion),
new PeepholeRemoveDeadCode(),
new PeepholeMinimizeConditions(late),
new PeepholeSubstituteAlternateSyntax(late),
new PeepholeReplaceKnownMethods(late),
new PeepholeFoldConstants(late),
new ReorderConstantExpression());
}
};
/** Checks that all variables are defined. */
private final HotSwapPassFactory checkVars =
new HotSwapPassFactory("checkVars", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new VarCheck(compiler);
}
};
/** Infers constants. */
private final PassFactory inferConsts = new PassFactory("inferConsts", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InferConsts(compiler);
}
};
/** Checks for RegExp references. */
private final PassFactory checkRegExp =
new PassFactory("checkRegExp", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
final CheckRegExp pass = new CheckRegExp(compiler);
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
compiler.setHasRegExpGlobalReferences(
pass.isGlobalRegExpPropertiesUsed());
}
};
}
};
/** Checks that references to variables look reasonable. */
private final HotSwapPassFactory checkVariableReferences =
new HotSwapPassFactory("checkVariableReferences", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new VariableReferenceCheck(compiler);
}
};
/** Pre-process goog.testing.ObjectPropertyString. */
private final PassFactory objectPropertyStringPreprocess =
new PassFactory("ObjectPropertyStringPreprocess", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ObjectPropertyStringPreprocess(compiler);
}
};
/** Creates a typed scope and adds types to the type registry. */
final HotSwapPassFactory resolveTypes =
new HotSwapPassFactory("resolveTypes", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new GlobalTypeResolver(compiler);
}
};
/** Clears the typed scope when we're done. */
private final PassFactory clearTypedScopePass =
new PassFactory("clearTypedScopePass", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ClearTypedScope();
}
};
/** Runs type inference. */
final HotSwapPassFactory inferTypes =
new HotSwapPassFactory("inferTypes", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
Preconditions.checkNotNull(topScope);
Preconditions.checkNotNull(getTypedScopeCreator());
makeTypeInference(compiler).process(externs, root);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
makeTypeInference(compiler).inferAllScopes(scriptRoot);
}
};
}
};
private final PassFactory symbolTableForNewTypeInference =
new PassFactory("GlobalTypeInfo", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new GlobalTypeInfo(compiler);
}
};
private final PassFactory newTypeInference =
new PassFactory("NewTypeInference", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new NewTypeInference(compiler, options.closurePass);
}
};
private final HotSwapPassFactory inferJsDocInfo =
new HotSwapPassFactory("inferJsDocInfo", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
Preconditions.checkNotNull(topScope);
Preconditions.checkNotNull(getTypedScopeCreator());
makeInferJsDocInfo(compiler).process(externs, root);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
makeInferJsDocInfo(compiler).hotSwapScript(scriptRoot, originalRoot);
}
};
}
};
/** Checks type usage */
private final HotSwapPassFactory checkTypes =
new HotSwapPassFactory("checkTypes", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
Preconditions.checkNotNull(topScope);
Preconditions.checkNotNull(getTypedScopeCreator());
TypeCheck check = makeTypeCheck(compiler);
check.process(externs, root);
compiler.getErrorManager().setTypedPercent(check.getTypedPercent());
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
makeTypeCheck(compiler).check(scriptRoot, false);
}
};
}
};
/**
* Checks possible execution paths of the program for problems: missing return
* statements and dead code.
*/
private final HotSwapPassFactory checkControlFlow =
new HotSwapPassFactory("checkControlFlow", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
List<Callback> callbacks = new ArrayList<>();
if (!options.disables(DiagnosticGroups.CHECK_USELESS_CODE)) {
callbacks.add(new CheckUnreachableCode(compiler));
}
if (options.checkMissingReturn.isOn()) {
callbacks.add(
new CheckMissingReturn(compiler, options.checkMissingReturn));
}
return combineChecks(compiler, callbacks);
}
};
/** Checks access controls. Depends on type-inference. */
private final HotSwapPassFactory checkAccessControls =
new HotSwapPassFactory("checkAccessControls", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckAccessControls(
compiler, options.enforceAccessControlCodingConventions);
}
};
private final HotSwapPassFactory lintChecks =
new HotSwapPassFactory("lintChecks", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
ImmutableList.Builder<Callback> callbacks = ImmutableList.<Callback>builder()
.add(new CheckEmptyStatements(compiler))
.add(new CheckEnums(compiler))
.add(new CheckInterfaces(compiler))
.add(new CheckJSDocStyle(compiler))
.add(new CheckNullableReturn(compiler))
.add(new CheckPrototypeProperties(compiler))
.add(new ImplicitNullabilityCheck(compiler));
if (options.closurePass) {
callbacks.add(new CheckRequiresAndProvidesSorted(compiler));
}
return combineChecks(compiler, callbacks.build());
}
};
/** Executes the given callbacks with a {@link CombinedCompilerPass}. */
private static HotSwapCompilerPass combineChecks(AbstractCompiler compiler,
List<Callback> callbacks) {
Preconditions.checkArgument(!callbacks.isEmpty());
return new CombinedCompilerPass(compiler, callbacks);
}
/** A compiler pass that resolves types in the global scope. */
class GlobalTypeResolver implements HotSwapCompilerPass {
private final AbstractCompiler compiler;
GlobalTypeResolver(AbstractCompiler compiler) {
this.compiler = compiler;
}
@Override
public void process(Node externs, Node root) {
if (topScope == null) {
regenerateGlobalTypedScope(compiler, root.getParent());
} else {
compiler.getTypeRegistry().resolveTypesInScope(topScope);
}
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
patchGlobalTypedScope(compiler, scriptRoot);
}
}
/** A compiler pass that clears the global scope. */
class ClearTypedScope implements CompilerPass {
@Override
public void process(Node externs, Node root) {
clearTypedScope();
}
}
/** Checks global name usage. */
private final PassFactory checkGlobalNames =
new PassFactory("checkGlobalNames", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
// Create a global namespace for analysis by check passes.
// Note that this class does all heavy computation lazily,
// so it's OK to create it here.
namespaceForChecks = new GlobalNamespace(compiler, externs, jsRoot);
new CheckGlobalNames(compiler, options.checkGlobalNamesLevel)
.injectNamespace(namespaceForChecks).process(externs, jsRoot);
}
};
}
};
/** Checks that the code is ES5 strict compliant. */
private final PassFactory checkStrictMode =
new PassFactory("checkStrictMode", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new StrictModeCheck(compiler,
!options.checkSymbols); // don't check variables twice
}
};
/** Process goog.tweak.getTweak() calls. */
private final PassFactory processTweaks = new PassFactory("processTweaks", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
new ProcessTweaks(compiler,
options.getTweakProcessing().shouldStrip(),
options.getTweakReplacements()).process(externs, jsRoot);
}
};
}
};
/** Override @define-annotated constants. */
private final PassFactory processDefines = new PassFactory("processDefines", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
HashMap<String, Node> replacements = new HashMap<>();
replacements.putAll(compiler.getDefaultDefineValues());
replacements.putAll(getAdditionalReplacements(options));
replacements.putAll(options.getDefineReplacements());
new ProcessDefines(compiler, ImmutableMap.copyOf(replacements))
.injectNamespace(namespaceForChecks).process(externs, jsRoot);
}
};
}
};
/** Release references to data that is only needed during checks. */
final PassFactory garbageCollectChecks =
new HotSwapPassFactory("garbageCollectChecks", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
// Kill the global namespace so that it can be garbage collected
// after all passes are through with it.
namespaceForChecks = null;
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
process(null, null);
}
};
}
};
/** Checks that all constants are not modified */
private final PassFactory checkConsts = new PassFactory("checkConsts", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ConstCheck(compiler);
}
};
/** Checks that the arguments are constants */
private final PassFactory checkConstParams =
new PassFactory("checkConstParams", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ConstParamCheck(compiler);
}
};
/** Check memory bloat patterns */
private final PassFactory checkEventfulObjectDisposal =
new PassFactory("checkEventfulObjectDisposal", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CheckEventfulObjectDisposal(compiler,
options.checkEventfulObjectDisposalPolicy);
}
};
/** Computes the names of functions for later analysis. */
private final PassFactory computeFunctionNames =
new PassFactory("computeFunctionNames", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return ((functionNames = new FunctionNames(compiler)));
}
};
/** Inserts run-time type assertions for debugging. */
private final PassFactory runtimeTypeCheck =
new PassFactory("runtimeTypeCheck", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RuntimeTypeCheck(compiler,
options.runtimeTypeCheckLogFunction);
}
};
/** Generates unique ids. */
private final PassFactory replaceIdGenerators =
new PassFactory("replaceIdGenerators", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
ReplaceIdGenerators pass =
new ReplaceIdGenerators(
compiler, options.idGenerators, options.generatePseudoNames,
options.idGeneratorsMapSerialized);
pass.process(externs, root);
idGeneratorMap = pass.getSerializedIdMappings();
}
};
}
};
/** Replace strings. */
private final PassFactory replaceStrings = new PassFactory("replaceStrings", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
ReplaceStrings pass = new ReplaceStrings(
compiler,
options.replaceStringsPlaceholderToken,
options.replaceStringsFunctionDescriptions,
options.replaceStringsReservedStrings,
options.replaceStringsInputMap);
pass.process(externs, root);
stringMap = pass.getStringMap();
}
};
}
};
/** Optimizes the "arguments" array. */
private final PassFactory optimizeArgumentsArray =
new PassFactory("optimizeArgumentsArray", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new OptimizeArgumentsArray(compiler);
}
};
/** Remove variables set to goog.abstractMethod. */
private final PassFactory closureCodeRemoval =
new PassFactory("closureCodeRemoval", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ClosureCodeRemoval(compiler, options.removeAbstractMethods,
options.removeClosureAsserts);
}
};
/** Special case optimizations for closure functions. */
private final PassFactory closureOptimizePrimitives =
new PassFactory("closureOptimizePrimitives", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ClosureOptimizePrimitives(compiler);
}
};
/** Puts global symbols into a single object. */
private final PassFactory rescopeGlobalSymbols =
new PassFactory("rescopeGlobalSymbols", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RescopeGlobalSymbols(
compiler,
options.renamePrefixNamespace,
options.renamePrefixNamespaceAssumeCrossModuleNames);
}
};
/** Collapses names in the global scope. */
private final PassFactory collapseProperties =
new PassFactory("collapseProperties", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CollapseProperties(compiler);
}
};
/** Rewrite properties as variables. */
private final PassFactory collapseObjectLiterals =
new PassFactory("collapseObjectLiterals", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineObjectLiterals(
compiler, compiler.getUniqueNameIdSupplier());
}
};
/** Disambiguate property names based on the coding convention. */
private final PassFactory disambiguatePrivateProperties =
new PassFactory("disambiguatePrivateProperties", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DisambiguatePrivateProperties(compiler);
}
};
/** Disambiguate property names based on type information. */
private final PassFactory disambiguateProperties =
new PassFactory("disambiguateProperties", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return DisambiguateProperties.forJSTypeSystem(compiler,
options.propertyInvalidationErrors);
}
};
/**
* Chain calls to functions that return this.
*/
private final PassFactory chainCalls = new PassFactory("chainCalls", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ChainCalls(compiler);
}
};
/**
* Rewrite instance methods as static methods, to make them easier
* to inline.
*/
private final PassFactory devirtualizePrototypeMethods =
new PassFactory("devirtualizePrototypeMethods", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DevirtualizePrototypeMethods(compiler);
}
};
/**
* Optimizes unused function arguments, unused return values, and inlines
* constant parameters. Also runs RemoveUnusedVars.
*/
private final PassFactory optimizeCallsAndRemoveUnusedVars =
new PassFactory("optimizeCalls_and_removeUnusedVars", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
OptimizeCalls passes = new OptimizeCalls(compiler);
if (options.optimizeReturns) {
// Remove unused return values.
passes.addPass(new OptimizeReturns(compiler));
}
if (options.optimizeParameters) {
// Remove all parameters that are constants or unused.
passes.addPass(new OptimizeParameters(compiler));
}
if (options.optimizeCalls) {
boolean removeOnlyLocals = options.removeUnusedLocalVars
&& !options.removeUnusedVars;
boolean preserveAnonymousFunctionNames =
options.anonymousFunctionNaming !=
AnonymousFunctionNamingPolicy.OFF;
passes.addPass(
new RemoveUnusedVars(compiler, !removeOnlyLocals,
preserveAnonymousFunctionNames, true));
}
return passes;
}
};
/**
* Look for function calls that are pure, and annotate them
* that way.
*/
private final PassFactory markPureFunctions =
new PassFactory("markPureFunctions", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new PureFunctionIdentifier.Driver(
compiler, options.debugFunctionSideEffectsPath, false);
}
};
/**
* Look for function calls that have no side effects, and annotate them
* that way.
*/
private final PassFactory markNoSideEffectCalls =
new PassFactory("markNoSideEffectCalls", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new MarkNoSideEffectCalls(compiler);
}
};
/** Inlines variables heuristically. */
private final PassFactory inlineVariables =
new PassFactory("inlineVariables", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
InlineVariables.Mode mode;
if (options.inlineVariables) {
mode = InlineVariables.Mode.ALL;
} else if (options.inlineLocalVariables) {
mode = InlineVariables.Mode.LOCALS_ONLY;
} else {
throw new IllegalStateException("No variable inlining option set.");
}
return new InlineVariables(compiler, mode, true);
}
};
/** Inlines variables that are marked as constants. */
private final PassFactory inlineConstants =
new PassFactory("inlineConstants", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineVariables(
compiler, InlineVariables.Mode.CONSTANTS_ONLY, true);
}
};
/**
* Perform local control flow optimizations.
*/
private final PassFactory minimizeExitPoints =
new PassFactory("minimizeExitPoints", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new MinimizeExitPoints(compiler);
}
};
/**
* Use data flow analysis to remove dead branches.
*/
private final PassFactory removeUnreachableCode =
new PassFactory("removeUnreachableCode", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new UnreachableCodeElimination(compiler, true);
}
};
/**
* Remove prototype properties that do not appear to be used.
*/
private final PassFactory removeUnusedPrototypeProperties =
new PassFactory("removeUnusedPrototypeProperties", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RemoveUnusedPrototypeProperties(
compiler, options.removeUnusedPrototypePropertiesInExterns,
!options.removeUnusedVars);
}
};
/**
* Remove prototype properties that do not appear to be used.
*/
private final PassFactory removeUnusedClassProperties =
new PassFactory("removeUnusedClassProperties", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RemoveUnusedClassProperties(
compiler, options.removeUnusedConstructorProperties);
}
};
/**
* Process smart name processing - removes unused classes and does referencing
* starting with minimum set of names.
*/
private final PassFactory smartNamePass = new PassFactory("smartNamePass", true) {
private boolean hasWrittenFile = false;
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
NameAnalyzer na = new NameAnalyzer(compiler, false);
na.process(externs, root);
String reportPath = options.reportPath;
if (reportPath != null) {
try {
if (hasWrittenFile) {
Files.append(na.getHtmlReport(), new File(reportPath),
UTF_8);
} else {
Files.write(na.getHtmlReport(), new File(reportPath),
UTF_8);
hasWrittenFile = true;
}
} catch (IOException e) {
compiler.report(JSError.make(REPORT_PATH_IO_ERROR, reportPath));
}
}
if (options.smartNameRemoval) {
na.removeUnreferenced();
}
}
};
}
};
/**
* Process smart name processing - removes unused classes and does referencing
* starting with minimum set of names.
*/
private final PassFactory smartNamePass2 = new PassFactory("smartNamePass", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
NameAnalyzer na = new NameAnalyzer(compiler, false);
na.process(externs, root);
na.removeUnreferenced();
}
};
}
};
/** Inlines simple methods, like getters */
private final PassFactory inlineSimpleMethods =
new PassFactory("inlineSimpleMethods", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineSimpleMethods(compiler);
}
};
/** Kills dead assignments. */
private final PassFactory deadAssignmentsElimination =
new PassFactory("deadAssignmentsElimination", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DeadAssignmentsElimination(compiler);
}
};
/** Inlines function calls. */
private final PassFactory inlineFunctions =
new PassFactory("inlineFunctions", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineFunctions(
compiler,
compiler.getUniqueNameIdSupplier(),
options.inlineFunctions,
options.inlineLocalFunctions,
true,
options.assumeStrictThis()
|| options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT,
options.assumeClosuresOnlyCaptureReferences,
options.maxFunctionSizeAfterInlining);
}
};
/** Inlines constant properties. */
private final PassFactory inlineProperties =
new PassFactory("inlineProperties", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineProperties(compiler);
}
};
/** Removes variables that are never used. */
private final PassFactory removeUnusedVars =
new PassFactory("removeUnusedVars", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
boolean removeOnlyLocals = options.removeUnusedLocalVars
&& !options.removeUnusedVars;
boolean preserveAnonymousFunctionNames =
options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF;
return new RemoveUnusedVars(
compiler,
!removeOnlyLocals,
preserveAnonymousFunctionNames,
false);
}
};
/**
* Move global symbols to a deeper common module
*/
private final PassFactory crossModuleCodeMotion =
new PassFactory(Compiler.CROSS_MODULE_CODE_MOTION_NAME, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CrossModuleCodeMotion(
compiler,
compiler.getModuleGraph(),
options.parentModuleCanSeeSymbolsDeclaredInChildren);
}
};
/**
* Move methods to a deeper common module
*/
private final PassFactory crossModuleMethodMotion =
new PassFactory(Compiler.CROSS_MODULE_METHOD_MOTION_NAME, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CrossModuleMethodMotion(
compiler, crossModuleIdGenerator,
// Only move properties in externs if we're not treating
// them as exports.
options.removeUnusedPrototypePropertiesInExterns,
options.crossModuleCodeMotionNoStubMethods);
}
};
/** A data-flow based variable inliner. */
private final PassFactory flowSensitiveInlineVariables =
new PassFactory("flowSensitiveInlineVariables", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new FlowSensitiveInlineVariables(compiler);
}
};
/** Uses register-allocation algorithms to use fewer variables. */
private final PassFactory coalesceVariableNames =
new PassFactory("coalesceVariableNames", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CoalesceVariableNames(compiler, options.generatePseudoNames);
}
};
/**
* Some simple, local collapses (e.g., {@code var x; var y;} becomes
* {@code var x,y;}.
*/
private final PassFactory exploitAssign = new PassFactory("exploitAssign", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new PeepholeOptimizationsPass(compiler,
new ExploitAssigns());
}
};
/**
* Some simple, local collapses (e.g., {@code var x; var y;} becomes
* {@code var x,y;}.
*/
private final PassFactory collapseVariableDeclarations =
new PassFactory("collapseVariableDeclarations", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CollapseVariableDeclarations(compiler);
}
};
/**
* Extracts common sub-expressions.
*/
private final PassFactory extractPrototypeMemberDeclarations =
new PassFactory("extractPrototypeMemberDeclarations", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
Pattern pattern;
switch (options.extractPrototypeMemberDeclarations) {
case USE_GLOBAL_TEMP:
pattern = Pattern.USE_GLOBAL_TEMP;
break;
case USE_IIFE:
pattern = Pattern.USE_IIFE;
break;
default:
throw new IllegalStateException("unexpected");
}
return new ExtractPrototypeMemberDeclarations(
compiler, pattern);
}
};
/** Rewrites common function definitions to be more compact. */
private final PassFactory rewriteFunctionExpressions =
new PassFactory("rewriteFunctionExpressions", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new FunctionRewriter(compiler);
}
};
/** Collapses functions to not use the VAR keyword. */
private final PassFactory collapseAnonymousFunctions =
new PassFactory("collapseAnonymousFunctions", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CollapseAnonymousFunctions(compiler);
}
};
/** Moves function declarations to the top, to simulate actual hoisting. */
private final PassFactory moveFunctionDeclarations =
new PassFactory("moveFunctionDeclarations", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new MoveFunctionDeclarations(compiler);
}
};
private final PassFactory nameUnmappedAnonymousFunctions =
new PassFactory("nameAnonymousFunctions", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new NameAnonymousFunctions(compiler);
}
};
private final PassFactory nameMappedAnonymousFunctions =
new PassFactory("nameAnonymousFunctions", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
NameAnonymousFunctionsMapped naf =
new NameAnonymousFunctionsMapped(
compiler, options.inputAnonymousFunctionNamingMap);
naf.process(externs, root);
anonymousFunctionNameMap = naf.getFunctionMap();
}
};
}
};
/** Alias external symbols. */
private final PassFactory aliasExternals = new PassFactory("aliasExternals", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AliasExternals(compiler, compiler.getModuleGraph(),
options.unaliasableGlobals, options.aliasableGlobals);
}
};
/**
* Alias string literals with global variables, to avoid creating lots of
* transient objects.
*/
private final PassFactory aliasStrings = new PassFactory("aliasStrings", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AliasStrings(
compiler,
compiler.getModuleGraph(),
options.aliasAllStrings ? null : options.aliasableStrings,
options.aliasStringsBlacklist,
options.outputJsStringUsage);
}
};
/** Handling for the ObjectPropertyString primitive. */
private final PassFactory objectPropertyStringPostprocess =
new PassFactory("ObjectPropertyStringPostprocess", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ObjectPropertyStringPostprocess(compiler);
}
};
/**
* Renames properties so that the two properties that never appear on
* the same object get the same name.
*/
private final PassFactory ambiguateProperties =
new PassFactory("ambiguateProperties", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AmbiguateProperties(
compiler, options.anonymousFunctionNaming.getReservedCharacters());
}
};
/**
* Mark the point at which the normalized AST assumptions no longer hold.
*/
private final PassFactory markUnnormalized =
new PassFactory("markUnnormalized", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
compiler.setLifeCycleStage(LifeCycleStage.RAW);
}
};
}
};
/** Denormalize the AST for code generation. */
private final PassFactory denormalize = new PassFactory("denormalize", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new Denormalize(compiler);
}
};
/** Inverting name normalization. */
private final PassFactory invertContextualRenaming =
new PassFactory("invertContextualRenaming", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return MakeDeclaredNamesUnique.getContextualRenameInverter(compiler);
}
};
/**
* Renames properties.
*/
private final PassFactory renameProperties =
new PassFactory("renameProperties", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
Preconditions.checkState(options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED);
final VariableMap prevPropertyMap = options.inputPropertyMap;
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
char[] reservedChars = options.anonymousFunctionNaming.getReservedCharacters();
RenameProperties rprop =
new RenameProperties(
compiler, options.generatePseudoNames, prevPropertyMap, reservedChars);
rprop.process(externs, root);
propertyMap = rprop.getPropertyMap();
}
};
}
};
/** Renames variables. */
private final PassFactory renameVars = new PassFactory("renameVars", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
final VariableMap prevVariableMap = options.inputVariableMap;
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
variableMap = runVariableRenaming(
compiler, prevVariableMap, externs, root);
}
};
}
};
private VariableMap runVariableRenaming(
AbstractCompiler compiler, VariableMap prevVariableMap,
Node externs, Node root) {
char[] reservedChars =
options.anonymousFunctionNaming.getReservedCharacters();
boolean preserveAnonymousFunctionNames =
options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF;
Set<String> reservedNames = new HashSet<>();
if (options.renamePrefixNamespace != null) {
// don't use the prefix name as a global symbol.
reservedNames.add(options.renamePrefixNamespace);
}
if (exportedNames != null) {
reservedNames.addAll(exportedNames);
}
reservedNames.addAll(ParserRunner.getReservedVars());
RenameVars rn = new RenameVars(
compiler,
options.renamePrefix,
options.variableRenaming == VariableRenamingPolicy.LOCAL,
preserveAnonymousFunctionNames,
options.generatePseudoNames,
options.shadowVariables,
options.preferStableNames,
prevVariableMap,
reservedChars,
reservedNames);
rn.process(externs, root);
return rn.getVariableMap();
}
/** Renames labels */
private final PassFactory renameLabels = new PassFactory("renameLabels", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RenameLabels(compiler);
}
};
/** Convert bracket access to dot access */
private final PassFactory convertToDottedProperties =
new PassFactory("convertToDottedProperties", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ConvertToDottedProperties(compiler);
}
};
/** Checks that all variables are defined. */
private final PassFactory sanityCheckAst = new PassFactory("sanityCheckAst", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AstValidator(compiler);
}
};
/** Checks that all variables are defined. */
private final PassFactory sanityCheckVars = new PassFactory("sanityCheckVars", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new VarCheck(compiler, true);
}
};
/** Adds instrumentations according to an instrumentation template. */
private final PassFactory instrumentFunctions =
new PassFactory("instrumentFunctions", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
try {
FileReader templateFile =
new FileReader(options.instrumentationTemplate);
(new InstrumentFunctions(
compiler, functionNames,
options.instrumentationTemplate,
options.appNameStr,
templateFile)).process(externs, root);
} catch (IOException e) {
compiler.report(
JSError.make(AbstractCompiler.READ_ERROR,
options.instrumentationTemplate));
}
}
};
}
};
private final PassFactory instrumentForCodeCoverage =
new PassFactory("instrumentForCodeCoverage", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
// TODO(johnlenz): make global instrumentation an option
return new CoverageInstrumentationPass(
compiler, CoverageReach.CONDITIONAL);
}
};
/** Extern property names gathering pass. */
private final PassFactory gatherExternProperties =
new PassFactory("gatherExternProperties", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new GatherExternProperties(compiler);
}
};
/**
* Create a no-op pass that can only run once. Used to break up loops.
*/
static PassFactory createEmptyPass(String name) {
return new PassFactory(name, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return runInSerial();
}
};
}
/**
* Runs custom passes that are designated to run at a particular time.
*/
private PassFactory getCustomPasses(
final CustomPassExecutionTime executionTime) {
return new PassFactory("runCustomPasses", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return runInSerial(options.customPasses.get(executionTime));
}
};
}
/** Create a compiler pass that runs the given passes in serial. */
private static CompilerPass runInSerial(final CompilerPass ... passes) {
return runInSerial(ImmutableSet.copyOf(passes));
}
/** Create a compiler pass that runs the given passes in serial. */
private static CompilerPass runInSerial(
final Collection<CompilerPass> passes) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
for (CompilerPass pass : passes) {
pass.process(externs, root);
}
}
};
}
@VisibleForTesting
static Map<String, Node> getAdditionalReplacements(
CompilerOptions options) {
Map<String, Node> additionalReplacements = new HashMap<>();
if (options.markAsCompiled || options.closurePass) {
additionalReplacements.put(COMPILED_CONSTANT_NAME, IR.trueNode());
}
if (options.closurePass && options.locale != null) {
additionalReplacements.put(CLOSURE_LOCALE_CONSTANT_NAME,
IR.string(options.locale));
}
return additionalReplacements;
}
private final PassFactory printNameReferenceGraph =
new PassFactory("printNameReferenceGraph", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
NameReferenceGraphConstruction gc =
new NameReferenceGraphConstruction(compiler);
gc.process(externs, jsRoot);
String graphFileName = options.nameReferenceGraphPath;
try {
Files.write(DotFormatter.toDot(gc.getNameReferenceGraph()),
new File(graphFileName),
UTF_8);
} catch (IOException e) {
compiler.report(
JSError.make(
NAME_REF_GRAPH_FILE_ERROR, e.getMessage(), graphFileName));
}
}
};
}
};
private final PassFactory printNameReferenceReport =
new PassFactory("printNameReferenceReport", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
NameReferenceGraphConstruction gc =
new NameReferenceGraphConstruction(compiler);
String reportFileName = options.nameReferenceReportPath;
try {
NameReferenceGraphReport report =
new NameReferenceGraphReport(gc.getNameReferenceGraph());
Files.write(report.getHtmlReport(),
new File(reportFileName),
UTF_8);
} catch (IOException e) {
compiler.report(
JSError.make(
NAME_REF_REPORT_FILE_ERROR,
e.getMessage(),
reportFileName));
}
}
};
}
};
/** Rewrites Polymer({}) */
private final HotSwapPassFactory polymerPass =
new HotSwapPassFactory("polymerPass", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new PolymerPass(compiler);
}
};
/**
* A pass-factory that is good for {@code HotSwapCompilerPass} passes.
*/
abstract static class HotSwapPassFactory extends PassFactory {
HotSwapPassFactory(String name, boolean isOneTimePass) {
super(name, isOneTimePass);
}
@Override
protected abstract HotSwapCompilerPass create(AbstractCompiler compiler);
@Override
HotSwapCompilerPass getHotSwapPass(AbstractCompiler compiler) {
return this.create(compiler);
}
}
private final PassFactory checkConformance =
new PassFactory("checkConformance", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CheckConformance(
compiler, ImmutableList.copyOf(options.getConformanceConfigs()));
}
};
/** Optimizations that output ES6 features. */
private final PassFactory optimizeToEs6 = new PassFactory("optimizeToEs6", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new SubstituteEs6Syntax(compiler);
}
};
}
|
src/com/google/javascript/jscomp/DefaultPassConfig.java
|
/*
* Copyright 2009 The Closure Compiler 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 com.google.javascript.jscomp;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Files;
import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage;
import com.google.javascript.jscomp.CompilerOptions.ExtractPrototypeMemberDeclarationsMode;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.jscomp.CoverageInstrumentationPass.CoverageReach;
import com.google.javascript.jscomp.ExtractPrototypeMemberDeclarations.Pattern;
import com.google.javascript.jscomp.NodeTraversal.Callback;
import com.google.javascript.jscomp.lint.CheckEmptyStatements;
import com.google.javascript.jscomp.lint.CheckEnums;
import com.google.javascript.jscomp.lint.CheckInterfaces;
import com.google.javascript.jscomp.lint.CheckJSDocStyle;
import com.google.javascript.jscomp.lint.CheckNullableReturn;
import com.google.javascript.jscomp.lint.CheckPrototypeProperties;
import com.google.javascript.jscomp.lint.CheckRequiresAndProvidesSorted;
import com.google.javascript.jscomp.parsing.ParserRunner;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Pass factories and meta-data for native JSCompiler passes.
*
* @author nicksantos@google.com (Nick Santos)
*/
// TODO(nicksantos): This needs state for a variety of reasons. Some of it
// is to satisfy the existing API. Some of it is because passes really do
// need to share state in non-trivial ways. This should be audited and
// cleaned up.
public final class DefaultPassConfig extends PassConfig {
/* For the --mark-as-compiled pass */
private static final String COMPILED_CONSTANT_NAME = "COMPILED";
/* Constant name for Closure's locale */
private static final String CLOSURE_LOCALE_CONSTANT_NAME = "goog.LOCALE";
static final DiagnosticType CANNOT_USE_PROTOTYPE_AND_VAR =
DiagnosticType.error("JSC_CANNOT_USE_PROTOTYPE_AND_VAR",
"Rename prototypes and inline variables cannot be used together.");
// Miscellaneous errors.
static final DiagnosticType REPORT_PATH_IO_ERROR =
DiagnosticType.error("JSC_REPORT_PATH_IO_ERROR",
"Error writing compiler report to {0}");
private static final DiagnosticType NAME_REF_GRAPH_FILE_ERROR =
DiagnosticType.error("JSC_NAME_REF_GRAPH_FILE_ERROR",
"Error \"{1}\" writing name reference graph to \"{0}\".");
private static final DiagnosticType NAME_REF_REPORT_FILE_ERROR =
DiagnosticType.error("JSC_NAME_REF_REPORT_FILE_ERROR",
"Error \"{1}\" writing name reference report to \"{0}\".");
private static final java.util.regex.Pattern GLOBAL_SYMBOL_NAMESPACE_PATTERN =
java.util.regex.Pattern.compile("^[a-zA-Z0-9$_]+$");
/**
* A global namespace to share across checking passes.
*/
private GlobalNamespace namespaceForChecks = null;
/**
* A symbol table for registering references that get removed during
* preprocessing.
*/
private PreprocessorSymbolTable preprocessorSymbolTable = null;
/** Names exported by goog.exportSymbol. */
private Set<String> exportedNames = null;
/**
* Ids for cross-module method stubbing, so that each method has
* a unique id.
*/
private CrossModuleMethodMotion.IdGenerator crossModuleIdGenerator =
new CrossModuleMethodMotion.IdGenerator();
/**
* Keys are arguments passed to getCssName() found during compilation; values
* are the number of times the key appeared as an argument to getCssName().
*/
private Map<String, Integer> cssNames = null;
/** The variable renaming map */
private VariableMap variableMap = null;
/** The property renaming map */
private VariableMap propertyMap = null;
/** The naming map for anonymous functions */
private VariableMap anonymousFunctionNameMap = null;
/** Fully qualified function names and globally unique ids */
private FunctionNames functionNames = null;
/** String replacement map */
private VariableMap stringMap = null;
/** Id generator map */
private String idGeneratorMap = null;
/**
* Whether to protect "hidden" side-effects.
* @see CheckSideEffects
*/
private final boolean protectHiddenSideEffects;
public DefaultPassConfig(CompilerOptions options) {
super(options);
// The current approach to protecting "hidden" side-effects is to
// wrap them in a function call that is stripped later, this shouldn't
// be done in IDE mode where AST changes may be unexpected.
protectHiddenSideEffects = options != null &&
options.protectHiddenSideEffects && !options.ideMode;
}
@Override
protected State getIntermediateState() {
return new State(
cssNames == null ? null : new HashMap<>(cssNames),
exportedNames == null ? null :
Collections.unmodifiableSet(exportedNames),
crossModuleIdGenerator, variableMap, propertyMap,
anonymousFunctionNameMap, stringMap, functionNames, idGeneratorMap);
}
@Override
protected void setIntermediateState(State state) {
this.cssNames = state.cssNames == null ? null :
new HashMap<>(state.cssNames);
this.exportedNames = state.exportedNames == null ? null :
new HashSet<>(state.exportedNames);
this.crossModuleIdGenerator = state.crossModuleIdGenerator;
this.variableMap = state.variableMap;
this.propertyMap = state.propertyMap;
this.anonymousFunctionNameMap = state.anonymousFunctionNameMap;
this.stringMap = state.stringMap;
this.functionNames = state.functionNames;
this.idGeneratorMap = state.idGeneratorMap;
}
GlobalNamespace getGlobalNamespace() {
return namespaceForChecks;
}
PreprocessorSymbolTable getPreprocessorSymbolTable() {
return preprocessorSymbolTable;
}
void maybeInitializePreprocessorSymbolTable(AbstractCompiler compiler) {
if (options.ideMode) {
Node root = compiler.getRoot();
if (preprocessorSymbolTable == null ||
preprocessorSymbolTable.getRootNode() != root) {
preprocessorSymbolTable = new PreprocessorSymbolTable(root);
}
}
}
@Override
protected List<PassFactory> getChecks() {
List<PassFactory> checks = new ArrayList<>();
checks.add(createEmptyPass("beforeStandardChecks"));
// Verify JsDoc annotations
checks.add(checkJsDoc);
if (options.getLanguageIn() == LanguageMode.ECMASCRIPT6_TYPED
&& options.getLanguageOut() != LanguageMode.ECMASCRIPT6_TYPED) {
checks.add(convertEs6TypedToEs6);
}
// Early ES6 transpilation.
// Includes ES6 features that are straightforward to transpile.
// We won't handle them natively in the rest of the compiler, so we always
// transpile them, even if the output language is also ES6.
if (options.getLanguageIn().isEs6OrHigher() && !options.skipTranspilationAndCrash) {
checks.add(es6RewriteArrowFunction);
checks.add(es6RenameVariablesInParamLists);
checks.add(es6SplitVariableDeclarations);
checks.add(es6RewriteDestructuring);
}
// goog.module rewrite must happen even if options.skipNonTranspilationPasses is set.
if (options.closurePass) {
checks.add(closureRewriteModule);
}
if (!options.skipNonTranspilationPasses && options.declaredGlobalExternsOnWindow) {
checks.add(declaredGlobalExternsOnWindow);
}
checks.add(checkVariableReferences);
if (!options.skipNonTranspilationPasses && options.closurePass) {
checks.add(closureGoogScopeAliases);
checks.add(closureRewriteClass);
}
if (options.enables(DiagnosticGroups.MISSING_REQUIRE)
|| options.enables(DiagnosticGroups.EXTRA_REQUIRE)) {
checks.add(checkRequires);
}
checks.add(checkSideEffects);
if (options.checkProvides.isOn() || options.enables(DiagnosticGroups.MISSING_PROVIDE)) {
checks.add(checkProvides);
}
if (options.jqueryPass && !options.skipNonTranspilationPasses) {
checks.add(jqueryAliases);
}
if (options.generateExports && !options.skipNonTranspilationPasses) {
checks.add(generateExports);
}
// Late ES6 transpilation.
// Includes ES6 features that are best handled natively by the compiler.
// As we convert more passes to handle these features, we will be moving the transpilation
// later in the compilation, and eventually only transpiling when the output is lower than ES6.
if (options.getLanguageIn().isEs6OrHigher() && !options.skipTranspilationAndCrash) {
checks.add(es6ConvertSuper);
checks.add(convertEs6ToEs3);
checks.add(rewriteLetConst);
checks.add(rewriteGenerators);
checks.add(markTranspilationDone);
}
if (options.raiseToEs6Typed()) {
checks.add(convertToTypedES6);
}
if (options.skipNonTranspilationPasses) {
return checks;
}
if (options.getLanguageIn().isEs6OrHigher()) {
checks.add(es6RuntimeLibrary);
}
checks.add(convertStaticInheritance);
// End of ES6 transpilation passes.
if (options.angularPass) {
checks.add(angularPass);
}
if (options.exportTestFunctions) {
checks.add(exportTestFunctions);
}
if (options.closurePass) {
checks.add(closurePrimitives);
}
// It's important that the PolymerPass run *after* the ClosurePrimitives rewrite and *before*
// the suspicious code checks.
if (options.polymerPass) {
checks.add(polymerPass);
}
if (options.checkSuspiciousCode
|| options.enables(DiagnosticGroups.GLOBAL_THIS)
|| options.enables(DiagnosticGroups.DEBUGGER_STATEMENT_PRESENT)) {
checks.add(suspiciousCode);
}
if (options.closurePass && options.checkMissingGetCssNameLevel.isOn()) {
checks.add(closureCheckGetCssName);
}
if (options.syntheticBlockStartMarker != null) {
// This pass must run before the first fold constants pass.
checks.add(createSyntheticBlocks);
}
checks.add(checkVars);
if (options.inferConsts) {
checks.add(inferConsts);
}
if (options.computeFunctionSideEffects) {
checks.add(checkRegExp);
}
// This pass should run before types are assigned.
if (options.processObjectPropertyString) {
checks.add(objectPropertyStringPreprocess);
}
checks.add(createEmptyPass("beforeTypeChecking"));
if (options.useNewTypeInference) {
checks.add(symbolTableForNewTypeInference);
checks.add(newTypeInference);
}
if (options.checkTypes || options.inferTypes) {
checks.add(resolveTypes);
checks.add(inferTypes);
if (options.checkTypes) {
checks.add(checkTypes);
} else {
checks.add(inferJsDocInfo);
}
// We assume that only IDE-mode clients will try to query the
// typed scope creator after the compile job.
if (!options.ideMode) {
checks.add(clearTypedScopePass);
}
}
if (!options.disables(DiagnosticGroups.CHECK_USELESS_CODE) ||
options.checkMissingReturn.isOn()) {
checks.add(checkControlFlow);
}
// CheckAccessControls only works if check types is on.
if (options.checkTypes &&
(!options.disables(DiagnosticGroups.ACCESS_CONTROLS)
|| options.enables(DiagnosticGroups.CONSTANT_PROPERTY))) {
checks.add(checkAccessControls);
}
// Lint checks must be run after typechecking.
if (options.enables(DiagnosticGroups.LINT_CHECKS)) {
checks.add(lintChecks);
}
if (options.checkEventfulObjectDisposalPolicy !=
CheckEventfulObjectDisposal.DisposalCheckingPolicy.OFF) {
checks.add(checkEventfulObjectDisposal);
}
if (options.checkGlobalNamesLevel.isOn()) {
checks.add(checkGlobalNames);
}
if (options.enables(DiagnosticGroups.ES5_STRICT)) {
checks.add(checkStrictMode);
}
if (!options.getConformanceConfigs().isEmpty()) {
checks.add(checkConformance);
}
// Replace 'goog.getCssName' before processing defines but after the
// other checks have been done.
if (options.closurePass) {
checks.add(closureReplaceGetCssName);
}
// i18n
// If you want to customize the compiler to use a different i18n pass,
// you can create a PassConfig that calls replacePassFactory
// to replace this.
if (options.replaceMessagesWithChromeI18n) {
checks.add(replaceMessagesForChrome);
} else if (options.messageBundle != null) {
checks.add(replaceMessages);
}
if (options.getTweakProcessing().isOn()) {
checks.add(processTweaks);
}
// Defines in code always need to be processed.
checks.add(processDefines);
if (options.instrumentationTemplate != null ||
options.recordFunctionInformation) {
checks.add(computeFunctionNames);
}
if (options.nameReferenceGraphPath != null &&
!options.nameReferenceGraphPath.isEmpty()) {
checks.add(printNameReferenceGraph);
}
if (options.nameReferenceReportPath != null &&
!options.nameReferenceReportPath.isEmpty()) {
checks.add(printNameReferenceReport);
}
checks.add(createEmptyPass("afterStandardChecks"));
assertAllOneTimePasses(checks);
assertValidOrder(checks);
return checks;
}
@Override
protected List<PassFactory> getOptimizations() {
List<PassFactory> passes = new ArrayList<>();
if (options.skipNonTranspilationPasses) {
return passes;
}
// Gather property names in externs so they can be queried by the
// optimising passes.
passes.add(gatherExternProperties);
passes.add(garbageCollectChecks);
// TODO(nicksantos): The order of these passes makes no sense, and needs
// to be re-arranged.
if (options.instrumentForCoverage) {
passes.add(instrumentForCodeCoverage);
}
if (options.runtimeTypeCheck) {
passes.add(runtimeTypeCheck);
}
passes.add(createEmptyPass("beforeStandardOptimizations"));
if (options.replaceIdGenerators) {
passes.add(replaceIdGenerators);
}
// Optimizes references to the arguments variable.
if (options.optimizeArgumentsArray) {
passes.add(optimizeArgumentsArray);
}
// Abstract method removal works best on minimally modified code, and also
// only needs to run once.
if (options.closurePass &&
(options.removeAbstractMethods || options.removeClosureAsserts)) {
passes.add(closureCodeRemoval);
}
// Property disambiguation should only run once and needs to be done
// soon after type checking, both so that it can make use of type
// information and so that other passes can take advantage of the renamed
// properties.
if (options.disambiguatePrivateProperties) {
passes.add(disambiguatePrivateProperties);
}
// Collapsing properties can undo constant inlining, so we do this before
// the main optimization loop.
if (options.collapseProperties) {
passes.add(collapseProperties);
}
if (options.inferConsts) {
passes.add(inferConsts);
}
// Running this pass before disambiguate properties allow the removing
// unused methods that share the same name as methods called from unused
// code.
if (options.extraSmartNameRemoval && options.smartNameRemoval) {
// These passes remove code that is dead because of define flags.
// If the dead code is weakly typed, running these passes before property
// disambiguation results in more code removal.
// The passes are one-time on purpose. (The later runs are loopable.)
if (options.foldConstants &&
(options.inlineVariables || options.inlineLocalVariables)) {
passes.add(earlyInlineVariables);
passes.add(earlyPeepholeOptimizations);
}
passes.add(smartNamePass);
}
// Property disambiguation should only run once and needs to be done
// soon after type checking, both so that it can make use of type
// information and so that other passes can take advantage of the renamed
// properties.
if (options.disambiguateProperties) {
passes.add(disambiguateProperties);
}
if (options.computeFunctionSideEffects) {
passes.add(markPureFunctions);
} else if (options.markNoSideEffectCalls) {
// TODO(user) The properties that this pass adds to CALL and NEW
// AST nodes increase the AST's in-memory size. Given that we are
// already running close to our memory limits, we could run into
// trouble if we end up using the @nosideeffects annotation a lot
// or compute @nosideeffects annotations by looking at function
// bodies. It should be easy to propagate @nosideeffects
// annotations as part of passes that depend on this property and
// store the result outside the AST (which would allow garbage
// collection once the pass is done).
passes.add(markNoSideEffectCalls);
}
if (options.chainCalls) {
passes.add(chainCalls);
}
// Constant checking must be done after property collapsing because
// property collapsing can introduce new constants (e.g. enum values).
// TODO(johnlenz): make checkConsts namespace aware so it can be run
// as during the checks phase.
passes.add(checkConsts);
// Detects whether invocations of the method goog.string.Const.from are done
// with an argument which is a string literal.
passes.add(checkConstParams);
assertAllOneTimePasses(passes);
if (options.smartNameRemoval || options.reportPath != null) {
passes.addAll(getCodeRemovingPasses());
passes.add(smartNamePass);
}
// This needs to come after the inline constants pass, which is run within
// the code removing passes.
if (options.closurePass) {
passes.add(closureOptimizePrimitives);
}
// ReplaceStrings runs after CollapseProperties in order to simplify
// pulling in values of constants defined in enums structures. It also runs
// after disambiguate properties and smart name removal so that it can
// correctly identify logging types and can replace references to string
// expressions.
if (!options.replaceStringsFunctionDescriptions.isEmpty()) {
passes.add(replaceStrings);
}
// TODO(user): This forces a first crack at crossModuleCodeMotion
// before devirtualization. Once certain functions are devirtualized,
// it confuses crossModuleCodeMotion ability to recognized that
// it is recursive.
// TODO(user): This is meant for a temporary quick win.
// In the future, we might want to improve our analysis in
// CrossModuleCodeMotion so we don't need to do this.
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
// Method devirtualization benefits from property disambiguation so
// it should run after that pass but before passes that do
// optimizations based on global names (like cross module code motion
// and inline functions). Smart Name Removal does better if run before
// this pass.
if (options.devirtualizePrototypeMethods) {
passes.add(devirtualizePrototypeMethods);
}
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP));
}
passes.add(createEmptyPass("beforeMainOptimizations"));
passes.addAll(getMainOptimizationLoop());
passes.add(createEmptyPass("beforeModuleMotion"));
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
if (options.crossModuleMethodMotion) {
passes.add(crossModuleMethodMotion);
}
passes.add(createEmptyPass("afterModuleMotion"));
// Some optimizations belong outside the loop because running them more
// than once would either have no benefit or be incorrect.
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP));
}
if (options.flowSensitiveInlineVariables) {
passes.add(flowSensitiveInlineVariables);
// After inlining some of the variable uses, some variables are unused.
// Re-run remove unused vars to clean it up.
if (options.removeUnusedVars || options.removeUnusedLocalVars) {
passes.add(removeUnusedVars);
}
}
// Running this pass again is required to have goog.events compile down to
// nothing when compiled on its own.
if (options.smartNameRemoval) {
passes.add(smartNamePass2);
}
if (options.collapseAnonymousFunctions) {
passes.add(collapseAnonymousFunctions);
}
// Move functions before extracting prototype member declarations.
if (options.moveFunctionDeclarations ||
// renamePrefixNamescape relies on moveFunctionDeclarations
// to preserve semantics.
options.renamePrefixNamespace != null) {
passes.add(moveFunctionDeclarations);
}
if (options.anonymousFunctionNaming ==
AnonymousFunctionNamingPolicy.MAPPED) {
passes.add(nameMappedAnonymousFunctions);
}
// The mapped name anonymous function pass makes use of information that
// the extract prototype member declarations pass removes so the former
// happens before the latter.
if (options.extractPrototypeMemberDeclarations != ExtractPrototypeMemberDeclarationsMode.OFF) {
passes.add(extractPrototypeMemberDeclarations);
}
if (options.ambiguateProperties &&
(options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) {
passes.add(ambiguateProperties);
}
if (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED) {
passes.add(renameProperties);
}
// Reserve global names added to the "windows" object.
if (options.reserveRawExports) {
passes.add(gatherRawExports);
}
// This comes after property renaming because quoted property names must
// not be renamed.
if (options.convertToDottedProperties) {
passes.add(convertToDottedProperties);
}
// Property renaming must happen before this pass runs since this
// pass may convert dotted properties into quoted properties. It
// is beneficial to run before alias strings, alias keywords and
// variable renaming.
if (options.rewriteFunctionExpressions) {
passes.add(rewriteFunctionExpressions);
}
// This comes after converting quoted property accesses to dotted property
// accesses in order to avoid aliasing property names.
if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) {
passes.add(aliasStrings);
}
if (options.aliasExternals) {
passes.add(aliasExternals);
}
// Passes after this point can no longer depend on normalized AST
// assumptions.
passes.add(markUnnormalized);
if (options.coalesceVariableNames) {
passes.add(coalesceVariableNames);
// coalesceVariables creates identity assignments and more redundant code
// that can be removed, rerun the peephole optimizations to clean them
// up.
if (options.foldConstants) {
passes.add(peepholeOptimizations);
}
}
if (options.collapseVariableDeclarations) {
passes.add(exploitAssign);
passes.add(collapseVariableDeclarations);
}
// This pass works best after collapseVariableDeclarations.
passes.add(denormalize);
if (options.instrumentationTemplate != null) {
passes.add(instrumentFunctions);
}
if (options.variableRenaming != VariableRenamingPolicy.ALL) {
// If we're leaving some (or all) variables with their old names,
// then we need to undo any of the markers we added for distinguishing
// local variables ("$$1").
passes.add(invertContextualRenaming);
}
if (options.variableRenaming != VariableRenamingPolicy.OFF) {
passes.add(renameVars);
}
// This pass should run after names stop changing.
if (options.processObjectPropertyString) {
passes.add(objectPropertyStringPostprocess);
}
if (options.labelRenaming) {
passes.add(renameLabels);
}
if (options.foldConstants) {
passes.add(latePeepholeOptimizations);
}
if (options.anonymousFunctionNaming ==
AnonymousFunctionNamingPolicy.UNMAPPED) {
passes.add(nameUnmappedAnonymousFunctions);
}
if (protectHiddenSideEffects) {
passes.add(stripSideEffectProtection);
}
if (options.renamePrefixNamespace != null) {
if (!GLOBAL_SYMBOL_NAMESPACE_PATTERN.matcher(
options.renamePrefixNamespace).matches()) {
throw new IllegalArgumentException(
"Illegal character in renamePrefixNamespace name: "
+ options.renamePrefixNamespace);
}
passes.add(rescopeGlobalSymbols);
}
// Safety checks
passes.add(sanityCheckAst);
passes.add(sanityCheckVars);
// Raise to ES6, if allowed
if (options.getLanguageOut().isEs6OrHigher()) {
passes.add(optimizeToEs6);
}
return passes;
}
/** Creates the passes for the main optimization loop. */
private List<PassFactory> getMainOptimizationLoop() {
List<PassFactory> passes = new ArrayList<>();
if (options.inlineGetters) {
passes.add(inlineSimpleMethods);
}
passes.addAll(getCodeRemovingPasses());
if (options.inlineFunctions || options.inlineLocalFunctions) {
passes.add(inlineFunctions);
}
if (options.inlineProperties) {
passes.add(inlineProperties);
}
boolean runOptimizeCalls = options.optimizeCalls
|| options.optimizeParameters
|| options.optimizeReturns;
if (options.removeUnusedVars || options.removeUnusedLocalVars) {
if (options.deadAssignmentElimination) {
passes.add(deadAssignmentsElimination);
}
if (!runOptimizeCalls) {
passes.add(removeUnusedVars);
}
}
if (runOptimizeCalls) {
passes.add(optimizeCallsAndRemoveUnusedVars);
}
assertAllLoopablePasses(passes);
return passes;
}
/** Creates several passes aimed at removing code. */
private List<PassFactory> getCodeRemovingPasses() {
List<PassFactory> passes = new ArrayList<>();
if (options.collapseObjectLiterals) {
passes.add(collapseObjectLiterals);
}
if (options.inlineVariables || options.inlineLocalVariables) {
passes.add(inlineVariables);
} else if (options.inlineConstantVars) {
passes.add(inlineConstants);
}
if (options.foldConstants) {
// These used to be one pass.
passes.add(minimizeExitPoints);
passes.add(peepholeOptimizations);
}
if (options.removeDeadCode) {
passes.add(removeUnreachableCode);
}
if (options.removeUnusedPrototypeProperties) {
passes.add(removeUnusedPrototypeProperties);
}
if (options.removeUnusedClassProperties) {
passes.add(removeUnusedClassProperties);
}
assertAllLoopablePasses(passes);
return passes;
}
/**
* Checks for code that is probably wrong (such as stray expressions).
*/
private final HotSwapPassFactory checkSideEffects =
new HotSwapPassFactory("checkSideEffects", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new CheckSideEffects(compiler,
options.checkSuspiciousCode ? CheckLevel.WARNING : CheckLevel.OFF,
protectHiddenSideEffects);
}
};
/**
* Removes the "protector" functions that were added by CheckSideEffects.
*/
private final PassFactory stripSideEffectProtection =
new PassFactory("stripSideEffectProtection", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CheckSideEffects.StripProtection(compiler);
}
};
/**
* Checks for code that is probably wrong (such as stray expressions).
*/
private final HotSwapPassFactory suspiciousCode =
new HotSwapPassFactory("suspiciousCode", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
List<Callback> sharedCallbacks = new ArrayList<>();
if (options.checkSuspiciousCode) {
sharedCallbacks.add(new CheckSuspiciousCode());
}
if (options.enables(DiagnosticGroups.GLOBAL_THIS)) {
sharedCallbacks.add(new CheckGlobalThis(compiler));
}
if (options.enables(DiagnosticGroups.DEBUGGER_STATEMENT_PRESENT)) {
sharedCallbacks.add(new CheckDebuggerStatement(compiler));
}
return combineChecks(compiler, sharedCallbacks);
}
};
/** Verify that all the passes are one-time passes. */
private static void assertAllOneTimePasses(List<PassFactory> passes) {
for (PassFactory pass : passes) {
Preconditions.checkState(pass.isOneTimePass());
}
}
/** Verify that all the passes are multi-run passes. */
private static void assertAllLoopablePasses(List<PassFactory> passes) {
for (PassFactory pass : passes) {
Preconditions.checkState(!pass.isOneTimePass());
}
}
/**
* Certain checks need to run in a particular order. For example, the PolymerPass
* will not work correctly unless it runs after the goog.provide() processing.
* This enforces those constraints.
* @param checks The list of check passes
*/
private void assertValidOrder(List<PassFactory> checks) {
int polymerIndex = checks.indexOf(polymerPass);
int closureIndex = checks.indexOf(closurePrimitives);
int suspiciousCodeIndex = checks.indexOf(suspiciousCode);
int checkVarsIndex = checks.indexOf(checkVariableReferences);
int googScopeIndex = checks.indexOf(closureGoogScopeAliases);
if (polymerIndex != -1 && closureIndex != -1) {
Preconditions.checkState(polymerIndex > closureIndex,
"The Polymer pass must run after goog.provide processing.");
}
if (polymerIndex != -1 && suspiciousCodeIndex != -1) {
Preconditions.checkState(polymerIndex < suspiciousCodeIndex,
"The Polymer pass must run befor suspiciousCode processing.");
}
if (googScopeIndex != -1) {
Preconditions.checkState(checkVarsIndex != -1,
"goog.scope processing requires variable checking");
Preconditions.checkState(checkVarsIndex < googScopeIndex,
"Variable checking must happen before goog.scope processing.");
}
}
/** Checks that all constructed classes are goog.require()d. */
private final HotSwapPassFactory checkRequires =
new HotSwapPassFactory("checkRequires", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckRequiresForConstructors(compiler);
}
};
/** Makes sure @constructor is paired with goog.provides(). */
private final HotSwapPassFactory checkProvides =
new HotSwapPassFactory("checkProvides", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckProvides(compiler, options.checkProvides);
}
};
private static final DiagnosticType GENERATE_EXPORTS_ERROR =
DiagnosticType.error(
"JSC_GENERATE_EXPORTS_ERROR",
"Exports can only be generated if export symbol/property " +
"functions are set.");
/** Verifies JSDoc annotations are used properly. */
private final PassFactory checkJsDoc = new PassFactory("checkJsDoc", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CheckJSDoc(compiler);
}
};
/** Generates exports for @export annotations. */
private final PassFactory generateExports = new PassFactory("generateExports", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
CodingConvention convention = compiler.getCodingConvention();
if (convention.getExportSymbolFunction() != null &&
convention.getExportPropertyFunction() != null) {
return new GenerateExports(compiler,
options.exportLocalPropertyDefinitions,
convention.getExportSymbolFunction(),
convention.getExportPropertyFunction());
} else {
return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR);
}
}
};
/** Generates exports for functions associated with JsUnit. */
private final PassFactory exportTestFunctions =
new PassFactory("exportTestFunctions", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
CodingConvention convention = compiler.getCodingConvention();
if (convention.getExportSymbolFunction() != null) {
return new ExportTestFunctions(compiler,
convention.getExportSymbolFunction(),
convention.getExportPropertyFunction());
} else {
return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR);
}
}
};
/** Raw exports processing pass. */
private final PassFactory gatherRawExports =
new PassFactory("gatherRawExports", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
final GatherRawExports pass = new GatherRawExports(
compiler);
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
if (exportedNames == null) {
exportedNames = new HashSet<>();
}
exportedNames.addAll(pass.getExportedVariableNames());
}
};
}
};
/** Closure pre-processing pass. */
private final HotSwapPassFactory closurePrimitives =
new HotSwapPassFactory("closurePrimitives", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
maybeInitializePreprocessorSymbolTable(compiler);
final ProcessClosurePrimitives pass = new ProcessClosurePrimitives(
compiler,
preprocessorSymbolTable,
options.brokenClosureRequiresLevel,
options.preserveGoogRequires);
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
exportedNames = pass.getExportedVariableNames();
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
pass.hotSwapScript(scriptRoot, originalRoot);
}
};
}
};
/** Expand jQuery Primitives and Aliases pass. */
private final PassFactory jqueryAliases = new PassFactory("jqueryAliases", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ExpandJqueryAliases(compiler);
}
};
/** Process AngularJS-specific annotations. */
private final HotSwapPassFactory angularPass =
new HotSwapPassFactory("angularPass", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new AngularPass(compiler);
}
};
/**
* The default i18n pass.
* A lot of the options are not configurable, because ReplaceMessages
* has a lot of legacy logic.
*/
private final PassFactory replaceMessages = new PassFactory("replaceMessages", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ReplaceMessages(compiler,
options.messageBundle,
/* warn about message dupes */
true,
/* allow messages with goog.getMsg */
JsMessage.Style.CLOSURE,
/* if we can't find a translation, don't worry about it. */
false);
}
};
private final PassFactory replaceMessagesForChrome =
new PassFactory("replaceMessages", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ReplaceMessagesForChrome(compiler,
new GoogleJsMessageIdGenerator(options.tcProjectId),
/* warn about message dupes */
true,
/* allow messages with goog.getMsg */
JsMessage.Style.CLOSURE);
}
};
/** Applies aliases and inlines goog.scope. */
private final HotSwapPassFactory closureGoogScopeAliases =
new HotSwapPassFactory("closureGoogScopeAliases", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
maybeInitializePreprocessorSymbolTable(compiler);
return new ScopedAliases(
compiler,
preprocessorSymbolTable,
options.getAliasTransformationHandler());
}
};
private final PassFactory es6RuntimeLibrary =
new PassFactory("Es6RuntimeLibrary", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new InjectEs6RuntimeLibrary(compiler);
}
};
private final PassFactory es6RewriteDestructuring =
new PassFactory("Es6RewriteDestructuring", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new Es6RewriteDestructuring(compiler);
}
};
private final HotSwapPassFactory es6RenameVariablesInParamLists =
new HotSwapPassFactory("Es6RenameVariablesInParamLists", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6RenameVariablesInParamLists(compiler);
}
};
private final PassFactory es6RewriteArrowFunction =
new PassFactory("Es6RewriteArrowFunction", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new Es6RewriteArrowFunction(compiler);
}
};
private final HotSwapPassFactory es6SplitVariableDeclarations =
new HotSwapPassFactory("Es6SplitVariableDeclarations", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6SplitVariableDeclarations(compiler);
}
};
private final HotSwapPassFactory es6ConvertSuper =
new HotSwapPassFactory("es6ConvertSuper", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6ConvertSuper(compiler);
}
};
/**
* Does the main ES6 to ES3 conversion.
* There are a few other passes which run before or after this one,
* to convert constructs which are not converted by this pass.
*/
private final HotSwapPassFactory convertEs6ToEs3 =
new HotSwapPassFactory("convertEs6", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6ToEs3Converter(compiler);
}
};
private final HotSwapPassFactory rewriteLetConst =
new HotSwapPassFactory("Es6RewriteLetConst", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6RewriteLetConst(compiler);
}
};
/**
* Desugars ES6_TYPED features into ES6 code.
*/
final HotSwapPassFactory convertEs6TypedToEs6 =
new HotSwapPassFactory("convertEs6Typed", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6TypedToEs6Converter(compiler);
}
};
private final HotSwapPassFactory rewriteGenerators =
new HotSwapPassFactory("rewriteGenerators", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new Es6RewriteGenerators(compiler);
}
};
private final PassFactory convertStaticInheritance =
new PassFactory("Es6StaticInheritance", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new Es6ToEs3ClassSideInheritance(compiler);
}
};
private final PassFactory convertToTypedES6 =
new PassFactory("ConvertToTypedES6", true) {
@Override
CompilerPass create(AbstractCompiler compiler) {
return new JsdocToEs6TypedConverter(compiler);
}
};
private final PassFactory markTranspilationDone = new PassFactory("setLanguageMode", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
LanguageMode langOut = options.getLanguageOut();
compiler.setLanguageMode(langOut.isEs6OrHigher() ? LanguageMode.ECMASCRIPT5 : langOut);
}
};
}
};
/** Applies aliases and inlines goog.scope. */
private final PassFactory declaredGlobalExternsOnWindow =
new PassFactory("declaredGlobalExternsOnWindow", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DeclaredGlobalExternsOnWindow(compiler);
}
};
/** Rewrites goog.defineClass */
private final HotSwapPassFactory closureRewriteClass =
new HotSwapPassFactory("closureRewriteClass", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new ClosureRewriteClass(compiler);
}
};
/** Rewrites goog.module */
private final HotSwapPassFactory closureRewriteModule =
new HotSwapPassFactory("closureRewriteModule", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new ClosureRewriteModule(compiler);
}
};
/** Checks that CSS class names are wrapped in goog.getCssName */
private final PassFactory closureCheckGetCssName =
new PassFactory("closureCheckGetCssName", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CheckMissingGetCssName(
compiler, options.checkMissingGetCssNameLevel,
options.checkMissingGetCssNameBlacklist);
}
};
/**
* Processes goog.getCssName. The cssRenamingMap is used to lookup
* replacement values for the classnames. If null, the raw class names are
* inlined.
*/
private final PassFactory closureReplaceGetCssName =
new PassFactory("closureReplaceGetCssName", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
Map<String, Integer> newCssNames = null;
if (options.gatherCssNames) {
newCssNames = new HashMap<>();
}
ReplaceCssNames pass = new ReplaceCssNames(
compiler,
newCssNames,
options.cssRenamingWhitelist);
pass.process(externs, jsRoot);
cssNames = newCssNames;
}
};
}
};
/**
* Creates synthetic blocks to prevent FoldConstants from moving code
* past markers in the source.
*/
private final PassFactory createSyntheticBlocks =
new PassFactory("createSyntheticBlocks", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CreateSyntheticBlocks(compiler,
options.syntheticBlockStartMarker,
options.syntheticBlockEndMarker);
}
};
private final PassFactory earlyPeepholeOptimizations =
new PassFactory("earlyPeepholeOptimizations", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new PeepholeOptimizationsPass(compiler,
new PeepholeRemoveDeadCode());
}
};
private final PassFactory earlyInlineVariables =
new PassFactory("earlyInlineVariables", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
InlineVariables.Mode mode;
if (options.inlineVariables) {
mode = InlineVariables.Mode.ALL;
} else if (options.inlineLocalVariables) {
mode = InlineVariables.Mode.LOCALS_ONLY;
} else {
throw new IllegalStateException("No variable inlining option set.");
}
return new InlineVariables(compiler, mode, true);
}
};
/** Various peephole optimizations. */
private final PassFactory peepholeOptimizations =
new PassFactory("peepholeOptimizations", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
final boolean late = false;
return new PeepholeOptimizationsPass(compiler,
new PeepholeMinimizeConditions(late),
new PeepholeSubstituteAlternateSyntax(late),
new PeepholeReplaceKnownMethods(late),
new PeepholeRemoveDeadCode(),
new PeepholeFoldConstants(late),
new PeepholeCollectPropertyAssignments());
}
};
/** Same as peepholeOptimizations but aggressively merges code together */
private final PassFactory latePeepholeOptimizations =
new PassFactory("latePeepholeOptimizations", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
final boolean late = true;
return new PeepholeOptimizationsPass(compiler,
new StatementFusion(options.aggressiveFusion),
new PeepholeRemoveDeadCode(),
new PeepholeMinimizeConditions(late),
new PeepholeSubstituteAlternateSyntax(late),
new PeepholeReplaceKnownMethods(late),
new PeepholeFoldConstants(late),
new ReorderConstantExpression());
}
};
/** Checks that all variables are defined. */
private final HotSwapPassFactory checkVars =
new HotSwapPassFactory("checkVars", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new VarCheck(compiler);
}
};
/** Infers constants. */
private final PassFactory inferConsts = new PassFactory("inferConsts", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InferConsts(compiler);
}
};
/** Checks for RegExp references. */
private final PassFactory checkRegExp =
new PassFactory("checkRegExp", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
final CheckRegExp pass = new CheckRegExp(compiler);
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
compiler.setHasRegExpGlobalReferences(
pass.isGlobalRegExpPropertiesUsed());
}
};
}
};
/** Checks that references to variables look reasonable. */
private final HotSwapPassFactory checkVariableReferences =
new HotSwapPassFactory("checkVariableReferences", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new VariableReferenceCheck(compiler);
}
};
/** Pre-process goog.testing.ObjectPropertyString. */
private final PassFactory objectPropertyStringPreprocess =
new PassFactory("ObjectPropertyStringPreprocess", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ObjectPropertyStringPreprocess(compiler);
}
};
/** Creates a typed scope and adds types to the type registry. */
final HotSwapPassFactory resolveTypes =
new HotSwapPassFactory("resolveTypes", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new GlobalTypeResolver(compiler);
}
};
/** Clears the typed scope when we're done. */
private final PassFactory clearTypedScopePass =
new PassFactory("clearTypedScopePass", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ClearTypedScope();
}
};
/** Runs type inference. */
final HotSwapPassFactory inferTypes =
new HotSwapPassFactory("inferTypes", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
Preconditions.checkNotNull(topScope);
Preconditions.checkNotNull(getTypedScopeCreator());
makeTypeInference(compiler).process(externs, root);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
makeTypeInference(compiler).inferAllScopes(scriptRoot);
}
};
}
};
private final PassFactory symbolTableForNewTypeInference =
new PassFactory("GlobalTypeInfo", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new GlobalTypeInfo(compiler);
}
};
private final PassFactory newTypeInference =
new PassFactory("NewTypeInference", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new NewTypeInference(compiler, options.closurePass);
}
};
private final HotSwapPassFactory inferJsDocInfo =
new HotSwapPassFactory("inferJsDocInfo", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
Preconditions.checkNotNull(topScope);
Preconditions.checkNotNull(getTypedScopeCreator());
makeInferJsDocInfo(compiler).process(externs, root);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
makeInferJsDocInfo(compiler).hotSwapScript(scriptRoot, originalRoot);
}
};
}
};
/** Checks type usage */
private final HotSwapPassFactory checkTypes =
new HotSwapPassFactory("checkTypes", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node root) {
Preconditions.checkNotNull(topScope);
Preconditions.checkNotNull(getTypedScopeCreator());
TypeCheck check = makeTypeCheck(compiler);
check.process(externs, root);
compiler.getErrorManager().setTypedPercent(check.getTypedPercent());
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
makeTypeCheck(compiler).check(scriptRoot, false);
}
};
}
};
/**
* Checks possible execution paths of the program for problems: missing return
* statements and dead code.
*/
private final HotSwapPassFactory checkControlFlow =
new HotSwapPassFactory("checkControlFlow", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
List<Callback> callbacks = new ArrayList<>();
if (!options.disables(DiagnosticGroups.CHECK_USELESS_CODE)) {
callbacks.add(new CheckUnreachableCode(compiler));
}
if (options.checkMissingReturn.isOn()) {
callbacks.add(
new CheckMissingReturn(compiler, options.checkMissingReturn));
}
return combineChecks(compiler, callbacks);
}
};
/** Checks access controls. Depends on type-inference. */
private final HotSwapPassFactory checkAccessControls =
new HotSwapPassFactory("checkAccessControls", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new CheckAccessControls(
compiler, options.enforceAccessControlCodingConventions);
}
};
private final HotSwapPassFactory lintChecks =
new HotSwapPassFactory("lintChecks", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
ImmutableList.Builder<Callback> callbacks = ImmutableList.<Callback>builder()
.add(new CheckEmptyStatements(compiler))
.add(new CheckEnums(compiler))
.add(new CheckInterfaces(compiler))
.add(new CheckJSDocStyle(compiler))
.add(new CheckNullableReturn(compiler))
.add(new CheckPrototypeProperties(compiler))
.add(new ImplicitNullabilityCheck(compiler));
if (options.closurePass) {
callbacks.add(new CheckRequiresAndProvidesSorted(compiler));
}
return combineChecks(compiler, callbacks.build());
}
};
/** Executes the given callbacks with a {@link CombinedCompilerPass}. */
private static HotSwapCompilerPass combineChecks(AbstractCompiler compiler,
List<Callback> callbacks) {
Preconditions.checkArgument(!callbacks.isEmpty());
return new CombinedCompilerPass(compiler, callbacks);
}
/** A compiler pass that resolves types in the global scope. */
class GlobalTypeResolver implements HotSwapCompilerPass {
private final AbstractCompiler compiler;
GlobalTypeResolver(AbstractCompiler compiler) {
this.compiler = compiler;
}
@Override
public void process(Node externs, Node root) {
if (topScope == null) {
regenerateGlobalTypedScope(compiler, root.getParent());
} else {
compiler.getTypeRegistry().resolveTypesInScope(topScope);
}
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
patchGlobalTypedScope(compiler, scriptRoot);
}
}
/** A compiler pass that clears the global scope. */
class ClearTypedScope implements CompilerPass {
@Override
public void process(Node externs, Node root) {
clearTypedScope();
}
}
/** Checks global name usage. */
private final PassFactory checkGlobalNames =
new PassFactory("checkGlobalNames", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
// Create a global namespace for analysis by check passes.
// Note that this class does all heavy computation lazily,
// so it's OK to create it here.
namespaceForChecks = new GlobalNamespace(compiler, externs, jsRoot);
new CheckGlobalNames(compiler, options.checkGlobalNamesLevel)
.injectNamespace(namespaceForChecks).process(externs, jsRoot);
}
};
}
};
/** Checks that the code is ES5 strict compliant. */
private final PassFactory checkStrictMode =
new PassFactory("checkStrictMode", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new StrictModeCheck(compiler,
!options.checkSymbols); // don't check variables twice
}
};
/** Process goog.tweak.getTweak() calls. */
private final PassFactory processTweaks = new PassFactory("processTweaks", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
new ProcessTweaks(compiler,
options.getTweakProcessing().shouldStrip(),
options.getTweakReplacements()).process(externs, jsRoot);
}
};
}
};
/** Override @define-annotated constants. */
private final PassFactory processDefines = new PassFactory("processDefines", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
HashMap<String, Node> replacements = new HashMap<>();
replacements.putAll(compiler.getDefaultDefineValues());
replacements.putAll(getAdditionalReplacements(options));
replacements.putAll(options.getDefineReplacements());
new ProcessDefines(compiler, ImmutableMap.copyOf(replacements))
.injectNamespace(namespaceForChecks).process(externs, jsRoot);
}
};
}
};
/** Release references to data that is only needed during checks. */
final PassFactory garbageCollectChecks =
new HotSwapPassFactory("garbageCollectChecks", true) {
@Override
protected HotSwapCompilerPass create(final AbstractCompiler compiler) {
return new HotSwapCompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
// Kill the global namespace so that it can be garbage collected
// after all passes are through with it.
namespaceForChecks = null;
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
process(null, null);
}
};
}
};
/** Checks that all constants are not modified */
private final PassFactory checkConsts = new PassFactory("checkConsts", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ConstCheck(compiler);
}
};
/** Checks that the arguments are constants */
private final PassFactory checkConstParams =
new PassFactory("checkConstParams", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ConstParamCheck(compiler);
}
};
/** Check memory bloat patterns */
private final PassFactory checkEventfulObjectDisposal =
new PassFactory("checkEventfulObjectDisposal", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CheckEventfulObjectDisposal(compiler,
options.checkEventfulObjectDisposalPolicy);
}
};
/** Computes the names of functions for later analysis. */
private final PassFactory computeFunctionNames =
new PassFactory("computeFunctionNames", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return ((functionNames = new FunctionNames(compiler)));
}
};
/** Inserts run-time type assertions for debugging. */
private final PassFactory runtimeTypeCheck =
new PassFactory("runtimeTypeCheck", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RuntimeTypeCheck(compiler,
options.runtimeTypeCheckLogFunction);
}
};
/** Generates unique ids. */
private final PassFactory replaceIdGenerators =
new PassFactory("replaceIdGenerators", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
ReplaceIdGenerators pass =
new ReplaceIdGenerators(
compiler, options.idGenerators, options.generatePseudoNames,
options.idGeneratorsMapSerialized);
pass.process(externs, root);
idGeneratorMap = pass.getSerializedIdMappings();
}
};
}
};
/** Replace strings. */
private final PassFactory replaceStrings = new PassFactory("replaceStrings", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
ReplaceStrings pass = new ReplaceStrings(
compiler,
options.replaceStringsPlaceholderToken,
options.replaceStringsFunctionDescriptions,
options.replaceStringsReservedStrings,
options.replaceStringsInputMap);
pass.process(externs, root);
stringMap = pass.getStringMap();
}
};
}
};
/** Optimizes the "arguments" array. */
private final PassFactory optimizeArgumentsArray =
new PassFactory("optimizeArgumentsArray", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new OptimizeArgumentsArray(compiler);
}
};
/** Remove variables set to goog.abstractMethod. */
private final PassFactory closureCodeRemoval =
new PassFactory("closureCodeRemoval", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ClosureCodeRemoval(compiler, options.removeAbstractMethods,
options.removeClosureAsserts);
}
};
/** Special case optimizations for closure functions. */
private final PassFactory closureOptimizePrimitives =
new PassFactory("closureOptimizePrimitives", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new ClosureOptimizePrimitives(compiler);
}
};
/** Puts global symbols into a single object. */
private final PassFactory rescopeGlobalSymbols =
new PassFactory("rescopeGlobalSymbols", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RescopeGlobalSymbols(
compiler,
options.renamePrefixNamespace,
options.renamePrefixNamespaceAssumeCrossModuleNames);
}
};
/** Collapses names in the global scope. */
private final PassFactory collapseProperties =
new PassFactory("collapseProperties", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CollapseProperties(compiler);
}
};
/** Rewrite properties as variables. */
private final PassFactory collapseObjectLiterals =
new PassFactory("collapseObjectLiterals", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineObjectLiterals(
compiler, compiler.getUniqueNameIdSupplier());
}
};
/** Disambiguate property names based on the coding convention. */
private final PassFactory disambiguatePrivateProperties =
new PassFactory("disambiguatePrivateProperties", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DisambiguatePrivateProperties(compiler);
}
};
/** Disambiguate property names based on type information. */
private final PassFactory disambiguateProperties =
new PassFactory("disambiguateProperties", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return DisambiguateProperties.forJSTypeSystem(compiler,
options.propertyInvalidationErrors);
}
};
/**
* Chain calls to functions that return this.
*/
private final PassFactory chainCalls = new PassFactory("chainCalls", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ChainCalls(compiler);
}
};
/**
* Rewrite instance methods as static methods, to make them easier
* to inline.
*/
private final PassFactory devirtualizePrototypeMethods =
new PassFactory("devirtualizePrototypeMethods", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DevirtualizePrototypeMethods(compiler);
}
};
/**
* Optimizes unused function arguments, unused return values, and inlines
* constant parameters. Also runs RemoveUnusedVars.
*/
private final PassFactory optimizeCallsAndRemoveUnusedVars =
new PassFactory("optimizeCalls_and_removeUnusedVars", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
OptimizeCalls passes = new OptimizeCalls(compiler);
if (options.optimizeReturns) {
// Remove unused return values.
passes.addPass(new OptimizeReturns(compiler));
}
if (options.optimizeParameters) {
// Remove all parameters that are constants or unused.
passes.addPass(new OptimizeParameters(compiler));
}
if (options.optimizeCalls) {
boolean removeOnlyLocals = options.removeUnusedLocalVars
&& !options.removeUnusedVars;
boolean preserveAnonymousFunctionNames =
options.anonymousFunctionNaming !=
AnonymousFunctionNamingPolicy.OFF;
passes.addPass(
new RemoveUnusedVars(compiler, !removeOnlyLocals,
preserveAnonymousFunctionNames, true));
}
return passes;
}
};
/**
* Look for function calls that are pure, and annotate them
* that way.
*/
private final PassFactory markPureFunctions =
new PassFactory("markPureFunctions", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new PureFunctionIdentifier.Driver(
compiler, options.debugFunctionSideEffectsPath, false);
}
};
/**
* Look for function calls that have no side effects, and annotate them
* that way.
*/
private final PassFactory markNoSideEffectCalls =
new PassFactory("markNoSideEffectCalls", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new MarkNoSideEffectCalls(compiler);
}
};
/** Inlines variables heuristically. */
private final PassFactory inlineVariables =
new PassFactory("inlineVariables", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
InlineVariables.Mode mode;
if (options.inlineVariables) {
mode = InlineVariables.Mode.ALL;
} else if (options.inlineLocalVariables) {
mode = InlineVariables.Mode.LOCALS_ONLY;
} else {
throw new IllegalStateException("No variable inlining option set.");
}
return new InlineVariables(compiler, mode, true);
}
};
/** Inlines variables that are marked as constants. */
private final PassFactory inlineConstants =
new PassFactory("inlineConstants", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineVariables(
compiler, InlineVariables.Mode.CONSTANTS_ONLY, true);
}
};
/**
* Perform local control flow optimizations.
*/
private final PassFactory minimizeExitPoints =
new PassFactory("minimizeExitPoints", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new MinimizeExitPoints(compiler);
}
};
/**
* Use data flow analysis to remove dead branches.
*/
private final PassFactory removeUnreachableCode =
new PassFactory("removeUnreachableCode", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new UnreachableCodeElimination(compiler, true);
}
};
/**
* Remove prototype properties that do not appear to be used.
*/
private final PassFactory removeUnusedPrototypeProperties =
new PassFactory("removeUnusedPrototypeProperties", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RemoveUnusedPrototypeProperties(
compiler, options.removeUnusedPrototypePropertiesInExterns,
!options.removeUnusedVars);
}
};
/**
* Remove prototype properties that do not appear to be used.
*/
private final PassFactory removeUnusedClassProperties =
new PassFactory("removeUnusedClassProperties", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RemoveUnusedClassProperties(
compiler, options.removeUnusedConstructorProperties);
}
};
/**
* Process smart name processing - removes unused classes and does referencing
* starting with minimum set of names.
*/
private final PassFactory smartNamePass = new PassFactory("smartNamePass", true) {
private boolean hasWrittenFile = false;
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
NameAnalyzer na = new NameAnalyzer(compiler, false);
na.process(externs, root);
String reportPath = options.reportPath;
if (reportPath != null) {
try {
if (hasWrittenFile) {
Files.append(na.getHtmlReport(), new File(reportPath),
UTF_8);
} else {
Files.write(na.getHtmlReport(), new File(reportPath),
UTF_8);
hasWrittenFile = true;
}
} catch (IOException e) {
compiler.report(JSError.make(REPORT_PATH_IO_ERROR, reportPath));
}
}
if (options.smartNameRemoval) {
na.removeUnreferenced();
}
}
};
}
};
/**
* Process smart name processing - removes unused classes and does referencing
* starting with minimum set of names.
*/
private final PassFactory smartNamePass2 = new PassFactory("smartNamePass", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
NameAnalyzer na = new NameAnalyzer(compiler, false);
na.process(externs, root);
na.removeUnreferenced();
}
};
}
};
/** Inlines simple methods, like getters */
private final PassFactory inlineSimpleMethods =
new PassFactory("inlineSimpleMethods", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineSimpleMethods(compiler);
}
};
/** Kills dead assignments. */
private final PassFactory deadAssignmentsElimination =
new PassFactory("deadAssignmentsElimination", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new DeadAssignmentsElimination(compiler);
}
};
/** Inlines function calls. */
private final PassFactory inlineFunctions =
new PassFactory("inlineFunctions", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineFunctions(
compiler,
compiler.getUniqueNameIdSupplier(),
options.inlineFunctions,
options.inlineLocalFunctions,
true,
options.assumeStrictThis()
|| options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT,
options.assumeClosuresOnlyCaptureReferences,
options.maxFunctionSizeAfterInlining);
}
};
/** Inlines constant properties. */
private final PassFactory inlineProperties =
new PassFactory("inlineProperties", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new InlineProperties(compiler);
}
};
/** Removes variables that are never used. */
private final PassFactory removeUnusedVars =
new PassFactory("removeUnusedVars", false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
boolean removeOnlyLocals = options.removeUnusedLocalVars
&& !options.removeUnusedVars;
boolean preserveAnonymousFunctionNames =
options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF;
return new RemoveUnusedVars(
compiler,
!removeOnlyLocals,
preserveAnonymousFunctionNames,
false);
}
};
/**
* Move global symbols to a deeper common module
*/
private final PassFactory crossModuleCodeMotion =
new PassFactory(Compiler.CROSS_MODULE_CODE_MOTION_NAME, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CrossModuleCodeMotion(
compiler,
compiler.getModuleGraph(),
options.parentModuleCanSeeSymbolsDeclaredInChildren);
}
};
/**
* Move methods to a deeper common module
*/
private final PassFactory crossModuleMethodMotion =
new PassFactory(Compiler.CROSS_MODULE_METHOD_MOTION_NAME, false) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CrossModuleMethodMotion(
compiler, crossModuleIdGenerator,
// Only move properties in externs if we're not treating
// them as exports.
options.removeUnusedPrototypePropertiesInExterns,
options.crossModuleCodeMotionNoStubMethods);
}
};
/** A data-flow based variable inliner. */
private final PassFactory flowSensitiveInlineVariables =
new PassFactory("flowSensitiveInlineVariables", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new FlowSensitiveInlineVariables(compiler);
}
};
/** Uses register-allocation algorithms to use fewer variables. */
private final PassFactory coalesceVariableNames =
new PassFactory("coalesceVariableNames", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CoalesceVariableNames(compiler, options.generatePseudoNames);
}
};
/**
* Some simple, local collapses (e.g., {@code var x; var y;} becomes
* {@code var x,y;}.
*/
private final PassFactory exploitAssign = new PassFactory("exploitAssign", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new PeepholeOptimizationsPass(compiler,
new ExploitAssigns());
}
};
/**
* Some simple, local collapses (e.g., {@code var x; var y;} becomes
* {@code var x,y;}.
*/
private final PassFactory collapseVariableDeclarations =
new PassFactory("collapseVariableDeclarations", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CollapseVariableDeclarations(compiler);
}
};
/**
* Extracts common sub-expressions.
*/
private final PassFactory extractPrototypeMemberDeclarations =
new PassFactory("extractPrototypeMemberDeclarations", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
Pattern pattern;
switch (options.extractPrototypeMemberDeclarations) {
case USE_GLOBAL_TEMP:
pattern = Pattern.USE_GLOBAL_TEMP;
break;
case USE_IIFE:
pattern = Pattern.USE_IIFE;
break;
default:
throw new IllegalStateException("unexpected");
}
return new ExtractPrototypeMemberDeclarations(
compiler, pattern);
}
};
/** Rewrites common function definitions to be more compact. */
private final PassFactory rewriteFunctionExpressions =
new PassFactory("rewriteFunctionExpressions", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new FunctionRewriter(compiler);
}
};
/** Collapses functions to not use the VAR keyword. */
private final PassFactory collapseAnonymousFunctions =
new PassFactory("collapseAnonymousFunctions", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new CollapseAnonymousFunctions(compiler);
}
};
/** Moves function declarations to the top, to simulate actual hoisting. */
private final PassFactory moveFunctionDeclarations =
new PassFactory("moveFunctionDeclarations", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new MoveFunctionDeclarations(compiler);
}
};
private final PassFactory nameUnmappedAnonymousFunctions =
new PassFactory("nameAnonymousFunctions", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new NameAnonymousFunctions(compiler);
}
};
private final PassFactory nameMappedAnonymousFunctions =
new PassFactory("nameAnonymousFunctions", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
NameAnonymousFunctionsMapped naf =
new NameAnonymousFunctionsMapped(
compiler, options.inputAnonymousFunctionNamingMap);
naf.process(externs, root);
anonymousFunctionNameMap = naf.getFunctionMap();
}
};
}
};
/** Alias external symbols. */
private final PassFactory aliasExternals = new PassFactory("aliasExternals", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AliasExternals(compiler, compiler.getModuleGraph(),
options.unaliasableGlobals, options.aliasableGlobals);
}
};
/**
* Alias string literals with global variables, to avoid creating lots of
* transient objects.
*/
private final PassFactory aliasStrings = new PassFactory("aliasStrings", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AliasStrings(
compiler,
compiler.getModuleGraph(),
options.aliasAllStrings ? null : options.aliasableStrings,
options.aliasStringsBlacklist,
options.outputJsStringUsage);
}
};
/** Handling for the ObjectPropertyString primitive. */
private final PassFactory objectPropertyStringPostprocess =
new PassFactory("ObjectPropertyStringPostprocess", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ObjectPropertyStringPostprocess(compiler);
}
};
/**
* Renames properties so that the two properties that never appear on
* the same object get the same name.
*/
private final PassFactory ambiguateProperties =
new PassFactory("ambiguateProperties", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AmbiguateProperties(
compiler, options.anonymousFunctionNaming.getReservedCharacters());
}
};
/**
* Mark the point at which the normalized AST assumptions no longer hold.
*/
private final PassFactory markUnnormalized =
new PassFactory("markUnnormalized", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
compiler.setLifeCycleStage(LifeCycleStage.RAW);
}
};
}
};
/** Denormalize the AST for code generation. */
private final PassFactory denormalize = new PassFactory("denormalize", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new Denormalize(compiler);
}
};
/** Inverting name normalization. */
private final PassFactory invertContextualRenaming =
new PassFactory("invertContextualRenaming", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return MakeDeclaredNamesUnique.getContextualRenameInverter(compiler);
}
};
/**
* Renames properties.
*/
private final PassFactory renameProperties =
new PassFactory("renameProperties", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
Preconditions.checkState(options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED);
final VariableMap prevPropertyMap = options.inputPropertyMap;
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
char[] reservedChars = options.anonymousFunctionNaming.getReservedCharacters();
RenameProperties rprop =
new RenameProperties(
compiler, options.generatePseudoNames, prevPropertyMap, reservedChars);
rprop.process(externs, root);
propertyMap = rprop.getPropertyMap();
}
};
}
};
/** Renames variables. */
private final PassFactory renameVars = new PassFactory("renameVars", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
final VariableMap prevVariableMap = options.inputVariableMap;
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
variableMap = runVariableRenaming(
compiler, prevVariableMap, externs, root);
}
};
}
};
private VariableMap runVariableRenaming(
AbstractCompiler compiler, VariableMap prevVariableMap,
Node externs, Node root) {
char[] reservedChars =
options.anonymousFunctionNaming.getReservedCharacters();
boolean preserveAnonymousFunctionNames =
options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF;
Set<String> reservedNames = new HashSet<>();
if (options.renamePrefixNamespace != null) {
// don't use the prefix name as a global symbol.
reservedNames.add(options.renamePrefixNamespace);
}
if (exportedNames != null) {
reservedNames.addAll(exportedNames);
}
reservedNames.addAll(ParserRunner.getReservedVars());
RenameVars rn = new RenameVars(
compiler,
options.renamePrefix,
options.variableRenaming == VariableRenamingPolicy.LOCAL,
preserveAnonymousFunctionNames,
options.generatePseudoNames,
options.shadowVariables,
options.preferStableNames,
prevVariableMap,
reservedChars,
reservedNames);
rn.process(externs, root);
return rn.getVariableMap();
}
/** Renames labels */
private final PassFactory renameLabels = new PassFactory("renameLabels", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new RenameLabels(compiler);
}
};
/** Convert bracket access to dot access */
private final PassFactory convertToDottedProperties =
new PassFactory("convertToDottedProperties", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new ConvertToDottedProperties(compiler);
}
};
/** Checks that all variables are defined. */
private final PassFactory sanityCheckAst = new PassFactory("sanityCheckAst", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new AstValidator(compiler);
}
};
/** Checks that all variables are defined. */
private final PassFactory sanityCheckVars = new PassFactory("sanityCheckVars", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new VarCheck(compiler, true);
}
};
/** Adds instrumentations according to an instrumentation template. */
private final PassFactory instrumentFunctions =
new PassFactory("instrumentFunctions", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
try {
FileReader templateFile =
new FileReader(options.instrumentationTemplate);
(new InstrumentFunctions(
compiler, functionNames,
options.instrumentationTemplate,
options.appNameStr,
templateFile)).process(externs, root);
} catch (IOException e) {
compiler.report(
JSError.make(AbstractCompiler.READ_ERROR,
options.instrumentationTemplate));
}
}
};
}
};
private final PassFactory instrumentForCodeCoverage =
new PassFactory("instrumentForCodeCoverage", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
// TODO(johnlenz): make global instrumentation an option
return new CoverageInstrumentationPass(
compiler, CoverageReach.CONDITIONAL);
}
};
/** Extern property names gathering pass. */
private final PassFactory gatherExternProperties =
new PassFactory("gatherExternProperties", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new GatherExternProperties(compiler);
}
};
/**
* Create a no-op pass that can only run once. Used to break up loops.
*/
static PassFactory createEmptyPass(String name) {
return new PassFactory(name, true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return runInSerial();
}
};
}
/**
* Runs custom passes that are designated to run at a particular time.
*/
private PassFactory getCustomPasses(
final CustomPassExecutionTime executionTime) {
return new PassFactory("runCustomPasses", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return runInSerial(options.customPasses.get(executionTime));
}
};
}
/** Create a compiler pass that runs the given passes in serial. */
private static CompilerPass runInSerial(final CompilerPass ... passes) {
return runInSerial(ImmutableSet.copyOf(passes));
}
/** Create a compiler pass that runs the given passes in serial. */
private static CompilerPass runInSerial(
final Collection<CompilerPass> passes) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
for (CompilerPass pass : passes) {
pass.process(externs, root);
}
}
};
}
@VisibleForTesting
static Map<String, Node> getAdditionalReplacements(
CompilerOptions options) {
Map<String, Node> additionalReplacements = new HashMap<>();
if (options.markAsCompiled || options.closurePass) {
additionalReplacements.put(COMPILED_CONSTANT_NAME, IR.trueNode());
}
if (options.closurePass && options.locale != null) {
additionalReplacements.put(CLOSURE_LOCALE_CONSTANT_NAME,
IR.string(options.locale));
}
return additionalReplacements;
}
private final PassFactory printNameReferenceGraph =
new PassFactory("printNameReferenceGraph", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
NameReferenceGraphConstruction gc =
new NameReferenceGraphConstruction(compiler);
gc.process(externs, jsRoot);
String graphFileName = options.nameReferenceGraphPath;
try {
Files.write(DotFormatter.toDot(gc.getNameReferenceGraph()),
new File(graphFileName),
UTF_8);
} catch (IOException e) {
compiler.report(
JSError.make(
NAME_REF_GRAPH_FILE_ERROR, e.getMessage(), graphFileName));
}
}
};
}
};
private final PassFactory printNameReferenceReport =
new PassFactory("printNameReferenceReport", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
NameReferenceGraphConstruction gc =
new NameReferenceGraphConstruction(compiler);
String reportFileName = options.nameReferenceReportPath;
try {
NameReferenceGraphReport report =
new NameReferenceGraphReport(gc.getNameReferenceGraph());
Files.write(report.getHtmlReport(),
new File(reportFileName),
UTF_8);
} catch (IOException e) {
compiler.report(
JSError.make(
NAME_REF_REPORT_FILE_ERROR,
e.getMessage(),
reportFileName));
}
}
};
}
};
/** Rewrites Polymer({}) */
private final HotSwapPassFactory polymerPass =
new HotSwapPassFactory("polymerPass", true) {
@Override
protected HotSwapCompilerPass create(AbstractCompiler compiler) {
return new PolymerPass(compiler);
}
};
/**
* A pass-factory that is good for {@code HotSwapCompilerPass} passes.
*/
abstract static class HotSwapPassFactory extends PassFactory {
HotSwapPassFactory(String name, boolean isOneTimePass) {
super(name, isOneTimePass);
}
@Override
protected abstract HotSwapCompilerPass create(AbstractCompiler compiler);
@Override
HotSwapCompilerPass getHotSwapPass(AbstractCompiler compiler) {
return this.create(compiler);
}
}
private final PassFactory checkConformance =
new PassFactory("checkConformance", true) {
@Override
protected CompilerPass create(final AbstractCompiler compiler) {
return new CheckConformance(
compiler, ImmutableList.copyOf(options.getConformanceConfigs()));
}
};
/** Optimizations that output ES6 features. */
private final PassFactory optimizeToEs6 = new PassFactory("optimizeToEs6", true) {
@Override
protected CompilerPass create(AbstractCompiler compiler) {
return new SubstituteEs6Syntax(compiler);
}
};
}
|
Moving exportTestFunctions pass to before later transpilation
-------------
Created by MOE: http://code.google.com/p/moe-java
MOE_MIGRATED_REVID=98840291
|
src/com/google/javascript/jscomp/DefaultPassConfig.java
|
Moving exportTestFunctions pass to before later transpilation ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=98840291
|
|
Java
|
apache-2.0
|
a28ad598dc464cf06c2870444c3dee269e7b74b9
| 0
|
pfirmstone/JGDMS,pfirmstone/river-internet,pfirmstone/JGDMS,pfirmstone/JGDMS,pfirmstone/JGDMS,pfirmstone/river-internet,pfirmstone/river-internet
|
/*
* 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.
*/
/*
* MulticastRequestDelay.java
*
* Created on March 4, 2005, 11:14 AM
* Revised on August 9, 2019, 11:53 AM AEST.
*/
package org.apache.river.test.impl.lookupdiscovery;
import org.apache.river.config.Config;
import org.apache.river.qa.harness.QAConfig;
import org.apache.river.qa.harness.QATestEnvironment;
import org.apache.river.qa.harness.Test;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.util.logging.Level;
import net.jini.config.Configuration;
import net.jini.discovery.Constants;
import net.jini.discovery.LookupDiscovery;
/**
* Tests the <code>initialMulticastRequestDelayRange</code> configuration entry
* for <code>LookupDiscovery</code>. It starts a number of
* <code>LookupDisocvery</code> instances and waits for multicast requests
* from them. The average delay of multicast discovery requests that are
* initiated is measured and must fall within the range
* <code>0.25 * initialMulticastRequestDelayRange < averageDelay <
* 0.75 * initialMulticastRequestDelayRange</code>.
*
*
*/
public class MulticastRequestDelay extends QATestEnvironment implements Test {
private static final int DISCOVERYPORT = Constants.discoveryPort;
/* P. Firmstone - 19th Aug 2019
*
* Previously this test had a SkipConfigTestVerifier, for all configurations
* except for jeri. It is not known whether jeri was left out by accident,
* as running with jeri has been a releatively recent occurrence
* for a long time tests have been run with none configuration, which
* would mean this test was skipped. It seems this test was not completed.
*
* This test is meant to confirm the average delay time of the
* "initialMulticastRequestDelayRange" configuration option for LookupDiscovery
* over a number of tests is within an expected range, from the middle of
* the delay duration, as the delay time is randomised between 0 and the
* configured delay range.
*
* Originally there were 100 LookupDiscovery instances created, resulting
* in significant creation time overhead, the last LookupDiscovery created
* also incurred the creation time of 99 other LookupDiscovery objects,
* which added significantly to the delay, resulting in test failures.
* Further complicating the issue is previously started LookupDiscovery
* instances are also still sending Datagram packets, so we might be counting
* datagram packets from the wrong LD.
* A much better approach is to start each LookupDiscovery
* individually, wait for the first repsonse, measure the delay, record it,
* stop the LookupDiscovery, then start another LookupDiscovery and so on,
* and average the delays. This way we are only incurring the start up
* time of one LookupDiscovery in our delay time and we can be idempotent,
* ignoring any Datagram packets that arrive before a LookupDiscovery starts.
* The number of LookupDiscovery objects started has been reduced to ten,
* this appears to be enough to confirm average delay time,
* if there are test failures, this number can be increased.
*
* Additionally the test was looking for the localhost IP address,
* rather than confirming that the network address originated from this
* node, so it didn't recognise any received events.
*
* After fixing this test, I found I needed to adjust LookupDiscovery
* to reduce the configured delay by its creation time. Unfortunately
* in order to maintain the same average delay, we must also reduce
* the upper bound, by a similar amount, resulting in a smaller standard
* deviation.
* Following the range adjustment to allow for creation time of LD, with
* 100 LD's the average is within 25ms of the required average delay. With
* 10 LD's the average is within 500ms of the required average delay, in any
* case all test durations appear to be with the upper and lower bounds as
* a result of the range adjustment in any case. With 10 LD's the test
* duration is 1 minute and 40 seconds, with 100, it's over 12 minutes.
*
* Obviously the longer the delay time configured, the
* less impact LD's creation time will have on the standard deviation.
*/
private static final int NUMLD = 10;
private Configuration config;
private Throwable failure = null;
private boolean done = false;
// Synchronize on acceptTime for startTime too.
private final long acceptTime[] = new long[NUMLD];
private final long startTime[] = new long[NUMLD];
LookupDiscovery[] ldArray = new LookupDiscovery[NUMLD];
private class AcceptThread extends Thread {
private MulticastSocket socket;
public AcceptThread() throws Exception {
super("multicast request");
setDaemon(true);
socket = new MulticastSocket(Constants.discoveryPort);
socket.joinGroup(Constants.getRequestAddress());
}
public void run() {
byte[] buf = new byte[576];
DatagramPacket dgram = new DatagramPacket(buf, buf.length);
int i = 0;
try {
while (i < NUMLD) {
dgram.setLength(buf.length);
socket.receive(dgram);
long time = System.currentTimeMillis();
// We confirm that this is the local expected address used during testing, not some foreign.
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(dgram.getAddress());
if (networkInterface != null) {
synchronized (acceptTime){
if (startTime[i] == 0) continue; // IGNORE: We haven't started this must be another from the last LD. Idempotent.
acceptTime[i] = time;
}
synchronized (this){
this.notify();
}
logger.log(Level.FINEST, "Received request {0}", i);
i++;
}
}
} catch (Throwable t) {
failure = t;
} finally {
synchronized (this) {
done = true;
this.notify();
socket.close();
}
}
}
}
@Override
public void run() throws Exception {
long delay = Config.getLongEntry(config,
"net.jini.discovery.LookupDiscovery",
"initialMulticastRequestDelayRange",
10000, 0, Long.MAX_VALUE);
long expectedDelay = delay / 2;
logger.log(Level.FINE, "Expected average delay {0}", expectedDelay);
long spread = expectedDelay / 2;
long lBound = expectedDelay - spread;
long uBound = expectedDelay + spread;
if ((lBound < 0) || (uBound < 0)) {
throw new IllegalArgumentException("Invalid delay " + delay);
}
if (NUMLD < 2) {
throw new IllegalArgumentException("Invalid number of LDs " + NUMLD);
}
Thread t = new AcceptThread();
t.start();
// Wait for AcceptThread to set up its socket.
Thread.sleep(1000);
for (int i = 0; i < NUMLD; i++) {
LookupDiscovery ld = null;
synchronized (acceptTime){
startTime[i] = System.currentTimeMillis();
}
try {
ld = new LookupDiscovery(
new String[] {
InetAddress.getLocalHost().getHostName() + "_mrd_" +
System.currentTimeMillis()
},
config);
synchronized(t) {
t.wait(delay * 3 / 2);
}
} finally {
if (ld != null) ld.terminate();
Thread.sleep(2000); // Allow some time for remaining events to be ignored.
}
}
if (failure != null) {
throw new RuntimeException("Test failed ", failure);
}
if (!done) {
throw new RuntimeException("All "
+ NUMLD + " multicast requests not received");
}
float averageDelay = 0f;
synchronized (acceptTime){
for (int i = 0; i < NUMLD; i++) {
logger.log(
Level.FINEST, "Start time: {0}, Finish time: {1}, Delay: {2}",
new String [] {
Long.toString(startTime[i]),
Long.toString(acceptTime[i]),
Long.toString(acceptTime[i] - startTime[i])
}
);
long timei = acceptTime[i] - startTime[i];
averageDelay = averageDelay + (timei / NUMLD);
}
}
logger.log(Level.FINE, "Average delay {0}", (long) averageDelay);
if ((averageDelay < lBound) || (averageDelay > uBound)) {
throw new RuntimeException("Elapsed time out of expected range " +
+ averageDelay +
" lower bound " + lBound +
" upper bound " + uBound);
}
}
@Override
public Test construct(QAConfig qaconfig) throws Exception {
super.construct(qaconfig);
config = qaconfig.getConfig().getConfiguration();
return this;
}
@Override
public void tearDown() {
super.tearDown();
for (int i = 0; i < NUMLD; i++) {
ldArray[i].terminate();
}
}
}
|
qa/src/org/apache/river/test/impl/lookupdiscovery/MulticastRequestDelay.java
|
/*
* 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.
*/
/*
* MulticastRequestDelay.java
*
* Created on March 4, 2005, 11:14 AM
*/
package org.apache.river.test.impl.lookupdiscovery;
import org.apache.river.config.Config;
import org.apache.river.qa.harness.QAConfig;
import org.apache.river.qa.harness.QATestEnvironment;
import org.apache.river.qa.harness.Test;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import net.jini.config.Configuration;
import net.jini.config.ConfigurationProvider;
import net.jini.discovery.Constants;
import net.jini.discovery.LookupDiscovery;
/**
* Tests the <code>initialMulticastRequestDelayRange</code> configuration entry
* for <code>LookupDiscovery</code>. It starts a number of
* <code>LookupDisocvery</code> instances and waits for multicast requests
* from them. The average delay of multicast discovery requests that are
* initiated is measured and must fall within the range
* <code>0.25 * initialMulticastRequestDelayRange < averageDelay <
* 0.75 * initialMulticastRequestDelayRange</code>.
*
*
*/
public class MulticastRequestDelay extends QATestEnvironment implements Test {
private static final int DISCOVERYPORT = Constants.discoveryPort;
private static final int NUMLD = 100;
private static final InetAddress localHost;
private Configuration config;
static {
try {
localHost = InetAddress.getLocalHost();
} catch (UnknownHostException ue) {
throw new RuntimeException(ue);
}
}
private Throwable failure = null;
private boolean done = false;
private long acceptTime[] = new long[NUMLD];
LookupDiscovery[] ldArray = new LookupDiscovery[NUMLD];
private class AcceptThread extends Thread {
private MulticastSocket socket;
public AcceptThread() throws Exception {
super("multicast request");
setDaemon(true);
socket = new MulticastSocket(Constants.discoveryPort);
socket.joinGroup(Constants.getRequestAddress());
}
public void run() {
byte[] buf = new byte[576];
DatagramPacket dgram = new DatagramPacket(buf, buf.length);
int i = 0;
try {
while (i < 100) {
dgram.setLength(buf.length);
socket.receive(dgram);
if (dgram.getAddress().equals(localHost)) {
acceptTime[i] = System.currentTimeMillis();
logger.log(Level.FINEST, "Received request " + i);
i++;
}
}
} catch (Throwable t) {
failure = t;
} finally {
synchronized (this) {
done = true;
this.notify();
socket.close();
}
}
}
}
public void run() throws Exception {
long delay = Config.getLongEntry(config,
"net.jini.discovery.LookupDiscovery",
"initialMulticastRequestDelayRange",
10000, 0, Long.MAX_VALUE);
long expectedDelay = delay / 2;
logger.log(Level.FINE, "Expected average delay " + expectedDelay);
long spread = expectedDelay / 2;
long lBound = expectedDelay - spread;
long uBound = expectedDelay + spread;
if ((lBound < 0) || (uBound < 0)) {
throw new IllegalArgumentException("Invalid delay " + delay);
}
if (NUMLD < 2) {
throw new IllegalArgumentException("Invalid number of LDs " + NUMLD);
}
Thread t = new AcceptThread();
t.start();
// Wait for AcceptThread to set up its socket.
Thread.sleep(1000);
long startTime = System.currentTimeMillis();
for (int i = 0; i < NUMLD; i++) {
ldArray[i] = new LookupDiscovery(
new String[] {
InetAddress.getLocalHost().getHostName() + "_mrd_" +
System.currentTimeMillis()
},
config);
}
synchronized(t) {
t.wait(delay * 3 / 2);
}
if (failure != null) {
throw new RuntimeException("Test failed ", failure);
}
if (!done) {
throw new RuntimeException("All "
+ NUMLD + " multicast requests not received");
}
float averageDelay = 0f;
for (int i = 0; i < NUMLD; i++) {
long timei = acceptTime[i] - startTime;
averageDelay = averageDelay + (timei / NUMLD);
}
logger.log(Level.FINE, "Average delay " + (long) averageDelay);
if ((averageDelay < lBound) || (averageDelay > uBound)) {
throw new RuntimeException("Elapsed time out of expected range " +
+ averageDelay +
" lower bound " + lBound +
" upper bound " + uBound);
}
}
public Test construct(QAConfig qaconfig) throws Exception {
super.construct(qaconfig);
config = qaconfig.getConfig().getConfiguration();
return this;
}
public void tearDown() {
super.tearDown();
for (int i = 0; i < NUMLD; i++) {
ldArray[i].terminate();
}
}
}
|
Integration test org/apache/river/test/impl/lookupdiscovery/MulticastRequestDelay.td in unfinished state #82
|
qa/src/org/apache/river/test/impl/lookupdiscovery/MulticastRequestDelay.java
|
Integration test org/apache/river/test/impl/lookupdiscovery/MulticastRequestDelay.td in unfinished state #82
|
|
Java
|
apache-2.0
|
99f93c3905e3e759db031f8fb8e608aea7f41d2c
| 0
|
crate/crate,crate/crate,crate/crate
|
/*
* 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.cluster;
import io.crate.integrationtests.SQLTransportIntegrationTest;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.settings.Settings;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicBoolean;
import static io.crate.testing.SQLTransportExecutor.REQUEST_TIMEOUT;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
public class ClusterHealthIT extends SQLTransportIntegrationTest {
@Test
public void testSimpleLocalHealth() {
execute("create table test (id int) with (number_of_replicas = 0)");
ensureGreen(); // master should think it's green now.
for (final String node : internalCluster().getNodeNames()) {
// a very high time out, which should never fire due to the local flag
logger.info("--> getting cluster health on [{}]", node);
final ClusterHealthResponse health = client(node).admin().cluster().prepareHealth().setLocal(true)
.setWaitForEvents(Priority.LANGUID).setTimeout("30s").execute().actionGet(REQUEST_TIMEOUT);
logger.info("--> got cluster health on [{}]", node);
assertFalse("timed out on " + node, health.isTimedOut());
assertThat("health status on " + node, health.getStatus(), equalTo(ClusterHealthStatus.GREEN));
}
}
@Test
public void testHealth() {
logger.info("--> running cluster health on an index that does not exists");
ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth("test1")
.setWaitForYellowStatus().setTimeout("1s").execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(true));
assertThat(healthResponse.getStatus(), equalTo(ClusterHealthStatus.RED));
assertThat(healthResponse.getIndices().isEmpty(), equalTo(true));
logger.info("--> running cluster wide health");
healthResponse = client().admin().cluster().prepareHealth().setWaitForGreenStatus().setTimeout("10s").execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
assertThat(healthResponse.getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(healthResponse.getIndices().isEmpty(), equalTo(true));
logger.info("--> Creating index test1 with zero replicas");
createIndex("test1");
logger.info("--> running cluster health on an index that does exists");
healthResponse = client().admin().cluster().prepareHealth("test1")
.setWaitForGreenStatus().setTimeout("10s").execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
assertThat(healthResponse.getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(healthResponse.getIndices().get("test1").getStatus(), equalTo(ClusterHealthStatus.GREEN));
logger.info("--> running cluster health on an index that does exists and an index that doesn't exists");
healthResponse = client().admin().cluster().prepareHealth("test1", "test2")
.setWaitForYellowStatus().setTimeout("1s").execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(true));
assertThat(healthResponse.getStatus(), equalTo(ClusterHealthStatus.RED));
assertThat(healthResponse.getIndices().get("test1").getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(healthResponse.getIndices().size(), equalTo(1));
}
@Test
public void testHealthWithClosedIndices() throws Exception {
var table_1 = getFqn("t1");
execute("create table t1 (id int) with (number_of_replicas = 0)");
var table_2 = getFqn("t2");
execute("create table t2 (id int) with (number_of_replicas = 0)");
waitNoPendingTasksOnAll();
execute("alter table t2 close");
var table_3 = getFqn("t3");
execute("create table t3 (id int) with (number_of_replicas = 20)");
waitNoPendingTasksOnAll();
execute("alter table t3 close");
{
ClusterHealthResponse response = client().admin().cluster().prepareHealth()
.setWaitForNoRelocatingShards(true)
.setWaitForNoInitializingShards(true)
.setWaitForYellowStatus()
.execute().actionGet(REQUEST_TIMEOUT);
assertThat(response.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
assertThat(response.isTimedOut(), equalTo(false));
assertThat(response.getIndices().size(), equalTo(3));
assertThat(response.getIndices().get(table_1).getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(response.getIndices().get(table_2).getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(response.getIndices().get(table_3).getStatus(), equalTo(ClusterHealthStatus.YELLOW));
}
{
ClusterHealthResponse response = client().admin().cluster().prepareHealth(table_1)
.execute().actionGet(REQUEST_TIMEOUT);
assertThat(response.getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(response.isTimedOut(), equalTo(false));
assertThat(response.getIndices().size(), equalTo(1));
assertThat(response.getIndices().get(table_1).getStatus(), equalTo(ClusterHealthStatus.GREEN));
}
{
ClusterHealthResponse response = client().admin().cluster().prepareHealth(table_2)
.execute().actionGet(REQUEST_TIMEOUT);
assertThat(response.getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(response.isTimedOut(), equalTo(false));
assertThat(response.getIndices().size(), equalTo(1));
assertThat(response.getIndices().get(table_2).getStatus(), equalTo(ClusterHealthStatus.GREEN));
}
{
ClusterHealthResponse response = client().admin().cluster().prepareHealth(table_3)
.execute().actionGet(REQUEST_TIMEOUT);
assertThat(response.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
assertThat(response.isTimedOut(), equalTo(false));
assertThat(response.getIndices().size(), equalTo(1));
assertThat(response.getIndices().get(table_3).getStatus(), equalTo(ClusterHealthStatus.YELLOW));
}
// CrateDB does not support altering a closed table, so we must use the ES API here
assertAcked(client().admin().indices().prepareUpdateSettings(table_3)
.setSettings(Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, numberOfReplicas())
.build()));
{
ClusterHealthResponse response = client().admin().cluster().prepareHealth()
.setWaitForGreenStatus()
.execute().actionGet(REQUEST_TIMEOUT);
assertThat(response.getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(response.isTimedOut(), equalTo(false));
assertThat(response.getIndices().size(), equalTo(3));
assertThat(response.getIndices().get(table_1).getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(response.getIndices().get(table_2).getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(response.getIndices().get(table_3).getStatus(), equalTo(ClusterHealthStatus.GREEN));
}
}
@Test
public void testHealthOnIndexCreation() throws Exception {
final AtomicBoolean finished = new AtomicBoolean(false);
Thread clusterHealthThread = new Thread() {
@Override
public void run() {
while (finished.get() == false) {
ClusterHealthResponse health = client().admin().cluster().prepareHealth().get();
assertThat(health.getStatus(), not(equalTo(ClusterHealthStatus.RED)));
}
}
};
clusterHealthThread.start();
for (int i = 0; i < 10; i++) {
createIndex("test" + i);
}
finished.set(true);
clusterHealthThread.join();
}
@Test
public void testWaitForEventsRetriesIfOtherConditionsNotMet() throws Exception {
final ActionFuture<ClusterHealthResponse> healthResponseFuture
= client().admin().cluster().prepareHealth("index").setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute();
final AtomicBoolean keepSubmittingTasks = new AtomicBoolean(true);
final ClusterService clusterService = internalCluster().getInstance(ClusterService.class, internalCluster().getMasterName());
clusterService.submitStateUpdateTask("looping task", new ClusterStateUpdateTask(Priority.LOW) {
@Override
public ClusterState execute(ClusterState currentState) {
return currentState;
}
@Override
public void onFailure(String source, Exception e) {
throw new AssertionError(source, e);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
if (keepSubmittingTasks.get()) {
clusterService.submitStateUpdateTask("looping task", this);
}
}
});
createIndex("index");
assertFalse(client().admin().cluster().prepareHealth("index").setWaitForGreenStatus().get().isTimedOut());
// at this point the original health response should not have returned: there was never a point where the index was green AND
// the master had processed all pending tasks above LANGUID priority.
assertFalse(healthResponseFuture.isDone());
keepSubmittingTasks.set(false);
assertFalse(healthResponseFuture.get().isTimedOut());
}
}
|
server/src/test/java/org/elasticsearch/cluster/ClusterHealthIT.java
|
/*
* 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.cluster;
import io.crate.integrationtests.SQLTransportIntegrationTest;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.settings.Settings;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicBoolean;
import static io.crate.testing.SQLTransportExecutor.REQUEST_TIMEOUT;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
public class ClusterHealthIT extends SQLTransportIntegrationTest {
@Test
public void testSimpleLocalHealth() {
execute("create table test (id int) with (number_of_replicas = 0)");
ensureGreen(); // master should think it's green now.
for (final String node : internalCluster().getNodeNames()) {
// a very high time out, which should never fire due to the local flag
logger.info("--> getting cluster health on [{}]", node);
final ClusterHealthResponse health = client(node).admin().cluster().prepareHealth().setLocal(true)
.setWaitForEvents(Priority.LANGUID).setTimeout("30s").execute().actionGet(REQUEST_TIMEOUT);
logger.info("--> got cluster health on [{}]", node);
assertFalse("timed out on " + node, health.isTimedOut());
assertThat("health status on " + node, health.getStatus(), equalTo(ClusterHealthStatus.GREEN));
}
}
@Test
public void testHealth() {
logger.info("--> running cluster health on an index that does not exists");
ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth("test1")
.setWaitForYellowStatus().setTimeout("1s").execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(true));
assertThat(healthResponse.getStatus(), equalTo(ClusterHealthStatus.RED));
assertThat(healthResponse.getIndices().isEmpty(), equalTo(true));
logger.info("--> running cluster wide health");
healthResponse = client().admin().cluster().prepareHealth().setWaitForGreenStatus().setTimeout("10s").execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
assertThat(healthResponse.getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(healthResponse.getIndices().isEmpty(), equalTo(true));
logger.info("--> Creating index test1 with zero replicas");
createIndex("test1");
logger.info("--> running cluster health on an index that does exists");
healthResponse = client().admin().cluster().prepareHealth("test1")
.setWaitForGreenStatus().setTimeout("10s").execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
assertThat(healthResponse.getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(healthResponse.getIndices().get("test1").getStatus(), equalTo(ClusterHealthStatus.GREEN));
logger.info("--> running cluster health on an index that does exists and an index that doesn't exists");
healthResponse = client().admin().cluster().prepareHealth("test1", "test2")
.setWaitForYellowStatus().setTimeout("1s").execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(true));
assertThat(healthResponse.getStatus(), equalTo(ClusterHealthStatus.RED));
assertThat(healthResponse.getIndices().get("test1").getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(healthResponse.getIndices().size(), equalTo(1));
}
@Test
public void testHealthWithClosedIndices() {
var table_1 = getFqn("t1");
execute("create table t1 (id int) with (number_of_replicas = 0)");
var table_2 = getFqn("t2");
execute("create table t2 (id int) with (number_of_replicas = 0)");
execute("alter table t2 close");
var table_3 = getFqn("t3");
execute("create table t3 (id int) with (number_of_replicas = 20)");
execute("alter table t3 close");
{
ClusterHealthResponse response = client().admin().cluster().prepareHealth()
.setWaitForNoRelocatingShards(true)
.setWaitForNoInitializingShards(true)
.setWaitForYellowStatus()
.execute().actionGet(REQUEST_TIMEOUT);
assertThat(response.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
assertThat(response.isTimedOut(), equalTo(false));
assertThat(response.getIndices().size(), equalTo(3));
assertThat(response.getIndices().get(table_1).getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(response.getIndices().get(table_2).getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(response.getIndices().get(table_3).getStatus(), equalTo(ClusterHealthStatus.YELLOW));
}
{
ClusterHealthResponse response = client().admin().cluster().prepareHealth(table_1)
.execute().actionGet(REQUEST_TIMEOUT);
assertThat(response.getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(response.isTimedOut(), equalTo(false));
assertThat(response.getIndices().size(), equalTo(1));
assertThat(response.getIndices().get(table_1).getStatus(), equalTo(ClusterHealthStatus.GREEN));
}
{
ClusterHealthResponse response = client().admin().cluster().prepareHealth(table_2)
.execute().actionGet(REQUEST_TIMEOUT);
assertThat(response.getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(response.isTimedOut(), equalTo(false));
assertThat(response.getIndices().size(), equalTo(1));
assertThat(response.getIndices().get(table_2).getStatus(), equalTo(ClusterHealthStatus.GREEN));
}
{
ClusterHealthResponse response = client().admin().cluster().prepareHealth(table_3)
.execute().actionGet(REQUEST_TIMEOUT);
assertThat(response.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
assertThat(response.isTimedOut(), equalTo(false));
assertThat(response.getIndices().size(), equalTo(1));
assertThat(response.getIndices().get(table_3).getStatus(), equalTo(ClusterHealthStatus.YELLOW));
}
// CrateDB does not support altering a closed table, so we must use the ES API here
assertAcked(client().admin().indices().prepareUpdateSettings(table_3)
.setSettings(Settings.builder()
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, numberOfReplicas())
.build()));
{
ClusterHealthResponse response = client().admin().cluster().prepareHealth()
.setWaitForGreenStatus()
.execute().actionGet(REQUEST_TIMEOUT);
assertThat(response.getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(response.isTimedOut(), equalTo(false));
assertThat(response.getIndices().size(), equalTo(3));
assertThat(response.getIndices().get(table_1).getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(response.getIndices().get(table_2).getStatus(), equalTo(ClusterHealthStatus.GREEN));
assertThat(response.getIndices().get(table_3).getStatus(), equalTo(ClusterHealthStatus.GREEN));
}
}
@Test
public void testHealthOnIndexCreation() throws Exception {
final AtomicBoolean finished = new AtomicBoolean(false);
Thread clusterHealthThread = new Thread() {
@Override
public void run() {
while (finished.get() == false) {
ClusterHealthResponse health = client().admin().cluster().prepareHealth().get();
assertThat(health.getStatus(), not(equalTo(ClusterHealthStatus.RED)));
}
}
};
clusterHealthThread.start();
for (int i = 0; i < 10; i++) {
createIndex("test" + i);
}
finished.set(true);
clusterHealthThread.join();
}
@Test
public void testWaitForEventsRetriesIfOtherConditionsNotMet() throws Exception {
final ActionFuture<ClusterHealthResponse> healthResponseFuture
= client().admin().cluster().prepareHealth("index").setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute();
final AtomicBoolean keepSubmittingTasks = new AtomicBoolean(true);
final ClusterService clusterService = internalCluster().getInstance(ClusterService.class, internalCluster().getMasterName());
clusterService.submitStateUpdateTask("looping task", new ClusterStateUpdateTask(Priority.LOW) {
@Override
public ClusterState execute(ClusterState currentState) {
return currentState;
}
@Override
public void onFailure(String source, Exception e) {
throw new AssertionError(source, e);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
if (keepSubmittingTasks.get()) {
clusterService.submitStateUpdateTask("looping task", this);
}
}
});
createIndex("index");
assertFalse(client().admin().cluster().prepareHealth("index").setWaitForGreenStatus().get().isTimedOut());
// at this point the original health response should not have returned: there was never a point where the index was green AND
// the master had processed all pending tasks above LANGUID priority.
assertFalse(healthResponseFuture.isDone());
keepSubmittingTasks.set(false);
assertFalse(healthResponseFuture.get().isTimedOut());
}
}
|
Fix flaky testHealthWithClosedIndices
It could have been the case that the closing & starting of a shard from
the CREATE and ALTER .. CLOSE statements interferred with each other
because these actions are asynchronously triggered by cluster state
change events resulting from the CREATE TABLE and ALTER TABLE
statements.
this adds some `waitNoPendingTasksOnAll` calls to ensure that there are
no pending operations from the CREATE TABLE statement running before
triggering the close operation.
The issue can be produced quite reliably with the following test case:
for (int i = 0; i < 5; i++) {
logger.info("XXX BEFORE create table");
execute("create table t" + i + " (id int) with (number_of_replicas = 5)");
logger.info("XXX BEFORE close table");
execute("alter table t" + i + " close");
logger.info("XXX BEFORE open table");
execute("alter table t" + i + " open");
logger.info("XXX BEFORE drop table");
execute("drop table t" + i);
}
|
server/src/test/java/org/elasticsearch/cluster/ClusterHealthIT.java
|
Fix flaky testHealthWithClosedIndices
|
|
Java
|
apache-2.0
|
0602d7510fb3017a196286041713ce3c49336696
| 0
|
karlmortensen/autopsy,eXcomm/autopsy,millmanorama/autopsy,wschaeferB/autopsy,dgrove727/autopsy,rcordovano/autopsy,karlmortensen/autopsy,esaunders/autopsy,eXcomm/autopsy,sidheshenator/autopsy,sidheshenator/autopsy,raman-bt/autopsy,mhmdfy/autopsy,maxrp/autopsy,wschaeferB/autopsy,esaunders/autopsy,APriestman/autopsy,sidheshenator/autopsy,eXcomm/autopsy,sidheshenator/autopsy,APriestman/autopsy,millmanorama/autopsy,dgrove727/autopsy,raman-bt/autopsy,APriestman/autopsy,karlmortensen/autopsy,rcordovano/autopsy,rcordovano/autopsy,APriestman/autopsy,APriestman/autopsy,narfindustries/autopsy,rcordovano/autopsy,wschaeferB/autopsy,esaunders/autopsy,maxrp/autopsy,rcordovano/autopsy,dgrove727/autopsy,APriestman/autopsy,raman-bt/autopsy,millmanorama/autopsy,maxrp/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,raman-bt/autopsy,esaunders/autopsy,rcordovano/autopsy,mhmdfy/autopsy,millmanorama/autopsy,APriestman/autopsy,mhmdfy/autopsy,eXcomm/autopsy,narfindustries/autopsy,raman-bt/autopsy,raman-bt/autopsy,narfindustries/autopsy,maxrp/autopsy,esaunders/autopsy,mhmdfy/autopsy,raman-bt/autopsy,karlmortensen/autopsy
|
/*
* Autopsy Forensic Browser
*
* Copyright 2011 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.keywordsearch;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.TermsResponse;
import org.apache.solr.client.solrj.response.TermsResponse.Term;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE;
import org.sleuthkit.datamodel.BlackboardAttribute;
import org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE;
import org.sleuthkit.datamodel.TskException;
public class TermComponentQuery implements KeywordSearchQuery {
private static final int TERMS_UNLIMITED = -1;
//corresponds to field in Solr schema, analyzed with white-space tokenizer only
private static final String TERMS_SEARCH_FIELD = Server.Schema.CONTENT_WS.toString();
private static final String TERMS_HANDLER = "/terms";
private static final int TERMS_TIMEOUT = 90 * 1000; //in ms
private static Logger logger = Logger.getLogger(TermComponentQuery.class.getName());
private String termsQuery;
private String queryEscaped;
private boolean isEscaped;
private List<Term> terms;
private Keyword keywordQuery = null;
private KeywordQueryFilter filter = null;
private String field = null;
public TermComponentQuery(Keyword keywordQuery) {
this.keywordQuery = keywordQuery;
this.termsQuery = keywordQuery.getQuery();
this.queryEscaped = termsQuery;
isEscaped = false;
terms = null;
}
@Override
public void setFilter(KeywordQueryFilter filter) {
this.filter = filter;
}
@Override
public void setField(String field) {
this.field = field;
}
@Override
public void escape() {
queryEscaped = Pattern.quote(termsQuery);
isEscaped = true;
}
@Override
public boolean validate() {
if (queryEscaped.equals("")) {
return false;
}
boolean valid = true;
try {
Pattern.compile(queryEscaped);
} catch (PatternSyntaxException ex1) {
valid = false;
} catch (IllegalArgumentException ex2) {
valid = false;
}
return valid;
}
@Override
public boolean isEscaped() {
return isEscaped;
}
@Override
public boolean isLiteral() {
return false;
}
/*
* helper method to create a Solr terms component query
*/
protected SolrQuery createQuery() {
final SolrQuery q = new SolrQuery();
q.setQueryType(TERMS_HANDLER);
q.setTerms(true);
q.setTermsLimit(TERMS_UNLIMITED);
q.setTermsRegexFlag("case_insensitive");
//q.setTermsLimit(200);
//q.setTermsRegexFlag(regexFlag);
//q.setTermsRaw(true);
q.setTermsRegex(queryEscaped);
q.addTermsField(TERMS_SEARCH_FIELD);
q.setTimeAllowed(TERMS_TIMEOUT);
return q;
}
/*
* execute query and return terms, helper method
*/
protected List<Term> executeQuery(SolrQuery q) throws NoOpenCoreException {
List<Term> termsCol = null;
try {
Server solrServer = KeywordSearch.getServer();
TermsResponse tr = solrServer.queryTerms(q);
termsCol = tr.getTerms(TERMS_SEARCH_FIELD);
return termsCol;
} catch (SolrServerException ex) {
logger.log(Level.WARNING, "Error executing the regex terms query: " + termsQuery, ex);
return null; //no need to create result view, just display error dialog
}
}
@Override
public String getEscapedQueryString() {
return this.queryEscaped;
}
@Override
public String getQueryString() {
return this.termsQuery;
}
@Override
public Collection<Term> getTerms() {
return terms;
}
@Override
public KeywordWriteResult writeToBlackBoard(String termHit, AbstractFile newFsHit, String snippet, String listName) {
final String MODULE_NAME = KeywordSearchIngestService.MODULE_NAME;
//there is match actually in this file, create artifact only then
BlackboardArtifact bba = null;
KeywordWriteResult writeResult = null;
Collection<BlackboardAttribute> attributes = new ArrayList<BlackboardAttribute>();
try {
bba = newFsHit.newArtifact(ARTIFACT_TYPE.TSK_KEYWORD_HIT);
writeResult = new KeywordWriteResult(bba);
} catch (Exception e) {
logger.log(Level.WARNING, "Error adding bb artifact for keyword hit", e);
return null;
}
//regex match
attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD.getTypeID(), MODULE_NAME, "", termHit));
//list
if (listName == null) {
listName = "";
}
attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID(), MODULE_NAME, "", listName));
//preview
if (snippet != null)
attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW.getTypeID(), MODULE_NAME, "", snippet));
//regex keyword
attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_REGEXP.getTypeID(), MODULE_NAME, "", termsQuery));
//selector TODO move to general info artifact
/*
if (keywordQuery != null) {
BlackboardAttribute.ATTRIBUTE_TYPE selType = keywordQuery.getType();
if (selType != null) {
BlackboardAttribute selAttr = new BlackboardAttribute(selType.getTypeID(), MODULE_NAME, "", regexMatch);
attributes.add(selAttr);
}
} */
try {
bba.addAttributes(attributes);
writeResult.add(attributes);
return writeResult;
} catch (TskException e) {
logger.log(Level.WARNING, "Error adding bb attributes for terms search artifact", e);
}
return null;
}
@Override
public Map<String, List<ContentHit>> performQuery() throws NoOpenCoreException {
Map<String, List<ContentHit>> results = new HashMap<String, List<ContentHit>>();
final SolrQuery q = createQuery();
terms = executeQuery(q);
for (Term term : terms) {
final String termStr = KeywordSearchUtil.escapeLuceneQuery(term.getTerm(), true, false);
LuceneQuery filesQuery = new LuceneQuery(termStr);
filesQuery.setField(TERMS_SEARCH_FIELD);
if (filter != null) {
filesQuery.setFilter(filter);
}
try {
Map<String, List<ContentHit>> subResults = filesQuery.performQuery();
Set<ContentHit> filesResults = new HashSet<ContentHit>();
for (String key : subResults.keySet()) {
filesResults.addAll(subResults.get(key));
}
results.put(term.getTerm(), new ArrayList<ContentHit>(filesResults));
} catch (NoOpenCoreException e) {
logger.log(Level.WARNING, "Error executing Solr query,", e);
throw e;
} catch (RuntimeException e) {
logger.log(Level.WARNING, "Error executing Solr query,", e);
}
}
return results;
}
}
|
KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/TermComponentQuery.java
|
/*
* Autopsy Forensic Browser
*
* Copyright 2011 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.keywordsearch;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.TermsResponse;
import org.apache.solr.client.solrj.response.TermsResponse.Term;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE;
import org.sleuthkit.datamodel.BlackboardAttribute;
import org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE;
import org.sleuthkit.datamodel.TskException;
public class TermComponentQuery implements KeywordSearchQuery {
private static final int TERMS_UNLIMITED = -1;
//corresponds to field in Solr schema, analyzed with white-space tokenizer only
private static final String TERMS_SEARCH_FIELD = Server.Schema.CONTENT_WS.toString();
private static final String TERMS_HANDLER = "/terms";
private static final int TERMS_TIMEOUT = 90 * 1000; //in ms
private static Logger logger = Logger.getLogger(TermComponentQuery.class.getName());
private String termsQuery;
private String queryEscaped;
private boolean isEscaped;
private List<Term> terms;
private Keyword keywordQuery = null;
private KeywordQueryFilter filter = null;
private String field = null;
public TermComponentQuery(Keyword keywordQuery) {
this.keywordQuery = keywordQuery;
this.termsQuery = keywordQuery.getQuery();
this.queryEscaped = termsQuery;
isEscaped = false;
terms = null;
}
@Override
public void setFilter(KeywordQueryFilter filter) {
this.filter = filter;
}
@Override
public void setField(String field) {
this.field = field;
}
@Override
public void escape() {
queryEscaped = Pattern.quote(termsQuery);
isEscaped = true;
}
@Override
public boolean validate() {
if (queryEscaped.equals("")) {
return false;
}
boolean valid = true;
try {
Pattern.compile(queryEscaped);
} catch (PatternSyntaxException ex1) {
valid = false;
} catch (IllegalArgumentException ex2) {
valid = false;
}
return valid;
}
@Override
public boolean isEscaped() {
return isEscaped;
}
@Override
public boolean isLiteral() {
return false;
}
/*
* helper method to create a Solr terms component query
*/
protected SolrQuery createQuery() {
final SolrQuery q = new SolrQuery();
q.setQueryType(TERMS_HANDLER);
q.setTerms(true);
q.setTermsLimit(TERMS_UNLIMITED);
q.setTermsRegexFlag("case_insensitive");
//q.setTermsLimit(200);
//q.setTermsRegexFlag(regexFlag);
//q.setTermsRaw(true);
q.setTermsRegex(queryEscaped);
q.addTermsField(TERMS_SEARCH_FIELD);
q.setTimeAllowed(TERMS_TIMEOUT);
return q;
}
/*
* execute query and return terms, helper method
*/
protected List<Term> executeQuery(SolrQuery q) throws NoOpenCoreException {
List<Term> termsCol = null;
try {
Server solrServer = KeywordSearch.getServer();
TermsResponse tr = solrServer.queryTerms(q);
termsCol = tr.getTerms(TERMS_SEARCH_FIELD);
return termsCol;
} catch (SolrServerException ex) {
logger.log(Level.WARNING, "Error executing the regex terms query: " + termsQuery, ex);
return null; //no need to create result view, just display error dialog
}
}
@Override
public String getEscapedQueryString() {
return this.queryEscaped;
}
@Override
public String getQueryString() {
return this.termsQuery;
}
@Override
public Collection<Term> getTerms() {
return terms;
}
@Override
public KeywordWriteResult writeToBlackBoard(String termHit, AbstractFile newFsHit, String snippet, String listName) {
final String MODULE_NAME = KeywordSearchIngestService.MODULE_NAME;
if (snippet == null || snippet.equals("")) {
return null;
}
//there is match actually in this file, create artifact only then
BlackboardArtifact bba = null;
KeywordWriteResult writeResult = null;
Collection<BlackboardAttribute> attributes = new ArrayList<BlackboardAttribute>();
try {
bba = newFsHit.newArtifact(ARTIFACT_TYPE.TSK_KEYWORD_HIT);
writeResult = new KeywordWriteResult(bba);
} catch (Exception e) {
logger.log(Level.WARNING, "Error adding bb artifact for keyword hit", e);
return null;
}
//regex match
attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD.getTypeID(), MODULE_NAME, "", termHit));
//list
if (listName == null) {
listName = "";
}
attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID(), MODULE_NAME, "", listName));
//preview
attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW.getTypeID(), MODULE_NAME, "", snippet));
//regex keyword
attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_REGEXP.getTypeID(), MODULE_NAME, "", termsQuery));
//selector TODO move to general info artifact
/*
if (keywordQuery != null) {
BlackboardAttribute.ATTRIBUTE_TYPE selType = keywordQuery.getType();
if (selType != null) {
BlackboardAttribute selAttr = new BlackboardAttribute(selType.getTypeID(), MODULE_NAME, "", regexMatch);
attributes.add(selAttr);
}
} */
try {
bba.addAttributes(attributes);
writeResult.add(attributes);
return writeResult;
} catch (TskException e) {
logger.log(Level.WARNING, "Error adding bb attributes for terms search artifact", e);
}
return null;
}
@Override
public Map<String, List<ContentHit>> performQuery() throws NoOpenCoreException {
Map<String, List<ContentHit>> results = new HashMap<String, List<ContentHit>>();
final SolrQuery q = createQuery();
terms = executeQuery(q);
for (Term term : terms) {
final String termStr = KeywordSearchUtil.escapeLuceneQuery(term.getTerm(), true, false);
LuceneQuery filesQuery = new LuceneQuery(termStr);
filesQuery.setField(TERMS_SEARCH_FIELD);
if (filter != null) {
filesQuery.setFilter(filter);
}
try {
Map<String, List<ContentHit>> subResults = filesQuery.performQuery();
Set<ContentHit> filesResults = new HashSet<ContentHit>();
for (String key : subResults.keySet()) {
filesResults.addAll(subResults.get(key));
}
results.put(term.getTerm(), new ArrayList<ContentHit>(filesResults));
} catch (NoOpenCoreException e) {
logger.log(Level.WARNING, "Error executing Solr query,", e);
throw e;
} catch (RuntimeException e) {
logger.log(Level.WARNING, "Error executing Solr query,", e);
}
}
return results;
}
}
|
Write regex search results to bb even if snippet is blank
|
KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/TermComponentQuery.java
|
Write regex search results to bb even if snippet is blank
|
|
Java
|
bsd-2-clause
|
cb963f71390edffaee346f09e46c06d240be224f
| 0
|
afester/RichTextFX,afester/RichTextFX,FXMisc/RichTextFX,FXMisc/RichTextFX
|
package org.fxmisc.richtext;
import static org.reactfx.EventStreams.*;
import static org.reactfx.util.Tuples.*;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.IntSupplier;
import java.util.function.IntUnaryOperator;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import javafx.application.ConditionalFeature;
import javafx.application.Platform;
import javafx.beans.NamedArg;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableSet;
import javafx.css.CssMetaData;
import javafx.css.PseudoClass;
import javafx.css.StyleConverter;
import javafx.css.Styleable;
import javafx.css.StyleableObjectProperty;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.BoundingBox;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.IndexRange;
import javafx.scene.input.InputMethodEvent;
import javafx.scene.input.InputMethodRequests;
import javafx.scene.input.InputMethodTextRun;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.text.TextFlow;
import org.fxmisc.flowless.Cell;
import org.fxmisc.flowless.VirtualFlow;
import org.fxmisc.flowless.VirtualFlowHit;
import org.fxmisc.flowless.Virtualized;
import org.fxmisc.flowless.VirtualizedScrollPane;
import org.fxmisc.richtext.model.Codec;
import org.fxmisc.richtext.model.EditableStyledDocument;
import org.fxmisc.richtext.model.GenericEditableStyledDocument;
import org.fxmisc.richtext.model.Paragraph;
import org.fxmisc.richtext.model.ReadOnlyStyledDocument;
import org.fxmisc.richtext.model.PlainTextChange;
import org.fxmisc.richtext.model.Replacement;
import org.fxmisc.richtext.model.RichTextChange;
import org.fxmisc.richtext.model.StyleSpans;
import org.fxmisc.richtext.model.StyledDocument;
import org.fxmisc.richtext.model.StyledSegment;
import org.fxmisc.richtext.model.TextOps;
import org.fxmisc.richtext.model.TwoDimensional;
import org.fxmisc.richtext.model.TwoLevelNavigator;
import org.fxmisc.richtext.event.MouseOverTextEvent;
import org.fxmisc.richtext.util.SubscribeableContentsObsSet;
import org.fxmisc.richtext.util.UndoUtils;
import org.fxmisc.undo.UndoManager;
import org.reactfx.EventStream;
import org.reactfx.EventStreams;
import org.reactfx.Guard;
import org.reactfx.Subscription;
import org.reactfx.Suspendable;
import org.reactfx.SuspendableEventStream;
import org.reactfx.SuspendableNo;
import org.reactfx.collection.LiveList;
import org.reactfx.collection.SuspendableList;
import org.reactfx.util.Tuple2;
import org.reactfx.value.Val;
import org.reactfx.value.Var;
/**
* Text editing control that renders and edits a {@link EditableStyledDocument}.
*
* Accepts user input (keyboard, mouse) and provides API to assign style to text ranges. It is suitable for
* syntax highlighting and rich-text editors.
*
* <h3>Adding Scrollbars to the Area</h3>
*
* <p>By default, scroll bars do not appear when the content spans outside of the viewport.
* To add scroll bars, the area needs to be wrapped in a {@link VirtualizedScrollPane}. For example, </p>
* <pre><code>
* // shows area without scroll bars
* InlineCssTextArea area = new InlineCssTextArea();
*
* // add scroll bars that will display as needed
* VirtualizedScrollPane<InlineCssTextArea> vsPane = new VirtualizedScrollPane<>(area);
*
* Parent parent = // creation code
* parent.getChildren().add(vsPane)
* </code></pre>
*
* <h3>Auto-Scrolling to the Caret</h3>
*
* <p>Every time the underlying {@link EditableStyledDocument} changes via user interaction (e.g. typing) through
* the {@code GenericStyledArea}, the area will scroll to insure the caret is kept in view. However, this does not
* occur if changes are done programmatically. For example, let's say the area is displaying the bottom part
* of the area's {@link EditableStyledDocument} and some code changes something in the top part of the document
* that is not currently visible. If there is no call to {@link #requestFollowCaret()} at the end of that code,
* the area will not auto-scroll to that section of the document. The change will occur, and the user will continue
* to see the bottom part of the document as before. If such a call is there, then the area will scroll
* to the top of the document and no longer display the bottom part of it.</p>
* <p>For example...</p>
* <pre><code>
* // assuming the user is currently seeing the top of the area
*
* // then changing the bottom, currently not visible part of the area...
* int startParIdx = 40;
* int startColPosition = 2;
* int endParIdx = 42;
* int endColPosition = 10;
*
* // ...by itself will not scroll the viewport to where the change occurs
* area.replaceText(startParIdx, startColPosition, endParIdx, endColPosition, "replacement text");
*
* // adding this line after the last modification to the area will cause the viewport to scroll to that change
* // leaving the following line out will leave the viewport unaffected and the user will not notice any difference
* area.requestFollowCaret();
* </code></pre>
*
* <p>Additionally, when overriding the default user-interaction behavior, remember to include a call
* to {@link #requestFollowCaret()}.</p>
*
* <h3>Setting the area's {@link UndoManager}</h3>
*
* <p>
* The default UndoManager can undo/redo either {@link PlainTextChange}s or {@link RichTextChange}s. To create
* your own specialized version that may use changes different than these (or a combination of these changes
* with others), create them using the convenient factory methods in {@link UndoUtils}.
* </p>
*
* <h3>Overriding default keyboard behavior</h3>
*
* {@code GenericStyledArea} uses {@link javafx.scene.input.KeyEvent#KEY_TYPED KEY_TYPED} to handle ordinary
* character input and {@link javafx.scene.input.KeyEvent#KEY_PRESSED KEY_PRESSED} to handle control key
* combinations (including Enter and Tab). To add or override some keyboard
* shortcuts, while keeping the rest in place, you would combine the default
* event handler with a new one that adds or overrides some of the default
* key combinations.
* <p>
* For example, this is how to bind {@code Ctrl+S} to the {@code save()} operation:
* </p>
* <pre><code>
* import static javafx.scene.input.KeyCode.*;
* import static javafx.scene.input.KeyCombination.*;
* import static org.fxmisc.wellbehaved.event.EventPattern.*;
* import static org.fxmisc.wellbehaved.event.InputMap.*;
*
* import org.fxmisc.wellbehaved.event.Nodes;
*
* // installs the following consume InputMap,
* // so that a CTRL+S event saves the document and consumes the event
* Nodes.addInputMap(area, consume(keyPressed(S, CONTROL_DOWN), event -> save()));
* </code></pre>
*
* <h3>Overriding default mouse behavior</h3>
*
* The area's default mouse behavior properly handles auto-scrolling and dragging the selected text to a new location.
* As such, some parts cannot be partially overridden without it affecting other behavior.
*
* <p>The following lists either {@link org.fxmisc.wellbehaved.event.EventPattern}s that cannot be
* overridden without negatively affecting the default mouse behavior or describe how to safely override things
* in a special way without disrupting the auto scroll behavior.</p>
* <ul>
* <li>
* <em>First (1 click count) Primary Button Mouse Pressed Events:</em>
* (<code>EventPattern.mousePressed(MouseButton.PRIMARY).onlyIf(e -> e.getClickCount() == 1)</code>).
* Do not override. Instead, use {@link #onOutsideSelectionMousePressed},
* {@link #onInsideSelectionMousePressReleased}, or see next item.
* </li>
* <li>(
* <em>All Other Mouse Pressed Events (e.g., Primary with 2+ click count):</em>
* Aside from hiding the context menu if it is showing (use {@link #hideContextMenu()} some((where in your
* overriding InputMap to maintain this behavior), these can be safely overridden via any of the
* {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate InputMapTemplate's factory methods} or
* {@link org.fxmisc.wellbehaved.event.InputMap InputMap's factory methods}.
* </li>
* <li>
* <em>Primary-Button-only Mouse Drag Detection Events:</em>
* (<code>EventPattern.eventType(MouseEvent.DRAG_DETECTED).onlyIf(e -> e.getButton() == MouseButton.PRIMARY && !e.isMiddleButtonDown() && !e.isSecondaryButtonDown())</code>).
* Do not override. Instead, use {@link #onNewSelectionDrag} or {@link #onSelectionDrag}.
* </li>
* <li>
* <em>Primary-Button-only Mouse Drag Events:</em>
* (<code>EventPattern.mouseDragged().onlyIf(e -> e.getButton() == MouseButton.PRIMARY && !e.isMiddleButtonDown() && !e.isSecondaryButtonDown())</code>)
* Do not override, but see next item.
* </li>
* <li>
* <em>All Other Mouse Drag Events:</em>
* You may safely override other Mouse Drag Events using different
* {@link org.fxmisc.wellbehaved.event.EventPattern}s without affecting default behavior only if
* process InputMaps (
* {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(javafx.event.EventType, BiFunction)},
* {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(org.fxmisc.wellbehaved.event.EventPattern, BiFunction)},
* {@link org.fxmisc.wellbehaved.event.InputMap#process(javafx.event.EventType, Function)}, or
* {@link org.fxmisc.wellbehaved.event.InputMap#process(org.fxmisc.wellbehaved.event.EventPattern, Function)}
* ) are used and {@link org.fxmisc.wellbehaved.event.InputHandler.Result#PROCEED} is returned.
* The area has a "catch all" Mouse Drag InputMap that will auto scroll towards the mouse drag event when it
* occurs outside the bounds of the area and will stop auto scrolling when the mouse event occurs within the
* area. However, this only works if the event is not consumed before the event reaches that InputMap.
* To insure the auto scroll feature is enabled, set {@link #isAutoScrollOnDragDesired()} to true in your
* process InputMap. If the feature is not desired for that specific drag event, set it to false in the
* process InputMap.
* <em>Note: Due to this "catch-all" nature, all Mouse Drag Events are consumed.</em>
* </li>
* <li>
* <em>Primary-Button-only Mouse Released Events:</em>
* (<code>EventPattern.mouseReleased().onlyIf(e -> e.getButton() == MouseButton.PRIMARY && !e.isMiddleButtonDown() && !e.isSecondaryButtonDown())</code>).
* Do not override. Instead, use {@link #onNewSelectionDragFinished}, {@link #onSelectionDropped}, or see next item.
* </li>
* <li>
* <em>All other Mouse Released Events:</em>
* You may override other Mouse Released Events using different
* {@link org.fxmisc.wellbehaved.event.EventPattern}s without affecting default behavior only if
* process InputMaps (
* {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(javafx.event.EventType, BiFunction)},
* {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(org.fxmisc.wellbehaved.event.EventPattern, BiFunction)},
* {@link org.fxmisc.wellbehaved.event.InputMap#process(javafx.event.EventType, Function)}, or
* {@link org.fxmisc.wellbehaved.event.InputMap#process(org.fxmisc.wellbehaved.event.EventPattern, Function)}
* ) are used and {@link org.fxmisc.wellbehaved.event.InputHandler.Result#PROCEED} is returned.
* The area has a "catch-all" InputMap that will consume all mouse released events and stop auto scroll if it
* was scrolling. However, this only works if the event is not consumed before the event reaches that InputMap.
* <em>Note: Due to this "catch-all" nature, all Mouse Released Events are consumed.</em>
* </li>
* </ul>
*
* <h3>CSS, Style Classes, and Pseudo Classes</h3>
* <p>
* Refer to the <a href="https://github.com/FXMisc/RichTextFX/wiki/RichTextFX-CSS-Reference-Guide">
* RichTextFX CSS Reference Guide
* </a>.
* </p>
*
* <h3>Area Actions and Other Operations</h3>
* <p>
* To distinguish the actual operations one can do on this area from the boilerplate methods
* within this area (e.g. properties and their getters/setters, etc.), look at the interfaces
* this area implements. Each lists and documents methods that fall under that category.
* </p>
* <p>
* To update multiple portions of the area's underlying document in one call, see {@link #createMultiChange()}.
* </p>
*
* <h3>Calculating a Position Within the Area</h3>
* <p>
* To calculate a position or index within the area, read through the javadoc of
* {@link org.fxmisc.richtext.model.TwoDimensional} and {@link org.fxmisc.richtext.model.TwoDimensional.Bias}.
* Also, read the difference between "position" and "index" in
* {@link org.fxmisc.richtext.model.StyledDocument#getAbsolutePosition(int, int)}.
* </p>
*
* @see EditableStyledDocument
* @see TwoDimensional
* @see org.fxmisc.richtext.model.TwoDimensional.Bias
* @see VirtualFlow
* @see VirtualizedScrollPane
* @see Caret
* @see Selection
* @see CaretSelectionBind
*
* @param <PS> type of style that can be applied to paragraphs (e.g. {@link TextFlow}.
* @param <SEG> type of segment used in {@link Paragraph}. Can be only text (plain or styled) or
* a type that combines text and other {@link Node}s.
* @param <S> type of style that can be applied to a segment.
*/
public class GenericStyledArea<PS, SEG, S> extends Region
implements
TextEditingArea<PS, SEG, S>,
EditActions<PS, SEG, S>,
ClipboardActions<PS, SEG, S>,
NavigationActions<PS, SEG, S>,
StyleActions<PS, S>,
UndoActions,
ViewActions<PS, SEG, S>,
TwoDimensional,
Virtualized {
/**
* Index range [0, 0).
*/
public static final IndexRange EMPTY_RANGE = new IndexRange(0, 0);
private static final PseudoClass READ_ONLY = PseudoClass.getPseudoClass("readonly");
private static final PseudoClass HAS_CARET = PseudoClass.getPseudoClass("has-caret");
private static final PseudoClass FIRST_PAR = PseudoClass.getPseudoClass("first-paragraph");
private static final PseudoClass LAST_PAR = PseudoClass.getPseudoClass("last-paragraph");
/* ********************************************************************** *
* *
* Properties *
* *
* Properties affect behavior and/or appearance of this control. *
* *
* They are readable and writable by the client code and never change by *
* other means, i.e. they contain either the default value or the value *
* set by the client code. *
* *
* ********************************************************************** */
/**
* Text color for highlighted text.
*/
private final StyleableObjectProperty<Paint> highlightTextFill
= new CustomStyleableProperty<>(Color.WHITE, "highlightTextFill", this, HIGHLIGHT_TEXT_FILL);
// editable property
private final BooleanProperty editable = new SimpleBooleanProperty(this, "editable", true) {
@Override
protected void invalidated() {
((Region) getBean()).pseudoClassStateChanged(READ_ONLY, !get());
}
};
@Override public final BooleanProperty editableProperty() { return editable; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setEditable(boolean value) { editable.set(value); }
@Override public boolean isEditable() { return editable.get(); }
// wrapText property
private final BooleanProperty wrapText = new SimpleBooleanProperty(this, "wrapText");
@Override public final BooleanProperty wrapTextProperty() { return wrapText; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setWrapText(boolean value) { wrapText.set(value); }
@Override public boolean isWrapText() { return wrapText.get(); }
// undo manager
private UndoManager undoManager;
@Override public UndoManager getUndoManager() { return undoManager; }
/**
* @param undoManager may be null in which case a no op undo manager will be set.
*/
@Override public void setUndoManager(UndoManager undoManager) {
this.undoManager.close();
this.undoManager = undoManager != null ? undoManager : UndoUtils.noOpUndoManager();
}
private Locale textLocale = Locale.getDefault();
/**
* This is used to determine word and sentence breaks while navigating or selecting.
* Override this method if your paragraph or text style accommodates Locales as well.
* @return Locale.getDefault() by default
*/
@Override
public Locale getLocale() { return textLocale; }
public void setLocale( Locale editorLocale ) {
textLocale = editorLocale;
}
private final ObjectProperty<Duration> mouseOverTextDelay = new SimpleObjectProperty<>(null);
@Override public ObjectProperty<Duration> mouseOverTextDelayProperty() { return mouseOverTextDelay; }
private final ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactory = new SimpleObjectProperty<>(null);
@Override public ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactoryProperty() { return paragraphGraphicFactory; }
public void recreateParagraphGraphic( int parNdx ) {
ObjectProperty<IntFunction<? extends Node>> gProp;
gProp = getCell(parNdx).graphicFactoryProperty();
gProp.unbind();
gProp.bind(paragraphGraphicFactoryProperty());
}
public Node getParagraphGraphic( int parNdx ) {
return getCell(parNdx).getGraphic();
}
/**
* This Node is shown to the user, centered over the area, when the area has no text content.
* <br>To customize the placeholder's layout override {@link #configurePlaceholder( Node )}
*/
public final void setPlaceholder(Node value) { setPlaceholder(value,Pos.CENTER); }
public void setPlaceholder(Node value, Pos where) { placeHolderProp.set(value); placeHolderPos = Objects.requireNonNull(where); }
private ObjectProperty<Node> placeHolderProp = new SimpleObjectProperty<>(this, "placeHolder", null);
public final ObjectProperty<Node> placeholderProperty() { return placeHolderProp; }
public final Node getPlaceholder() { return placeHolderProp.get(); }
private Pos placeHolderPos = Pos.CENTER;
private ObjectProperty<ContextMenu> contextMenu = new SimpleObjectProperty<>(null);
@Override public final ObjectProperty<ContextMenu> contextMenuObjectProperty() { return contextMenu; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setContextMenu(ContextMenu menu) { contextMenu.set(menu); }
@Override public ContextMenu getContextMenu() { return contextMenu.get(); }
protected final boolean isContextMenuPresent() { return contextMenu.get() != null; }
private DoubleProperty contextMenuXOffset = new SimpleDoubleProperty(2);
@Override public final DoubleProperty contextMenuXOffsetProperty() { return contextMenuXOffset; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setContextMenuXOffset(double offset) { contextMenuXOffset.set(offset); }
@Override public double getContextMenuXOffset() { return contextMenuXOffset.get(); }
private DoubleProperty contextMenuYOffset = new SimpleDoubleProperty(2);
@Override public final DoubleProperty contextMenuYOffsetProperty() { return contextMenuYOffset; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setContextMenuYOffset(double offset) { contextMenuYOffset.set(offset); }
@Override public double getContextMenuYOffset() { return contextMenuYOffset.get(); }
private final BooleanProperty useInitialStyleForInsertion = new SimpleBooleanProperty();
@Override public BooleanProperty useInitialStyleForInsertionProperty() { return useInitialStyleForInsertion; }
private Optional<Tuple2<Codec<PS>, Codec<StyledSegment<SEG, S>>>> styleCodecs = Optional.empty();
@Override public void setStyleCodecs(Codec<PS> paragraphStyleCodec, Codec<StyledSegment<SEG, S>> styledSegCodec) {
styleCodecs = Optional.of(t(paragraphStyleCodec, styledSegCodec));
}
@Override public Optional<Tuple2<Codec<PS>, Codec<StyledSegment<SEG, S>>>> getStyleCodecs() {
return styleCodecs;
}
@Override public Var<Double> estimatedScrollXProperty() { return virtualFlow.estimatedScrollXProperty(); }
@Override public Var<Double> estimatedScrollYProperty() { return virtualFlow.estimatedScrollYProperty(); }
private final SubscribeableContentsObsSet<CaretNode> caretSet;
private final SubscribeableContentsObsSet<Selection<PS, SEG, S>> selectionSet;
public final boolean addCaret(CaretNode caret) {
if (caret.getArea() != this) {
throw new IllegalArgumentException(String.format(
"The caret (%s) is associated with a different area (%s), " +
"not this area (%s)", caret, caret.getArea(), this));
}
return caretSet.add(caret);
}
public final boolean removeCaret(CaretNode caret) {
if (caret != caretSelectionBind.getUnderlyingCaret()) {
return caretSet.remove(caret);
} else {
return false;
}
}
public final boolean addSelection(Selection<PS, SEG, S> selection) {
if (selection.getArea() != this) {
throw new IllegalArgumentException(String.format(
"The selection (%s) is associated with a different area (%s), " +
"not this area (%s)", selection, selection.getArea(), this));
}
return selectionSet.add(selection);
}
public final boolean removeSelection(Selection<PS, SEG, S> selection) {
if (selection != caretSelectionBind.getUnderlyingSelection()) {
return selectionSet.remove(selection);
} else {
return false;
}
}
/* ********************************************************************** *
* *
* Mouse Behavior Hooks *
* *
* Hooks for overriding some of the default mouse behavior *
* *
* ********************************************************************** */
@Override public final EventHandler<MouseEvent> getOnOutsideSelectionMousePressed() { return onOutsideSelectionMousePressed.get(); }
@Override public final void setOnOutsideSelectionMousePressed(EventHandler<MouseEvent> handler) { onOutsideSelectionMousePressed.set( handler ); }
@Override public final ObjectProperty<EventHandler<MouseEvent>> onOutsideSelectionMousePressedProperty() { return onOutsideSelectionMousePressed; }
private final ObjectProperty<EventHandler<MouseEvent>> onOutsideSelectionMousePressed = new SimpleObjectProperty<>( e -> {
moveTo( hit( e.getX(), e.getY() ).getInsertionIndex(), SelectionPolicy.CLEAR );
});
@Override public final EventHandler<MouseEvent> getOnInsideSelectionMousePressReleased() { return onInsideSelectionMousePressReleased.get(); }
@Override public final void setOnInsideSelectionMousePressReleased(EventHandler<MouseEvent> handler) { onInsideSelectionMousePressReleased.set( handler ); }
@Override public final ObjectProperty<EventHandler<MouseEvent>> onInsideSelectionMousePressReleasedProperty() { return onInsideSelectionMousePressReleased; }
private final ObjectProperty<EventHandler<MouseEvent>> onInsideSelectionMousePressReleased = new SimpleObjectProperty<>( e -> {
moveTo( hit( e.getX(), e.getY() ).getInsertionIndex(), SelectionPolicy.CLEAR );
});
private final ObjectProperty<Consumer<Point2D>> onNewSelectionDrag = new SimpleObjectProperty<>(p -> {
CharacterHit hit = hit(p.getX(), p.getY());
moveTo(hit.getInsertionIndex(), SelectionPolicy.ADJUST);
});
@Override public final ObjectProperty<Consumer<Point2D>> onNewSelectionDragProperty() { return onNewSelectionDrag; }
@Override public final EventHandler<MouseEvent> getOnNewSelectionDragFinished() { return onNewSelectionDragFinished.get(); }
@Override public final void setOnNewSelectionDragFinished(EventHandler<MouseEvent> handler) { onNewSelectionDragFinished.set( handler ); }
@Override public final ObjectProperty<EventHandler<MouseEvent>> onNewSelectionDragFinishedProperty() { return onNewSelectionDragFinished; }
private final ObjectProperty<EventHandler<MouseEvent>> onNewSelectionDragFinished = new SimpleObjectProperty<>( e -> {
CharacterHit hit = hit(e.getX(), e.getY());
moveTo(hit.getInsertionIndex(), SelectionPolicy.ADJUST);
});
private final ObjectProperty<Consumer<Point2D>> onSelectionDrag = new SimpleObjectProperty<>(p -> {
CharacterHit hit = hit(p.getX(), p.getY());
displaceCaret(hit.getInsertionIndex());
});
@Override public final ObjectProperty<Consumer<Point2D>> onSelectionDragProperty() { return onSelectionDrag; }
@Override public final EventHandler<MouseEvent> getOnSelectionDropped() { return onSelectionDropped.get(); }
@Override public final void setOnSelectionDropped(EventHandler<MouseEvent> handler) { onSelectionDropped.set( handler ); }
@Override public final ObjectProperty<EventHandler<MouseEvent>> onSelectionDroppedProperty() { return onSelectionDropped; }
private final ObjectProperty<EventHandler<MouseEvent>> onSelectionDropped = new SimpleObjectProperty<>( e -> {
moveSelectedText( hit( e.getX(), e.getY() ).getInsertionIndex() );
});
// not a hook, but still plays a part in the default mouse behavior
private final BooleanProperty autoScrollOnDragDesired = new SimpleBooleanProperty(true);
@Override public final BooleanProperty autoScrollOnDragDesiredProperty() { return autoScrollOnDragDesired; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setAutoScrollOnDragDesired(boolean val) { autoScrollOnDragDesired.set(val); }
@Override public boolean isAutoScrollOnDragDesired() { return autoScrollOnDragDesired.get(); }
/* ********************************************************************** *
* *
* Observables *
* *
* Observables are "dynamic" (i.e. changing) characteristics of this *
* control. They are not directly settable by the client code, but change *
* in response to user input and/or API actions. *
* *
* ********************************************************************** */
// text
@Override public final ObservableValue<String> textProperty() { return content.textProperty(); }
// rich text
@Override public final StyledDocument<PS, SEG, S> getDocument() { return content; }
private CaretSelectionBind<PS, SEG, S> caretSelectionBind;
@Override public final CaretSelectionBind<PS, SEG, S> getCaretSelectionBind() { return caretSelectionBind; }
// length
@Override public final ObservableValue<Integer> lengthProperty() { return content.lengthProperty(); }
// paragraphs
@Override public LiveList<Paragraph<PS, SEG, S>> getParagraphs() { return content.getParagraphs(); }
private final SuspendableList<Paragraph<PS, SEG, S>> visibleParagraphs;
@Override public final LiveList<Paragraph<PS, SEG, S>> getVisibleParagraphs() { return visibleParagraphs; }
// beingUpdated
private final SuspendableNo beingUpdated = new SuspendableNo();
@Override public final SuspendableNo beingUpdatedProperty() { return beingUpdated; }
// total width estimate
@Override public Val<Double> totalWidthEstimateProperty() { return virtualFlow.totalWidthEstimateProperty(); }
// total height estimate
@Override public Val<Double> totalHeightEstimateProperty() { return virtualFlow.totalHeightEstimateProperty(); }
/* ********************************************************************** *
* *
* Event streams *
* *
* ********************************************************************** */
@Override public EventStream<List<RichTextChange<PS, SEG, S>>> multiRichChanges() { return content.multiRichChanges(); }
@Override public EventStream<List<PlainTextChange>> multiPlainChanges() { return content.multiPlainChanges(); }
// text changes
@Override public final EventStream<PlainTextChange> plainTextChanges() { return content.plainChanges(); }
// rich text changes
@Override public final EventStream<RichTextChange<PS, SEG, S>> richChanges() { return content.richChanges(); }
private final SuspendableEventStream<?> viewportDirty;
@Override public final EventStream<?> viewportDirtyEvents() { return viewportDirty; }
/* ********************************************************************** *
* *
* Private fields *
* *
* ********************************************************************** */
private Subscription subscriptions = () -> {};
private final VirtualFlow<Paragraph<PS, SEG, S>, Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> virtualFlow;
// used for two-level navigation, where on the higher level are
// paragraphs and on the lower level are lines within a paragraph
private final TwoLevelNavigator paragraphLineNavigator;
private boolean paging, followCaretRequested = false;
/* ********************************************************************** *
* *
* Fields necessary for Cloning *
* *
* ********************************************************************** */
private final EditableStyledDocument<PS, SEG, S> content;
@Override public final EditableStyledDocument<PS, SEG, S> getContent() { return content; }
private final S initialTextStyle;
@Override public final S getInitialTextStyle() { return initialTextStyle; }
private final PS initialParagraphStyle;
@Override public final PS getInitialParagraphStyle() { return initialParagraphStyle; }
private final BiConsumer<TextFlow, PS> applyParagraphStyle;
@Override public final BiConsumer<TextFlow, PS> getApplyParagraphStyle() { return applyParagraphStyle; }
// TODO: Currently, only undo/redo respect this flag.
private final boolean preserveStyle;
@Override public final boolean isPreserveStyle() { return preserveStyle; }
/* ********************************************************************** *
* *
* Miscellaneous *
* *
* ********************************************************************** */
private final TextOps<SEG, S> segmentOps;
@Override public final TextOps<SEG, S> getSegOps() { return segmentOps; }
private final EventStream<Boolean> autoCaretBlinksSteam;
final EventStream<Boolean> autoCaretBlink() { return autoCaretBlinksSteam; }
/* ********************************************************************** *
* *
* Constructors *
* *
* ********************************************************************** */
/**
* Creates a text area with empty text content.
*
* @param initialParagraphStyle style to use in places where no other style is
* specified (yet).
* @param applyParagraphStyle function that, given a {@link TextFlow} node and
* a style, applies the style to the paragraph node. This function is
* used by the default skin to apply style to paragraph nodes.
* @param initialTextStyle style to use in places where no other style is
* specified (yet).
* @param segmentOps The operations which are defined on the text segment objects.
* @param nodeFactory A function which is used to create the JavaFX scene nodes for a
* particular segment.
*/
public GenericStyledArea(@NamedArg("initialParagraphStyle") PS initialParagraphStyle,
@NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle,
@NamedArg("initialTextStyle") S initialTextStyle,
@NamedArg("segmentOps") TextOps<SEG, S> segmentOps,
@NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) {
this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, segmentOps, true, nodeFactory);
}
/**
* Same as {@link #GenericStyledArea(Object, BiConsumer, Object, TextOps, Function)} but also allows one
* to specify whether the undo manager should be a plain or rich undo manager via {@code preserveStyle}.
*
* @param initialParagraphStyle style to use in places where no other style is specified (yet).
* @param applyParagraphStyle function that, given a {@link TextFlow} node and
* a style, applies the style to the paragraph node. This function is
* used by the default skin to apply style to paragraph nodes.
* @param initialTextStyle style to use in places where no other style is specified (yet).
* @param segmentOps The operations which are defined on the text segment objects.
* @param preserveStyle whether to use an undo manager that can undo/redo {@link RichTextChange}s or
* {@link PlainTextChange}s
* @param nodeFactory A function which is used to create the JavaFX scene node for a particular segment.
*/
public GenericStyledArea(@NamedArg("initialParagraphStyle") PS initialParagraphStyle,
@NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle,
@NamedArg("initialTextStyle") S initialTextStyle,
@NamedArg("segmentOps") TextOps<SEG, S> segmentOps,
@NamedArg("preserveStyle") boolean preserveStyle,
@NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) {
this(initialParagraphStyle, applyParagraphStyle, initialTextStyle,
new GenericEditableStyledDocument<>(initialParagraphStyle, initialTextStyle, segmentOps), segmentOps, preserveStyle, nodeFactory);
}
/**
* The same as {@link #GenericStyledArea(Object, BiConsumer, Object, TextOps, Function)} except that
* this constructor can be used to create another {@code GenericStyledArea} that renders and edits the same
* {@link EditableStyledDocument} or when one wants to use a custom {@link EditableStyledDocument} implementation.
*/
public GenericStyledArea(
@NamedArg("initialParagraphStyle") PS initialParagraphStyle,
@NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle,
@NamedArg("initialTextStyle") S initialTextStyle,
@NamedArg("document") EditableStyledDocument<PS, SEG, S> document,
@NamedArg("segmentOps") TextOps<SEG, S> segmentOps,
@NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) {
this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, document, segmentOps, true, nodeFactory);
}
/**
* Creates an area with flexibility in all of its options.
*
* @param initialParagraphStyle style to use in places where no other style is specified (yet).
* @param applyParagraphStyle function that, given a {@link TextFlow} node and
* a style, applies the style to the paragraph node. This function is
* used by the default skin to apply style to paragraph nodes.
* @param initialTextStyle style to use in places where no other style is specified (yet).
* @param document the document to render and edit
* @param segmentOps The operations which are defined on the text segment objects.
* @param preserveStyle whether to use an undo manager that can undo/redo {@link RichTextChange}s or
* {@link PlainTextChange}s
* @param nodeFactory A function which is used to create the JavaFX scene node for a particular segment.
*/
public GenericStyledArea(
@NamedArg("initialParagraphStyle") PS initialParagraphStyle,
@NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle,
@NamedArg("initialTextStyle") S initialTextStyle,
@NamedArg("document") EditableStyledDocument<PS, SEG, S> document,
@NamedArg("segmentOps") TextOps<SEG, S> segmentOps,
@NamedArg("preserveStyle") boolean preserveStyle,
@NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) {
this.initialTextStyle = initialTextStyle;
this.initialParagraphStyle = initialParagraphStyle;
this.preserveStyle = preserveStyle;
this.content = document;
this.applyParagraphStyle = applyParagraphStyle;
this.segmentOps = segmentOps;
undoManager = UndoUtils.defaultUndoManager(this);
// allow tab traversal into area
setFocusTraversable(true);
this.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
getStyleClass().add("styled-text-area");
getStylesheets().add(StyledTextArea.class.getResource("styled-text-area.css").toExternalForm());
// keeps track of currently used non-empty cells
@SuppressWarnings("unchecked")
ObservableSet<ParagraphBox<PS, SEG, S>> nonEmptyCells = FXCollections.observableSet();
caretSet = new SubscribeableContentsObsSet<>();
manageSubscription(() -> {
List<CaretNode> l = new ArrayList<>(caretSet);
caretSet.clear();
l.forEach(CaretNode::dispose);
});
selectionSet = new SubscribeableContentsObsSet<>();
manageSubscription(() -> {
List<Selection<PS, SEG, S>> l = new ArrayList<>(selectionSet);
selectionSet.clear();
l.forEach(Selection::dispose);
});
// Initialize content
virtualFlow = VirtualFlow.createVertical(
getParagraphs(),
par -> {
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = createCell(
par,
applyParagraphStyle,
nodeFactory);
nonEmptyCells.add(cell.getNode());
return cell.beforeReset(() -> nonEmptyCells.remove(cell.getNode()))
.afterUpdateItem(p -> nonEmptyCells.add(cell.getNode()));
});
getChildren().add(virtualFlow);
// initialize navigator
IntSupplier cellCount = () -> getParagraphs().size();
IntUnaryOperator cellLength = i -> virtualFlow.getCell(i).getNode().getLineCount();
paragraphLineNavigator = new TwoLevelNavigator(cellCount, cellLength);
viewportDirty = merge(
// no need to check for width & height invalidations as scroll values update when these do
// scale
invalidationsOf(scaleXProperty()),
invalidationsOf(scaleYProperty()),
// scroll
invalidationsOf(estimatedScrollXProperty()),
invalidationsOf(estimatedScrollYProperty())
).suppressible();
autoCaretBlinksSteam = EventStreams.valuesOf(focusedProperty()
.and(editableProperty())
.and(disabledProperty().not())
);
caretSelectionBind = new CaretSelectionBindImpl<>("main-caret", "main-selection",this);
caretSelectionBind.paragraphIndexProperty().addListener( this::skipOverFoldedParagraphs );
caretSet.add(caretSelectionBind.getUnderlyingCaret());
selectionSet.add(caretSelectionBind.getUnderlyingSelection());
visibleParagraphs = LiveList.map(virtualFlow.visibleCells(), c -> c.getNode().getParagraph()).suspendable();
final Suspendable omniSuspendable = Suspendable.combine(
beingUpdated, // must be first, to be the last one to release
visibleParagraphs
);
manageSubscription(omniSuspendable.suspendWhen(content.beingUpdatedProperty()));
// dispatch MouseOverTextEvents when mouseOverTextDelay is not null
EventStreams.valuesOf(mouseOverTextDelayProperty())
.flatMap(delay -> delay != null
? mouseOverTextEvents(nonEmptyCells, delay)
: EventStreams.never())
.subscribe(evt -> Event.fireEvent(this, evt));
new GenericStyledAreaBehavior(this);
// Setup place holder visibility & placement
final Val<Boolean> showPlaceholder = Val.create
(
() -> getLength() == 0 && ! isFocused(),
lengthProperty(), focusedProperty()
);
placeHolderProp.addListener( (ob,ov,newNode) -> displayPlaceHolder( showPlaceholder.getValue(), newNode ) );
showPlaceholder.addListener( (ob,ov,show) -> displayPlaceHolder( show, getPlaceholder() ) );
if ( Platform.isFxApplicationThread() ) initInputMethodHandling();
else Platform.runLater( () -> initInputMethodHandling() );
}
private void initInputMethodHandling()
{
if( Platform.isSupported( ConditionalFeature.INPUT_METHOD ) )
{
setOnInputMethodTextChanged( event -> handleInputMethodEvent(event) );
// Both of these have to be set for input composition to work !
setInputMethodRequests( new InputMethodRequests()
{
@Override public Point2D getTextLocation( int offset ) {
Bounds charBounds = getCaretBounds().get();
return new Point2D( charBounds.getMaxX() - 5, charBounds.getMaxY() );
}
@Override public int getLocationOffset( int x, int y ) {
return 0;
}
@Override public void cancelLatestCommittedText() {}
@Override public String getSelectedText() {
return getSelectedText();
}
});
}
}
// Start/Length of the text under input method composition
private int imstart;
private int imlength;
protected void handleInputMethodEvent( InputMethodEvent event )
{
if ( isEditable() && !isDisabled() )
{
// remove previous input method text (if any) or selected text
if ( imlength != 0 ) {
selectRange( imstart, imstart + imlength );
}
// Insert committed text
if ( event.getCommitted().length() != 0 ) {
replaceText( getSelection(), event.getCommitted() );
}
// Replace composed text
imstart = getSelection().getStart();
StringBuilder composed = new StringBuilder();
for ( InputMethodTextRun run : event.getComposed() ) {
composed.append( run.getText() );
}
replaceText( getSelection(), composed.toString() );
imlength = composed.length();
if ( imlength != 0 )
{
int pos = imstart;
for ( InputMethodTextRun run : event.getComposed() ) {
int endPos = pos + run.getText().length();
pos = endPos;
}
// Set caret position in composed text
int caretPos = event.getCaretPosition();
if ( caretPos >= 0 && caretPos < imlength ) {
selectRange( imstart + caretPos, imstart + caretPos );
}
}
}
}
private Node placeholder;
private boolean positionPlaceholder = false;
private void displayPlaceHolder( boolean show, Node newNode )
{
if ( placeholder != null && (! show || newNode != placeholder) )
{
placeholder.layoutXProperty().unbind();
placeholder.layoutYProperty().unbind();
getChildren().remove( placeholder );
placeholder = null;
setClip( null );
}
if ( newNode != null && show && newNode != placeholder )
{
configurePlaceholder( newNode );
getChildren().add( newNode );
placeholder = newNode;
}
}
/**
* Override this to customize the placeholder's layout.
* <br>The default position is centered over the area.
*/
protected void configurePlaceholder( Node placeholder )
{
positionPlaceholder = true;
}
/* ********************************************************************** *
* *
* Queries *
* *
* Queries are parameterized observables. *
* *
* ********************************************************************** */
@Override
public final double getViewportHeight() {
return virtualFlow.getHeight();
}
@Override
public final Optional<Integer> allParToVisibleParIndex(int allParIndex) {
if (allParIndex < 0) {
throw new IllegalArgumentException("The given paragraph index (allParIndex) cannot be negative but was " + allParIndex);
}
if (allParIndex >= getParagraphs().size()) {
throw new IllegalArgumentException(String.format(
"Paragraphs' last index is [%s] but allParIndex was [%s]",
getParagraphs().size() - 1, allParIndex)
);
}
List<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> visibleList = virtualFlow.visibleCells();
int firstVisibleParIndex = visibleList.get( 0 ).getNode().getIndex();
int targetIndex = allParIndex - firstVisibleParIndex;
if ( allParIndex >= firstVisibleParIndex && targetIndex < visibleList.size() )
{
if ( visibleList.get( targetIndex ).getNode().getIndex() == allParIndex )
{
return Optional.of( targetIndex );
}
}
return Optional.empty();
}
@Override
public final int visibleParToAllParIndex(int visibleParIndex) {
if (visibleParIndex < 0) {
throw new IllegalArgumentException("Visible paragraph index cannot be negative but was " + visibleParIndex);
}
if (visibleParIndex > 0 && visibleParIndex >= getVisibleParagraphs().size()) {
throw new IllegalArgumentException(String.format(
"Visible paragraphs' last index is [%s] but visibleParIndex was [%s]",
getVisibleParagraphs().size() - 1, visibleParIndex)
);
}
Cell<Paragraph<PS,SEG,S>, ParagraphBox<PS,SEG,S>> visibleCell = null;
if ( visibleParIndex > 0 ) visibleCell = virtualFlow.visibleCells().get( visibleParIndex );
else visibleCell = virtualFlow.getCellIfVisible( virtualFlow.getFirstVisibleIndex() )
.orElseGet( () -> virtualFlow.visibleCells().get( visibleParIndex ) );
return visibleCell.getNode().getIndex();
}
@Override
public CharacterHit hit(double x, double y) {
// mouse position used, so account for padding
double adjustedX = x - getInsets().getLeft();
double adjustedY = y - getInsets().getTop();
VirtualFlowHit<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> hit = virtualFlow.hit(adjustedX, adjustedY);
if(hit.isBeforeCells()) {
return CharacterHit.insertionAt(0);
} else if(hit.isAfterCells()) {
return CharacterHit.insertionAt(getLength());
} else {
int parIdx = hit.getCellIndex();
int parOffset = getParagraphOffset(parIdx);
ParagraphBox<PS, SEG, S> cell = hit.getCell().getNode();
Point2D cellOffset = hit.getCellOffset();
CharacterHit parHit = cell.hit(cellOffset);
return parHit.offset(parOffset);
}
}
@Override
public final int lineIndex(int paragraphIndex, int columnPosition) {
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(paragraphIndex);
return cell.getNode().getCurrentLineIndex(columnPosition);
}
@Override
public int getParagraphLinesCount(int paragraphIndex) {
return virtualFlow.getCell(paragraphIndex).getNode().getLineCount();
}
@Override
public Optional<Bounds> getCharacterBoundsOnScreen(int from, int to) {
if (from < 0) {
throw new IllegalArgumentException("From is negative: " + from);
}
if (from > to) {
throw new IllegalArgumentException(String.format("From is greater than to. from=%s to=%s", from, to));
}
if (to > getLength()) {
throw new IllegalArgumentException(String.format("To is greater than area's length. length=%s, to=%s", getLength(), to));
}
// no bounds exist if range is just a newline character
if (getText(from, to).equals("\n")) {
return Optional.empty();
}
// if 'from' is the newline character at the end of a multi-line paragraph, it returns a Bounds that whose
// minX & minY are the minX and minY of the paragraph itself, not the newline character. So, ignore it.
int realFrom = getText(from, from + 1).equals("\n") ? from + 1 : from;
Position startPosition = offsetToPosition(realFrom, Bias.Forward);
int startRow = startPosition.getMajor();
Position endPosition = startPosition.offsetBy(to - realFrom, Bias.Forward);
int endRow = endPosition.getMajor();
if (startRow == endRow) {
return getRangeBoundsOnScreen(startRow, startPosition.getMinor(), endPosition.getMinor());
} else {
Optional<Bounds> rangeBounds = getRangeBoundsOnScreen(startRow, startPosition.getMinor(),
getParagraph(startRow).length());
for (int i = startRow + 1; i <= endRow; i++) {
Optional<Bounds> nextLineBounds = getRangeBoundsOnScreen(i, 0,
i == endRow
? endPosition.getMinor()
: getParagraph(i).length()
);
if (nextLineBounds.isPresent()) {
if (rangeBounds.isPresent()) {
Bounds lineBounds = nextLineBounds.get();
rangeBounds = rangeBounds.map(b -> {
double minX = Math.min(b.getMinX(), lineBounds.getMinX());
double minY = Math.min(b.getMinY(), lineBounds.getMinY());
double maxX = Math.max(b.getMaxX(), lineBounds.getMaxX());
double maxY = Math.max(b.getMaxY(), lineBounds.getMaxY());
return new BoundingBox(minX, minY, maxX - minX, maxY - minY);
});
} else {
rangeBounds = nextLineBounds;
}
}
}
return rangeBounds;
}
}
@Override
public final String getText(int start, int end) {
return content.getText(start, end);
}
@Override
public String getText(int paragraph) {
return content.getText(paragraph);
}
@Override
public String getText(IndexRange range) {
return content.getText(range);
}
@Override
public StyledDocument<PS, SEG, S> subDocument(int start, int end) {
return content.subSequence(start, end);
}
@Override
public StyledDocument<PS, SEG, S> subDocument(int paragraphIndex) {
return content.subDocument(paragraphIndex);
}
@Override
public IndexRange getParagraphSelection(Selection selection, int paragraph) {
int startPar = selection.getStartParagraphIndex();
int endPar = selection.getEndParagraphIndex();
if(selection.getLength() == 0 || paragraph < startPar || paragraph > endPar) {
return EMPTY_RANGE;
}
int start = paragraph == startPar ? selection.getStartColumnPosition() : 0;
int end = paragraph == endPar ? selection.getEndColumnPosition() : getParagraphLength(paragraph) + 1;
// force rangeProperty() to be valid
selection.getRange();
return new IndexRange(start, end);
}
@Override
public S getStyleOfChar(int index) {
return content.getStyleOfChar(index);
}
@Override
public S getStyleAtPosition(int position) {
return content.getStyleAtPosition(position);
}
@Override
public IndexRange getStyleRangeAtPosition(int position) {
return content.getStyleRangeAtPosition(position);
}
@Override
public StyleSpans<S> getStyleSpans(int from, int to) {
return content.getStyleSpans(from, to);
}
@Override
public S getStyleOfChar(int paragraph, int index) {
return content.getStyleOfChar(paragraph, index);
}
@Override
public S getStyleAtPosition(int paragraph, int position) {
return content.getStyleAtPosition(paragraph, position);
}
@Override
public IndexRange getStyleRangeAtPosition(int paragraph, int position) {
return content.getStyleRangeAtPosition(paragraph, position);
}
@Override
public StyleSpans<S> getStyleSpans(int paragraph) {
return content.getStyleSpans(paragraph);
}
@Override
public StyleSpans<S> getStyleSpans(int paragraph, int from, int to) {
return content.getStyleSpans(paragraph, from, to);
}
@Override
public int getAbsolutePosition(int paragraphIndex, int columnIndex) {
return content.getAbsolutePosition(paragraphIndex, columnIndex);
}
@Override
public Position position(int row, int col) {
return content.position(row, col);
}
@Override
public Position offsetToPosition(int charOffset, Bias bias) {
return content.offsetToPosition(charOffset, bias);
}
@Override
public Bounds getVisibleParagraphBoundsOnScreen(int visibleParagraphIndex) {
return getParagraphBoundsOnScreen(virtualFlow.visibleCells().get(visibleParagraphIndex));
}
@Override
public Optional<Bounds> getParagraphBoundsOnScreen(int paragraphIndex) {
return virtualFlow.getCellIfVisible(paragraphIndex).map(this::getParagraphBoundsOnScreen);
}
@Override
public final <T extends Node & Caret> Optional<Bounds> getCaretBoundsOnScreen(T caret) {
Optional<Bounds> caretBounds;
try { // This is the default mechanism, but sometimes throws just like in followCaret()
caretBounds = virtualFlow.getCellIfVisible(caret.getParagraphIndex())
.map(c -> c.getNode().getCaretBoundsOnScreen(caret));
}
catch ( IllegalArgumentException EX ) {
// This is an alternative mechanism, to address https://github.com/FXMisc/RichTextFX/issues/1048
caretBounds = Optional.ofNullable( caretSelectionBind.getUnderlyingCaret().getLayoutBounds() );
}
return caretBounds;
}
/* ********************************************************************** *
* *
* Actions *
* *
* Actions change the state of this control. They typically cause a *
* change of one or more observables and/or produce an event. *
* *
* ********************************************************************** */
@Override
public void scrollXToPixel(double pixel) {
suspendVisibleParsWhile(() -> virtualFlow.scrollXToPixel(pixel));
}
@Override
public void scrollYToPixel(double pixel) {
suspendVisibleParsWhile(() -> virtualFlow.scrollYToPixel(pixel));
}
@Override
public void scrollXBy(double deltaX) {
suspendVisibleParsWhile(() -> virtualFlow.scrollXBy(deltaX));
}
@Override
public void scrollYBy(double deltaY) {
suspendVisibleParsWhile(() -> virtualFlow.scrollYBy(deltaY));
}
@Override
public void scrollBy(Point2D deltas) {
suspendVisibleParsWhile(() -> virtualFlow.scrollBy(deltas));
}
@Override
public void showParagraphInViewport(int paragraphIndex) {
suspendVisibleParsWhile(() -> virtualFlow.show(paragraphIndex));
}
@Override
public void showParagraphAtTop(int paragraphIndex) {
suspendVisibleParsWhile(() -> virtualFlow.showAsFirst(paragraphIndex));
}
@Override
public void showParagraphAtBottom(int paragraphIndex) {
suspendVisibleParsWhile(() -> virtualFlow.showAsLast(paragraphIndex));
}
@Override
public void showParagraphRegion(int paragraphIndex, Bounds region) {
suspendVisibleParsWhile(() -> virtualFlow.show(paragraphIndex, region));
}
@Override
public void requestFollowCaret() {
followCaretRequested = true;
requestLayout();
}
@Override
public void lineStart(SelectionPolicy policy) {
moveTo(getCurrentParagraph(), getCurrentLineStartInParargraph(), policy);
}
@Override
public void lineEnd(SelectionPolicy policy) {
moveTo(getCurrentParagraph(), getCurrentLineEndInParargraph(), policy);
}
public int getCurrentLineStartInParargraph() {
return virtualFlow.getCell(getCurrentParagraph()).getNode().getCurrentLineStartPosition(caretSelectionBind.getUnderlyingCaret());
}
public int getCurrentLineEndInParargraph() {
return virtualFlow.getCell(getCurrentParagraph()).getNode().getCurrentLineEndPosition(caretSelectionBind.getUnderlyingCaret());
}
private double caretPrevY = -1;
private LineSelection<PS, SEG, S> lineHighlighter;
private ObjectProperty<Paint> lineHighlighterFill;
/**
* The default fill is "highlighter" yellow. It can also be styled using CSS with:<br>
* <code>.styled-text-area .line-highlighter { -fx-fill: lime; }</code><br>
* CSS selectors from Path, Shape, and Node can also be used.
*/
public void setLineHighlighterFill( Paint highlight )
{
if ( lineHighlighterFill != null && highlight != null ) {
lineHighlighterFill.set( highlight );
}
else {
boolean lineHighlightOn = isLineHighlighterOn();
if ( lineHighlightOn ) setLineHighlighterOn( false );
if ( highlight == null ) lineHighlighterFill = null;
else lineHighlighterFill = new SimpleObjectProperty( highlight );
if ( lineHighlightOn ) setLineHighlighterOn( true );
}
}
public boolean isLineHighlighterOn() {
return lineHighlighter != null && selectionSet.contains( lineHighlighter ) ;
}
/**
* Highlights the line that the main caret is on.<br>
* Line highlighting automatically follows the caret.
*/
public void setLineHighlighterOn( boolean show )
{
if ( show )
{
if ( lineHighlighter != null ) return;
lineHighlighter = new LineSelection<>( this, lineHighlighterFill );
Consumer<Bounds> caretListener = b ->
{
if ( lineHighlighter != null && (b.getMinY() != caretPrevY || getCaretColumn() == 1) ) {
lineHighlighter.selectCurrentLine();
caretPrevY = b.getMinY();
}
};
caretBoundsProperty().addListener( (ob,ov,nv) -> nv.ifPresent( caretListener ) );
getCaretBounds().ifPresent( caretListener );
selectionSet.add( lineHighlighter );
}
else if ( lineHighlighter != null ) {
selectionSet.remove( lineHighlighter );
lineHighlighter.deselect();
lineHighlighter = null;
caretPrevY = -1;
}
}
@Override
public void prevPage(SelectionPolicy selectionPolicy) {
// Paging up and we're in the first frame then move/select to start.
if ( firstVisibleParToAllParIndex() == 0 ) {
caretSelectionBind.moveTo( 0, selectionPolicy );
}
else page( -1, selectionPolicy );
}
@Override
public void nextPage(SelectionPolicy selectionPolicy) {
// Paging down and we're in the last frame then move/select to end.
if ( lastVisibleParToAllParIndex() == getParagraphs().size()-1 ) {
caretSelectionBind.moveTo( getLength(), selectionPolicy );
}
else page( +1, selectionPolicy );
}
/**
* @param pgCount the number of pages to page up/down.
* <br>Negative numbers for paging up and positive for down.
*/
private void page(int pgCount, SelectionPolicy selectionPolicy)
{
// Use underlying caret to get the same behaviour as navigating up/down a line where the x position is sticky
Optional<Bounds> cb = caretSelectionBind.getUnderlyingCaret().getCaretBounds();
paging = true; // Prevent scroll from reverting back to the current caret position
scrollYBy( pgCount * getViewportHeight() );
cb.map( this::screenToLocal ) // Place caret near the same on screen position as before
.map( b -> hit( b.getMinX(), b.getMinY()+b.getHeight()/2.0 ).getInsertionIndex() )
.ifPresent( i -> caretSelectionBind.moveTo( i, selectionPolicy ) );
// Adjust scroll by a few pixels to get the caret at the exact on screen location as before
cb.ifPresent( prev -> getCaretBounds().map( newB -> newB.getMinY() - prev.getMinY() )
.filter( delta -> delta != 0.0 ).ifPresent( delta -> scrollYBy( delta ) ) );
}
@Override
public void displaceCaret(int pos) {
caretSelectionBind.displaceCaret(pos);
}
@Override
public void setStyle(int from, int to, S style) {
content.setStyle(from, to, style);
}
@Override
public void setStyle(int paragraph, S style) {
content.setStyle(paragraph, style);
}
@Override
public void setStyle(int paragraph, int from, int to, S style) {
content.setStyle(paragraph, from, to, style);
}
@Override
public void setStyleSpans(int from, StyleSpans<? extends S> styleSpans) {
content.setStyleSpans(from, styleSpans);
}
@Override
public void setStyleSpans(int paragraph, int from, StyleSpans<? extends S> styleSpans) {
content.setStyleSpans(paragraph, from, styleSpans);
}
@Override
public void setParagraphStyle(int paragraph, PS paragraphStyle) {
content.setParagraphStyle(paragraph, paragraphStyle);
}
/**
* If you want to preset the style to be used for inserted text. Note that useInitialStyleForInsertion overrides this if true.
*/
public final void setTextInsertionStyle( S txtStyle ) { insertionTextStyle = txtStyle; }
public final S getTextInsertionStyle() { return insertionTextStyle; }
private S insertionTextStyle;
@Override
public final S getTextStyleForInsertionAt(int pos) {
if ( insertionTextStyle != null ) {
return insertionTextStyle;
} else if ( useInitialStyleForInsertion.get() ) {
return initialTextStyle;
} else {
return content.getStyleAtPosition(pos);
}
}
private PS insertionParagraphStyle;
/**
* If you want to preset the style to be used. Note that useInitialStyleForInsertion overrides this if true.
*/
public final void setParagraphInsertionStyle( PS paraStyle ) { insertionParagraphStyle = paraStyle; }
public final PS getParagraphInsertionStyle() { return insertionParagraphStyle; }
@Override
public final PS getParagraphStyleForInsertionAt(int pos) {
if ( insertionParagraphStyle != null ) {
return insertionParagraphStyle;
} else if ( useInitialStyleForInsertion.get() ) {
return initialParagraphStyle;
} else {
return content.getParagraphStyleAtPosition(pos);
}
}
@Override
public void replaceText(int start, int end, String text) {
StyledDocument<PS, SEG, S> doc = ReadOnlyStyledDocument.fromString(
text, getParagraphStyleForInsertionAt(start), getTextStyleForInsertionAt(start), segmentOps
);
replace(start, end, doc);
}
@Override
public void replace(int start, int end, SEG seg, S style) {
StyledDocument<PS, SEG, S> doc = ReadOnlyStyledDocument.fromSegment(
seg, getParagraphStyleForInsertionAt(start), style, segmentOps
);
replace(start, end, doc);
}
@Override
public void replace(int start, int end, StyledDocument<PS, SEG, S> replacement) {
content.replace(start, end, replacement);
int newCaretPos = start + replacement.length();
selectRange(newCaretPos, newCaretPos);
}
void replaceMulti(List<Replacement<PS, SEG, S>> replacements) {
content.replaceMulti(replacements);
// don't update selection as this is not the main method through which the area is updated
// leave that up to the developer using it to determine what to do
}
@Override
public MultiChangeBuilder<PS, SEG, S> createMultiChange() {
return new MultiChangeBuilder<>(this);
}
@Override
public MultiChangeBuilder<PS, SEG, S> createMultiChange(int initialNumOfChanges) {
return new MultiChangeBuilder<>(this, initialNumOfChanges);
}
/**
* Convenience method to fold (hide/collapse) the currently selected paragraphs,
* into (i.e. excluding) the first paragraph of the range.
*
* @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that will activate folding.
*
* <p>See {@link #fold(int, int, UnaryOperator)} for more info.</p>
*/
protected void foldSelectedParagraphs( UnaryOperator<PS> styleMixin )
{
IndexRange range = getSelection();
fold( range.getStart(), range.getEnd(), styleMixin );
}
/**
* Folds (hides/collapses) paragraphs from <code>start</code> to <code>
* end</code>, into (i.e. excluding) the first paragraph of the range.
*
* @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that will activate folding.
*
* <p>See {@link #fold(int, int, UnaryOperator)} for more info.</p>
*/
protected void foldParagraphs( int start, int end, UnaryOperator<PS> styleMixin )
{
start = getAbsolutePosition( start, 0 );
end = getAbsolutePosition( end, getParagraphLength( end ) );
fold( start, end, styleMixin );
}
/**
* Folds (hides/collapses) paragraphs from character position <code>startPos</code>
* to <code>endPos</code>, into (i.e. excluding) the first paragraph of the range.
*
* <p>Folding is achieved with the help of paragraph styling, which is applied to the paragraph's
* TextFlow object through the applyParagraphStyle BiConsumer (supplied in the constructor to
* GenericStyledArea). When applyParagraphStyle is to apply fold styling it just needs to set
* the TextFlow's visibility to collapsed for it to be folded. See {@code InlineCssTextArea},
* {@code StyleClassedTextArea}, and {@code RichTextDemo} for different ways of doing this.
* Also read the GitHub Wiki.</p>
*
* <p>The UnaryOperator <code>styleMixin</code> must return a
* different paragraph style Object to what was submitted.</p>
*
* @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that will activate folding.
*/
protected void fold( int startPos, int endPos, UnaryOperator<PS> styleMixin )
{
ReadOnlyStyledDocument<PS, SEG, S> subDoc;
UnaryOperator<Paragraph<PS, SEG, S>> mapper;
subDoc = (ReadOnlyStyledDocument<PS, SEG, S>) subDocument( startPos, endPos );
mapper = p -> p.setParagraphStyle( styleMixin.apply( p.getParagraphStyle() ) );
for ( int p = 1; p < subDoc.getParagraphCount(); p++ ) {
subDoc = subDoc.replaceParagraph( p, mapper ).get1();
}
replace( startPos, endPos, subDoc );
recreateParagraphGraphic( offsetToPosition( startPos, Bias.Backward ).getMajor() );
moveTo( startPos );
foldCheck = true;
}
protected boolean foldCheck = false;
private void skipOverFoldedParagraphs( ObservableValue<? extends Integer> ob, Integer prevParagraph, Integer newParagraph )
{
if ( foldCheck && getCell( newParagraph ).isFolded() )
{
// Prevent Ctrl+A and Ctrl+End breaking when the last paragraph is folded
// github.com/FXMisc/RichTextFX/pull/965#issuecomment-706268116
if ( newParagraph == getParagraphs().size() - 1 ) return;
int skip = (newParagraph - prevParagraph > 0) ? +1 : -1;
int p = newParagraph + skip;
while ( p > 0 && p < getParagraphs().size() ) {
if ( getCell( p ).isFolded() ) p += skip;
else break;
}
if ( p < 0 || p == getParagraphs().size() ) p = prevParagraph;
int col = Math.min( getCaretColumn(), getParagraphLength( p ) );
if ( getSelection().getLength() == 0 ) moveTo( p, col );
else moveTo( p, col, SelectionPolicy.EXTEND );
}
}
/**
* Unfolds paragraphs <code>startingFrom</code> onwards for the currently folded block.
*
* <p>The UnaryOperator <code>styleMixin</code> must return a
* different paragraph style Object to what was submitted.</p>
*
* @param isFolded Given a paragraph style PS check if it's folded.
* @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that excludes fold styling.
*/
protected void unfoldParagraphs( int startingFrom, Predicate<PS> isFolded, UnaryOperator<PS> styleMixin )
{
LiveList<Paragraph<PS, SEG, S>> pList = getParagraphs();
int to = startingFrom;
while ( ++to < pList.size() )
{
if ( ! isFolded.test( pList.get( to ).getParagraphStyle() ) ) break;
}
if ( --to > startingFrom )
{
ReadOnlyStyledDocument<PS, SEG, S> subDoc;
UnaryOperator<Paragraph<PS, SEG, S>> mapper;
int startPos = getAbsolutePosition( startingFrom, 0 );
int endPos = getAbsolutePosition( to, getParagraphLength( to ) );
subDoc = (ReadOnlyStyledDocument<PS, SEG, S>) subDocument( startPos, endPos );
mapper = p -> p.setParagraphStyle( styleMixin.apply( p.getParagraphStyle() ) );
for ( int p = 1; p < subDoc.getParagraphCount(); p++ ) {
subDoc = subDoc.replaceParagraph( p, mapper ).get1();
}
replace( startPos, endPos, subDoc );
moveTo( startingFrom, getParagraphLength( startingFrom ) );
recreateParagraphGraphic( startingFrom );
}
}
/* ********************************************************************** *
* *
* Public API *
* *
* ********************************************************************** */
@Override
public void dispose() {
if (undoManager != null) {
undoManager.close();
}
subscriptions.unsubscribe();
virtualFlow.dispose();
}
/* ********************************************************************** *
* *
* Layout *
* *
* ********************************************************************** */
private BooleanProperty autoHeightProp = new SimpleBooleanProperty();
public BooleanProperty autoHeightProperty() {
return autoHeightProp;
}
public void setAutoHeight( boolean value ) {
autoHeightProp.set( value );
}
public boolean isAutoHeight() {
return autoHeightProp.get();
}
@Override
protected double computePrefHeight( double width )
{
if ( autoHeightProp.get() )
{
if ( getWidth() == 0.0 ) Platform.runLater( () -> requestLayout() );
else
{
double height = 0.0;
Insets in = getInsets();
for ( int p = 0; p < getParagraphs().size(); p++ ) {
height += getCell( p ).getHeight();
}
if ( height > 0.0 ) {
return height + in.getTop() + in.getBottom();
}
}
}
return super.computePrefHeight( width );
}
@Override
protected void layoutChildren() {
Insets ins = getInsets();
visibleParagraphs.suspendWhile(() -> {
virtualFlow.resizeRelocate(
ins.getLeft(), ins.getTop(),
getWidth() - ins.getLeft() - ins.getRight(),
getHeight() - ins.getTop() - ins.getBottom());
if(followCaretRequested && ! paging) {
try (Guard g = viewportDirty.suspend()) {
followCaret();
}
}
followCaretRequested = false;
paging = false;
});
Node holder = placeholder;
if (holder != null && holder.isManaged()) {
if (holder.isResizable()) holder.autosize();
if (positionPlaceholder) Region.positionInArea
(
holder, getLayoutX(), getLayoutY(), getWidth(), getHeight(), getBaselineOffset(),
ins, placeHolderPos.getHpos(), placeHolderPos.getVpos(), isSnapToPixel()
);
}
}
/* ********************************************************************** *
* *
* Package-Private methods *
* *
* ********************************************************************** */
/**
* Returns the current line as a two-level index.
* The major number is the paragraph index, the minor
* number is the line number within the paragraph.
*
* <p>This method has a side-effect of bringing the current
* paragraph to the viewport if it is not already visible.
*/
TwoDimensional.Position currentLine() {
int parIdx = getCurrentParagraph();
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx);
int lineIdx = cell.getNode().getCurrentLineIndex(caretSelectionBind.getUnderlyingCaret());
return paragraphLineNavigator.position(parIdx, lineIdx);
}
void showCaretAtBottom() {
int parIdx = getCurrentParagraph();
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx);
Bounds caretBounds = cell.getNode().getCaretBounds(caretSelectionBind.getUnderlyingCaret());
double y = caretBounds.getMaxY();
suspendVisibleParsWhile(() -> virtualFlow.showAtOffset(parIdx, getViewportHeight() - y));
}
void showCaretAtTop() {
int parIdx = getCurrentParagraph();
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx);
Bounds caretBounds = cell.getNode().getCaretBounds(caretSelectionBind.getUnderlyingCaret());
double y = caretBounds.getMinY();
suspendVisibleParsWhile(() -> virtualFlow.showAtOffset(parIdx, -y));
}
/**
* Returns x coordinate of the caret in the current paragraph.
*/
final ParagraphBox.CaretOffsetX getCaretOffsetX(CaretNode caret) {
return getCell(caret.getParagraphIndex()).getCaretOffsetX(caret);
}
CharacterHit hit(ParagraphBox.CaretOffsetX x, TwoDimensional.Position targetLine) {
int parIdx = targetLine.getMajor();
ParagraphBox<PS, SEG, S> cell = virtualFlow.getCell(parIdx).getNode();
CharacterHit parHit = cell.hitTextLine(x, targetLine.getMinor());
return parHit.offset(getParagraphOffset(parIdx));
}
CharacterHit hit(ParagraphBox.CaretOffsetX x, double y) {
// don't account for padding here since height of virtualFlow is used, not area + potential padding
VirtualFlowHit<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> hit = virtualFlow.hit(0.0, y);
if(hit.isBeforeCells()) {
return CharacterHit.insertionAt(0);
} else if(hit.isAfterCells()) {
return CharacterHit.insertionAt(getLength());
} else {
int parIdx = hit.getCellIndex();
int parOffset = getParagraphOffset(parIdx);
ParagraphBox<PS, SEG, S> cell = hit.getCell().getNode();
Point2D cellOffset = hit.getCellOffset();
CharacterHit parHit = cell.hitText(x, cellOffset.getY());
return parHit.offset(parOffset);
}
}
final Optional<Bounds> getSelectionBoundsOnScreen(Selection<PS, SEG, S> selection) {
if (selection.getLength() == 0) {
return Optional.empty();
}
List<Bounds> bounds = new ArrayList<>(selection.getParagraphSpan());
for (int i = selection.getStartParagraphIndex(); i <= selection.getEndParagraphIndex(); i++) {
virtualFlow.getCellIfVisible(i)
.ifPresent(c -> c.getNode()
.getSelectionBoundsOnScreen(selection)
.ifPresent(bounds::add)
);
}
if(bounds.size() == 0) {
return Optional.empty();
}
double minX = bounds.stream().mapToDouble(Bounds::getMinX).min().getAsDouble();
double maxX = bounds.stream().mapToDouble(Bounds::getMaxX).max().getAsDouble();
double minY = bounds.stream().mapToDouble(Bounds::getMinY).min().getAsDouble();
double maxY = bounds.stream().mapToDouble(Bounds::getMaxY).max().getAsDouble();
return Optional.of(new BoundingBox(minX, minY, maxX-minX, maxY-minY));
}
void clearTargetCaretOffset() {
caretSelectionBind.clearTargetOffset();
}
ParagraphBox.CaretOffsetX getTargetCaretOffset() {
return caretSelectionBind.getTargetOffset();
}
/* ********************************************************************** *
* *
* Private methods *
* *
* ********************************************************************** */
private Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> createCell(
Paragraph<PS, SEG, S> paragraph,
BiConsumer<TextFlow, PS> applyParagraphStyle,
Function<StyledSegment<SEG, S>, Node> nodeFactory) {
ParagraphBox<PS, SEG, S> box = new ParagraphBox<>(paragraph, applyParagraphStyle, nodeFactory);
box.highlightTextFillProperty().bind(highlightTextFill);
box.wrapTextProperty().bind(wrapTextProperty());
box.graphicFactoryProperty().bind(paragraphGraphicFactoryProperty());
box.graphicOffset.bind(virtualFlow.breadthOffsetProperty());
EventStream<Integer> boxIndexValues = box.indexProperty().values().filter(i -> i != -1);
Subscription firstParPseudoClass = boxIndexValues.subscribe(idx -> box.pseudoClassStateChanged(FIRST_PAR, idx == 0));
Subscription lastParPseudoClass = EventStreams.combine(
boxIndexValues,
getParagraphs().sizeProperty().values()
).subscribe(in -> in.exec((i, n) -> box.pseudoClassStateChanged(LAST_PAR, i == n-1)));
// set up caret
Function<CaretNode, Subscription> subscribeToCaret = caret -> {
EventStream<Integer> caretIndexStream = EventStreams.nonNullValuesOf(caret.paragraphIndexProperty());
// a new event stream needs to be created for each caret added, so that it will immediately
// fire the box's current index value as an event, thereby running the code in the subscribe block
// Reusing boxIndexValues will not fire its most recent event, leading to a caret not being added
// Thus, we'll call the new event stream "fresh" box index values
EventStream<Integer> freshBoxIndexValues = box.indexProperty().values().filter(i -> i != -1);
return EventStreams.combine(caretIndexStream, freshBoxIndexValues)
.subscribe(t -> {
int caretParagraphIndex = t.get1();
int boxIndex = t.get2();
if (caretParagraphIndex == boxIndex) {
box.caretsProperty().add(caret);
} else {
box.caretsProperty().remove(caret);
}
});
};
Subscription caretSubscription = caretSet.addSubscriber(subscribeToCaret);
// TODO: how should 'hasCaret' be handled now?
Subscription hasCaretPseudoClass = EventStreams
.combine(boxIndexValues, Val.wrap(currentParagraphProperty()).values())
// box index (t1) == caret paragraph index (t2)
.map(t -> t.get1().equals(t.get2()))
.subscribe(value -> box.pseudoClassStateChanged(HAS_CARET, value));
Function<Selection<PS, SEG, S>, Subscription> subscribeToSelection = selection -> {
EventStream<Integer> startParagraphValues = EventStreams.nonNullValuesOf(selection.startParagraphIndexProperty());
EventStream<Integer> endParagraphValues = EventStreams.nonNullValuesOf(selection.endParagraphIndexProperty());
// see comment in caret section about why a new box index EventStream is needed
EventStream<Integer> freshBoxIndexValues = box.indexProperty().values().filter(i -> i != -1);
return EventStreams.combine(startParagraphValues, endParagraphValues, freshBoxIndexValues)
.subscribe(t -> {
int startPar = t.get1();
int endPar = t.get2();
int boxIndex = t.get3();
if (startPar <= boxIndex && boxIndex <= endPar) {
// So that we don't add multiple paths for the same selection,
// which leads to not removing the additional paths when selection is removed,
// this is a `Map#putIfAbsent(Key, Value)` implementation that creates the path lazily
SelectionPath p = box.selectionsProperty().get(selection);
if (p == null) {
// create & configure path
Val<IndexRange> range = Val.create(
() -> box.getIndex() != -1
? getParagraphSelection(selection, box.getIndex())
: EMPTY_RANGE,
selection.rangeProperty()
);
SelectionPath path = new SelectionPath(range);
path.getStyleClass().add( selection.getSelectionName() );
selection.configureSelectionPath(path);
box.selectionsProperty().put(selection, path);
}
} else {
box.selectionsProperty().remove(selection);
}
});
};
Subscription selectionSubscription = selectionSet.addSubscriber(subscribeToSelection);
return new Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>() {
@Override
public ParagraphBox<PS, SEG, S> getNode() {
return box;
}
@Override
public void updateIndex(int index) {
box.setIndex(index);
}
@Override
public void dispose() {
box.highlightTextFillProperty().unbind();
box.wrapTextProperty().unbind();
box.graphicFactoryProperty().unbind();
box.graphicOffset.unbind();
box.dispose();
firstParPseudoClass.unsubscribe();
lastParPseudoClass.unsubscribe();
caretSubscription.unsubscribe();
hasCaretPseudoClass.unsubscribe();
selectionSubscription.unsubscribe();
}
};
}
/** Assumes this method is called within a {@link #suspendVisibleParsWhile(Runnable)} block */
private void followCaret() {
int parIdx = getCurrentParagraph();
ParagraphBox<PS, SEG, S> paragrafBox = virtualFlow.getCell( parIdx ).getNode();
Bounds caretBounds;
try {
// This is the default mechanism, but is also needed for https://github.com/FXMisc/RichTextFX/issues/1017
caretBounds = paragrafBox.getCaretBounds( caretSelectionBind.getUnderlyingCaret() );
}
catch ( IllegalArgumentException EX ) {
// This is an alternative mechanism, to address https://github.com/FXMisc/RichTextFX/issues/939
caretBounds = caretSelectionBind.getUnderlyingCaret().getLayoutBounds();
}
double graphicWidth = paragrafBox.getGraphicPrefWidth();
Bounds region = extendLeft(caretBounds, graphicWidth);
double scrollX = virtualFlow.getEstimatedScrollX();
// Ordinarily when a caret ends a selection in the target paragraph and scrolling left is required to follow
// the caret then the selection won't be visible. So here we check for this scenario and adjust if needed.
if ( ! isWrapText() && scrollX > 0.0 && getParagraphSelection( parIdx ).getLength() > 0 )
{
double visibleLeftX = paragrafBox.getWidth() * scrollX / 100 - getWidth() + graphicWidth;
CaretNode selectionStart = new CaretNode( "", this, getSelection().getStart() );
paragrafBox.caretsProperty().add( selectionStart );
Bounds startBounds = paragrafBox.getCaretBounds( selectionStart );
paragrafBox.caretsProperty().remove( selectionStart );
if ( startBounds.getMinX() - graphicWidth < visibleLeftX ) {
region = extendLeft( startBounds, graphicWidth );
}
}
// Addresses https://github.com/FXMisc/RichTextFX/issues/937#issuecomment-674319602
if ( parIdx == getParagraphs().size()-1 && paragrafBox.getLineCount() == 1 )
{
region = new BoundingBox // Correcting the region's height
(
region.getMinX(), region.getMinY(), region.getWidth(),
paragrafBox.getLayoutBounds().getHeight()
);
}
virtualFlow.show(parIdx, region);
}
private ParagraphBox<PS, SEG, S> getCell(int index) {
return virtualFlow.getCell(index).getNode();
}
private EventStream<MouseOverTextEvent> mouseOverTextEvents(ObservableSet<ParagraphBox<PS, SEG, S>> cells, Duration delay) {
return merge(cells, c -> c.stationaryIndices(delay).map(e -> e.unify(
l -> l.map((pos, charIdx) -> MouseOverTextEvent.beginAt(c.localToScreen(pos), getParagraphOffset(c.getIndex()) + charIdx)),
r -> MouseOverTextEvent.end())));
}
private int getParagraphOffset(int parIdx) {
return position(parIdx, 0).toOffset();
}
private Bounds getParagraphBoundsOnScreen(Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell) {
Bounds nodeLocal = cell.getNode().getBoundsInLocal();
Bounds nodeScreen = cell.getNode().localToScreen(nodeLocal);
Bounds areaLocal = getBoundsInLocal();
Bounds areaScreen = localToScreen(areaLocal);
// use area's minX if scrolled right and paragraph's left is not visible
double minX = nodeScreen.getMinX() < areaScreen.getMinX()
? areaScreen.getMinX()
: nodeScreen.getMinX();
// use area's minY if scrolled down vertically and paragraph's top is not visible
double minY = nodeScreen.getMinY() < areaScreen.getMinY()
? areaScreen.getMinY()
: nodeScreen.getMinY();
// use area's width whether paragraph spans outside of it or not
// so that short or long paragraph takes up the entire space
double width = areaScreen.getWidth();
// use area's maxY if scrolled up vertically and paragraph's bottom is not visible
double maxY = nodeScreen.getMaxY() < areaScreen.getMaxY()
? nodeScreen.getMaxY()
: areaScreen.getMaxY();
return new BoundingBox(minX, minY, width, maxY - minY);
}
private Optional<Bounds> getRangeBoundsOnScreen(int paragraphIndex, int from, int to) {
return virtualFlow.getCellIfVisible(paragraphIndex)
.map(c -> c.getNode().getRangeBoundsOnScreen(from, to));
}
private void manageSubscription(Subscription subscription) {
subscriptions = subscriptions.and(subscription);
}
private static Bounds extendLeft(Bounds b, double w) {
if(w == 0) {
return b;
} else {
return new BoundingBox(
b.getMinX() - w, b.getMinY(),
b.getWidth() + w, b.getHeight());
}
}
private void suspendVisibleParsWhile(Runnable runnable) {
Suspendable.combine(beingUpdated, visibleParagraphs).suspendWhile(runnable);
}
/* ********************************************************************** *
* *
* CSS *
* *
* ********************************************************************** */
private static final CssMetaData<GenericStyledArea<?, ?, ?>, Paint> HIGHLIGHT_TEXT_FILL = new CustomCssMetaData<>(
"-fx-highlight-text-fill", StyleConverter.getPaintConverter(), Color.WHITE, s -> s.highlightTextFill
);
private static final List<CssMetaData<? extends Styleable, ?>> CSS_META_DATA_LIST;
static {
List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<>(Region.getClassCssMetaData());
styleables.add(HIGHLIGHT_TEXT_FILL);
CSS_META_DATA_LIST = Collections.unmodifiableList(styleables);
}
@Override
public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() {
return CSS_META_DATA_LIST;
}
public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() {
return CSS_META_DATA_LIST;
}
}
|
richtextfx/src/main/java/org/fxmisc/richtext/GenericStyledArea.java
|
package org.fxmisc.richtext;
import static org.reactfx.EventStreams.*;
import static org.reactfx.util.Tuples.*;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.IntSupplier;
import java.util.function.IntUnaryOperator;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import javafx.application.ConditionalFeature;
import javafx.application.Platform;
import javafx.beans.NamedArg;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableSet;
import javafx.css.CssMetaData;
import javafx.css.PseudoClass;
import javafx.css.StyleConverter;
import javafx.css.Styleable;
import javafx.css.StyleableObjectProperty;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.BoundingBox;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.IndexRange;
import javafx.scene.input.InputMethodEvent;
import javafx.scene.input.InputMethodRequests;
import javafx.scene.input.InputMethodTextRun;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.text.TextFlow;
import org.fxmisc.flowless.Cell;
import org.fxmisc.flowless.VirtualFlow;
import org.fxmisc.flowless.VirtualFlowHit;
import org.fxmisc.flowless.Virtualized;
import org.fxmisc.flowless.VirtualizedScrollPane;
import org.fxmisc.richtext.model.Codec;
import org.fxmisc.richtext.model.EditableStyledDocument;
import org.fxmisc.richtext.model.GenericEditableStyledDocument;
import org.fxmisc.richtext.model.Paragraph;
import org.fxmisc.richtext.model.ReadOnlyStyledDocument;
import org.fxmisc.richtext.model.PlainTextChange;
import org.fxmisc.richtext.model.Replacement;
import org.fxmisc.richtext.model.RichTextChange;
import org.fxmisc.richtext.model.StyleSpans;
import org.fxmisc.richtext.model.StyledDocument;
import org.fxmisc.richtext.model.StyledSegment;
import org.fxmisc.richtext.model.TextOps;
import org.fxmisc.richtext.model.TwoDimensional;
import org.fxmisc.richtext.model.TwoLevelNavigator;
import org.fxmisc.richtext.event.MouseOverTextEvent;
import org.fxmisc.richtext.util.SubscribeableContentsObsSet;
import org.fxmisc.richtext.util.UndoUtils;
import org.fxmisc.undo.UndoManager;
import org.reactfx.EventStream;
import org.reactfx.EventStreams;
import org.reactfx.Guard;
import org.reactfx.Subscription;
import org.reactfx.Suspendable;
import org.reactfx.SuspendableEventStream;
import org.reactfx.SuspendableNo;
import org.reactfx.collection.LiveList;
import org.reactfx.collection.SuspendableList;
import org.reactfx.util.Tuple2;
import org.reactfx.value.Val;
import org.reactfx.value.Var;
/**
* Text editing control that renders and edits a {@link EditableStyledDocument}.
*
* Accepts user input (keyboard, mouse) and provides API to assign style to text ranges. It is suitable for
* syntax highlighting and rich-text editors.
*
* <h3>Adding Scrollbars to the Area</h3>
*
* <p>By default, scroll bars do not appear when the content spans outside of the viewport.
* To add scroll bars, the area needs to be wrapped in a {@link VirtualizedScrollPane}. For example, </p>
* <pre><code>
* // shows area without scroll bars
* InlineCssTextArea area = new InlineCssTextArea();
*
* // add scroll bars that will display as needed
* VirtualizedScrollPane<InlineCssTextArea> vsPane = new VirtualizedScrollPane<>(area);
*
* Parent parent = // creation code
* parent.getChildren().add(vsPane)
* </code></pre>
*
* <h3>Auto-Scrolling to the Caret</h3>
*
* <p>Every time the underlying {@link EditableStyledDocument} changes via user interaction (e.g. typing) through
* the {@code GenericStyledArea}, the area will scroll to insure the caret is kept in view. However, this does not
* occur if changes are done programmatically. For example, let's say the area is displaying the bottom part
* of the area's {@link EditableStyledDocument} and some code changes something in the top part of the document
* that is not currently visible. If there is no call to {@link #requestFollowCaret()} at the end of that code,
* the area will not auto-scroll to that section of the document. The change will occur, and the user will continue
* to see the bottom part of the document as before. If such a call is there, then the area will scroll
* to the top of the document and no longer display the bottom part of it.</p>
* <p>For example...</p>
* <pre><code>
* // assuming the user is currently seeing the top of the area
*
* // then changing the bottom, currently not visible part of the area...
* int startParIdx = 40;
* int startColPosition = 2;
* int endParIdx = 42;
* int endColPosition = 10;
*
* // ...by itself will not scroll the viewport to where the change occurs
* area.replaceText(startParIdx, startColPosition, endParIdx, endColPosition, "replacement text");
*
* // adding this line after the last modification to the area will cause the viewport to scroll to that change
* // leaving the following line out will leave the viewport unaffected and the user will not notice any difference
* area.requestFollowCaret();
* </code></pre>
*
* <p>Additionally, when overriding the default user-interaction behavior, remember to include a call
* to {@link #requestFollowCaret()}.</p>
*
* <h3>Setting the area's {@link UndoManager}</h3>
*
* <p>
* The default UndoManager can undo/redo either {@link PlainTextChange}s or {@link RichTextChange}s. To create
* your own specialized version that may use changes different than these (or a combination of these changes
* with others), create them using the convenient factory methods in {@link UndoUtils}.
* </p>
*
* <h3>Overriding default keyboard behavior</h3>
*
* {@code GenericStyledArea} uses {@link javafx.scene.input.KeyEvent#KEY_TYPED KEY_TYPED} to handle ordinary
* character input and {@link javafx.scene.input.KeyEvent#KEY_PRESSED KEY_PRESSED} to handle control key
* combinations (including Enter and Tab). To add or override some keyboard
* shortcuts, while keeping the rest in place, you would combine the default
* event handler with a new one that adds or overrides some of the default
* key combinations.
* <p>
* For example, this is how to bind {@code Ctrl+S} to the {@code save()} operation:
* </p>
* <pre><code>
* import static javafx.scene.input.KeyCode.*;
* import static javafx.scene.input.KeyCombination.*;
* import static org.fxmisc.wellbehaved.event.EventPattern.*;
* import static org.fxmisc.wellbehaved.event.InputMap.*;
*
* import org.fxmisc.wellbehaved.event.Nodes;
*
* // installs the following consume InputMap,
* // so that a CTRL+S event saves the document and consumes the event
* Nodes.addInputMap(area, consume(keyPressed(S, CONTROL_DOWN), event -> save()));
* </code></pre>
*
* <h3>Overriding default mouse behavior</h3>
*
* The area's default mouse behavior properly handles auto-scrolling and dragging the selected text to a new location.
* As such, some parts cannot be partially overridden without it affecting other behavior.
*
* <p>The following lists either {@link org.fxmisc.wellbehaved.event.EventPattern}s that cannot be
* overridden without negatively affecting the default mouse behavior or describe how to safely override things
* in a special way without disrupting the auto scroll behavior.</p>
* <ul>
* <li>
* <em>First (1 click count) Primary Button Mouse Pressed Events:</em>
* (<code>EventPattern.mousePressed(MouseButton.PRIMARY).onlyIf(e -> e.getClickCount() == 1)</code>).
* Do not override. Instead, use {@link #onOutsideSelectionMousePressed},
* {@link #onInsideSelectionMousePressReleased}, or see next item.
* </li>
* <li>(
* <em>All Other Mouse Pressed Events (e.g., Primary with 2+ click count):</em>
* Aside from hiding the context menu if it is showing (use {@link #hideContextMenu()} some((where in your
* overriding InputMap to maintain this behavior), these can be safely overridden via any of the
* {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate InputMapTemplate's factory methods} or
* {@link org.fxmisc.wellbehaved.event.InputMap InputMap's factory methods}.
* </li>
* <li>
* <em>Primary-Button-only Mouse Drag Detection Events:</em>
* (<code>EventPattern.eventType(MouseEvent.DRAG_DETECTED).onlyIf(e -> e.getButton() == MouseButton.PRIMARY && !e.isMiddleButtonDown() && !e.isSecondaryButtonDown())</code>).
* Do not override. Instead, use {@link #onNewSelectionDrag} or {@link #onSelectionDrag}.
* </li>
* <li>
* <em>Primary-Button-only Mouse Drag Events:</em>
* (<code>EventPattern.mouseDragged().onlyIf(e -> e.getButton() == MouseButton.PRIMARY && !e.isMiddleButtonDown() && !e.isSecondaryButtonDown())</code>)
* Do not override, but see next item.
* </li>
* <li>
* <em>All Other Mouse Drag Events:</em>
* You may safely override other Mouse Drag Events using different
* {@link org.fxmisc.wellbehaved.event.EventPattern}s without affecting default behavior only if
* process InputMaps (
* {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(javafx.event.EventType, BiFunction)},
* {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(org.fxmisc.wellbehaved.event.EventPattern, BiFunction)},
* {@link org.fxmisc.wellbehaved.event.InputMap#process(javafx.event.EventType, Function)}, or
* {@link org.fxmisc.wellbehaved.event.InputMap#process(org.fxmisc.wellbehaved.event.EventPattern, Function)}
* ) are used and {@link org.fxmisc.wellbehaved.event.InputHandler.Result#PROCEED} is returned.
* The area has a "catch all" Mouse Drag InputMap that will auto scroll towards the mouse drag event when it
* occurs outside the bounds of the area and will stop auto scrolling when the mouse event occurs within the
* area. However, this only works if the event is not consumed before the event reaches that InputMap.
* To insure the auto scroll feature is enabled, set {@link #isAutoScrollOnDragDesired()} to true in your
* process InputMap. If the feature is not desired for that specific drag event, set it to false in the
* process InputMap.
* <em>Note: Due to this "catch-all" nature, all Mouse Drag Events are consumed.</em>
* </li>
* <li>
* <em>Primary-Button-only Mouse Released Events:</em>
* (<code>EventPattern.mouseReleased().onlyIf(e -> e.getButton() == MouseButton.PRIMARY && !e.isMiddleButtonDown() && !e.isSecondaryButtonDown())</code>).
* Do not override. Instead, use {@link #onNewSelectionDragFinished}, {@link #onSelectionDropped}, or see next item.
* </li>
* <li>
* <em>All other Mouse Released Events:</em>
* You may override other Mouse Released Events using different
* {@link org.fxmisc.wellbehaved.event.EventPattern}s without affecting default behavior only if
* process InputMaps (
* {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(javafx.event.EventType, BiFunction)},
* {@link org.fxmisc.wellbehaved.event.template.InputMapTemplate#process(org.fxmisc.wellbehaved.event.EventPattern, BiFunction)},
* {@link org.fxmisc.wellbehaved.event.InputMap#process(javafx.event.EventType, Function)}, or
* {@link org.fxmisc.wellbehaved.event.InputMap#process(org.fxmisc.wellbehaved.event.EventPattern, Function)}
* ) are used and {@link org.fxmisc.wellbehaved.event.InputHandler.Result#PROCEED} is returned.
* The area has a "catch-all" InputMap that will consume all mouse released events and stop auto scroll if it
* was scrolling. However, this only works if the event is not consumed before the event reaches that InputMap.
* <em>Note: Due to this "catch-all" nature, all Mouse Released Events are consumed.</em>
* </li>
* </ul>
*
* <h3>CSS, Style Classes, and Pseudo Classes</h3>
* <p>
* Refer to the <a href="https://github.com/FXMisc/RichTextFX/wiki/RichTextFX-CSS-Reference-Guide">
* RichTextFX CSS Reference Guide
* </a>.
* </p>
*
* <h3>Area Actions and Other Operations</h3>
* <p>
* To distinguish the actual operations one can do on this area from the boilerplate methods
* within this area (e.g. properties and their getters/setters, etc.), look at the interfaces
* this area implements. Each lists and documents methods that fall under that category.
* </p>
* <p>
* To update multiple portions of the area's underlying document in one call, see {@link #createMultiChange()}.
* </p>
*
* <h3>Calculating a Position Within the Area</h3>
* <p>
* To calculate a position or index within the area, read through the javadoc of
* {@link org.fxmisc.richtext.model.TwoDimensional} and {@link org.fxmisc.richtext.model.TwoDimensional.Bias}.
* Also, read the difference between "position" and "index" in
* {@link org.fxmisc.richtext.model.StyledDocument#getAbsolutePosition(int, int)}.
* </p>
*
* @see EditableStyledDocument
* @see TwoDimensional
* @see org.fxmisc.richtext.model.TwoDimensional.Bias
* @see VirtualFlow
* @see VirtualizedScrollPane
* @see Caret
* @see Selection
* @see CaretSelectionBind
*
* @param <PS> type of style that can be applied to paragraphs (e.g. {@link TextFlow}.
* @param <SEG> type of segment used in {@link Paragraph}. Can be only text (plain or styled) or
* a type that combines text and other {@link Node}s.
* @param <S> type of style that can be applied to a segment.
*/
public class GenericStyledArea<PS, SEG, S> extends Region
implements
TextEditingArea<PS, SEG, S>,
EditActions<PS, SEG, S>,
ClipboardActions<PS, SEG, S>,
NavigationActions<PS, SEG, S>,
StyleActions<PS, S>,
UndoActions,
ViewActions<PS, SEG, S>,
TwoDimensional,
Virtualized {
/**
* Index range [0, 0).
*/
public static final IndexRange EMPTY_RANGE = new IndexRange(0, 0);
private static final PseudoClass READ_ONLY = PseudoClass.getPseudoClass("readonly");
private static final PseudoClass HAS_CARET = PseudoClass.getPseudoClass("has-caret");
private static final PseudoClass FIRST_PAR = PseudoClass.getPseudoClass("first-paragraph");
private static final PseudoClass LAST_PAR = PseudoClass.getPseudoClass("last-paragraph");
/* ********************************************************************** *
* *
* Properties *
* *
* Properties affect behavior and/or appearance of this control. *
* *
* They are readable and writable by the client code and never change by *
* other means, i.e. they contain either the default value or the value *
* set by the client code. *
* *
* ********************************************************************** */
/**
* Text color for highlighted text.
*/
private final StyleableObjectProperty<Paint> highlightTextFill
= new CustomStyleableProperty<>(Color.WHITE, "highlightTextFill", this, HIGHLIGHT_TEXT_FILL);
// editable property
private final BooleanProperty editable = new SimpleBooleanProperty(this, "editable", true) {
@Override
protected void invalidated() {
((Region) getBean()).pseudoClassStateChanged(READ_ONLY, !get());
}
};
@Override public final BooleanProperty editableProperty() { return editable; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setEditable(boolean value) { editable.set(value); }
@Override public boolean isEditable() { return editable.get(); }
// wrapText property
private final BooleanProperty wrapText = new SimpleBooleanProperty(this, "wrapText");
@Override public final BooleanProperty wrapTextProperty() { return wrapText; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setWrapText(boolean value) { wrapText.set(value); }
@Override public boolean isWrapText() { return wrapText.get(); }
// undo manager
private UndoManager undoManager;
@Override public UndoManager getUndoManager() { return undoManager; }
/**
* @param undoManager may be null in which case a no op undo manager will be set.
*/
@Override public void setUndoManager(UndoManager undoManager) {
this.undoManager.close();
this.undoManager = undoManager != null ? undoManager : UndoUtils.noOpUndoManager();
}
private Locale textLocale = Locale.getDefault();
/**
* This is used to determine word and sentence breaks while navigating or selecting.
* Override this method if your paragraph or text style accommodates Locales as well.
* @return Locale.getDefault() by default
*/
@Override
public Locale getLocale() { return textLocale; }
public void setLocale( Locale editorLocale ) {
textLocale = editorLocale;
}
private final ObjectProperty<Duration> mouseOverTextDelay = new SimpleObjectProperty<>(null);
@Override public ObjectProperty<Duration> mouseOverTextDelayProperty() { return mouseOverTextDelay; }
private final ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactory = new SimpleObjectProperty<>(null);
@Override public ObjectProperty<IntFunction<? extends Node>> paragraphGraphicFactoryProperty() { return paragraphGraphicFactory; }
public void recreateParagraphGraphic( int parNdx ) {
ObjectProperty<IntFunction<? extends Node>> gProp;
gProp = getCell(parNdx).graphicFactoryProperty();
gProp.unbind();
gProp.bind(paragraphGraphicFactoryProperty());
}
public Node getParagraphGraphic( int parNdx ) {
return getCell(parNdx).getGraphic();
}
/**
* This Node is shown to the user, centered over the area, when the area has no text content.
* <br>To customize the placeholder's layout override {@link #configurePlaceholder( Node )}
*/
public final void setPlaceholder(Node value) { setPlaceholder(value,Pos.CENTER); }
public void setPlaceholder(Node value, Pos where) { placeHolderProp.set(value); placeHolderPos = Objects.requireNonNull(where); }
private ObjectProperty<Node> placeHolderProp = new SimpleObjectProperty<>(this, "placeHolder", null);
public final ObjectProperty<Node> placeholderProperty() { return placeHolderProp; }
public final Node getPlaceholder() { return placeHolderProp.get(); }
private Pos placeHolderPos = Pos.CENTER;
private ObjectProperty<ContextMenu> contextMenu = new SimpleObjectProperty<>(null);
@Override public final ObjectProperty<ContextMenu> contextMenuObjectProperty() { return contextMenu; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setContextMenu(ContextMenu menu) { contextMenu.set(menu); }
@Override public ContextMenu getContextMenu() { return contextMenu.get(); }
protected final boolean isContextMenuPresent() { return contextMenu.get() != null; }
private DoubleProperty contextMenuXOffset = new SimpleDoubleProperty(2);
@Override public final DoubleProperty contextMenuXOffsetProperty() { return contextMenuXOffset; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setContextMenuXOffset(double offset) { contextMenuXOffset.set(offset); }
@Override public double getContextMenuXOffset() { return contextMenuXOffset.get(); }
private DoubleProperty contextMenuYOffset = new SimpleDoubleProperty(2);
@Override public final DoubleProperty contextMenuYOffsetProperty() { return contextMenuYOffset; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setContextMenuYOffset(double offset) { contextMenuYOffset.set(offset); }
@Override public double getContextMenuYOffset() { return contextMenuYOffset.get(); }
private final BooleanProperty useInitialStyleForInsertion = new SimpleBooleanProperty();
@Override public BooleanProperty useInitialStyleForInsertionProperty() { return useInitialStyleForInsertion; }
private Optional<Tuple2<Codec<PS>, Codec<StyledSegment<SEG, S>>>> styleCodecs = Optional.empty();
@Override public void setStyleCodecs(Codec<PS> paragraphStyleCodec, Codec<StyledSegment<SEG, S>> styledSegCodec) {
styleCodecs = Optional.of(t(paragraphStyleCodec, styledSegCodec));
}
@Override public Optional<Tuple2<Codec<PS>, Codec<StyledSegment<SEG, S>>>> getStyleCodecs() {
return styleCodecs;
}
@Override public Var<Double> estimatedScrollXProperty() { return virtualFlow.estimatedScrollXProperty(); }
@Override public Var<Double> estimatedScrollYProperty() { return virtualFlow.estimatedScrollYProperty(); }
private final SubscribeableContentsObsSet<CaretNode> caretSet;
private final SubscribeableContentsObsSet<Selection<PS, SEG, S>> selectionSet;
public final boolean addCaret(CaretNode caret) {
if (caret.getArea() != this) {
throw new IllegalArgumentException(String.format(
"The caret (%s) is associated with a different area (%s), " +
"not this area (%s)", caret, caret.getArea(), this));
}
return caretSet.add(caret);
}
public final boolean removeCaret(CaretNode caret) {
if (caret != caretSelectionBind.getUnderlyingCaret()) {
return caretSet.remove(caret);
} else {
return false;
}
}
public final boolean addSelection(Selection<PS, SEG, S> selection) {
if (selection.getArea() != this) {
throw new IllegalArgumentException(String.format(
"The selection (%s) is associated with a different area (%s), " +
"not this area (%s)", selection, selection.getArea(), this));
}
return selectionSet.add(selection);
}
public final boolean removeSelection(Selection<PS, SEG, S> selection) {
if (selection != caretSelectionBind.getUnderlyingSelection()) {
return selectionSet.remove(selection);
} else {
return false;
}
}
/* ********************************************************************** *
* *
* Mouse Behavior Hooks *
* *
* Hooks for overriding some of the default mouse behavior *
* *
* ********************************************************************** */
@Override public final EventHandler<MouseEvent> getOnOutsideSelectionMousePressed() { return onOutsideSelectionMousePressed.get(); }
@Override public final void setOnOutsideSelectionMousePressed(EventHandler<MouseEvent> handler) { onOutsideSelectionMousePressed.set( handler ); }
@Override public final ObjectProperty<EventHandler<MouseEvent>> onOutsideSelectionMousePressedProperty() { return onOutsideSelectionMousePressed; }
private final ObjectProperty<EventHandler<MouseEvent>> onOutsideSelectionMousePressed = new SimpleObjectProperty<>( e -> {
moveTo( hit( e.getX(), e.getY() ).getInsertionIndex(), SelectionPolicy.CLEAR );
});
@Override public final EventHandler<MouseEvent> getOnInsideSelectionMousePressReleased() { return onInsideSelectionMousePressReleased.get(); }
@Override public final void setOnInsideSelectionMousePressReleased(EventHandler<MouseEvent> handler) { onInsideSelectionMousePressReleased.set( handler ); }
@Override public final ObjectProperty<EventHandler<MouseEvent>> onInsideSelectionMousePressReleasedProperty() { return onInsideSelectionMousePressReleased; }
private final ObjectProperty<EventHandler<MouseEvent>> onInsideSelectionMousePressReleased = new SimpleObjectProperty<>( e -> {
moveTo( hit( e.getX(), e.getY() ).getInsertionIndex(), SelectionPolicy.CLEAR );
});
private final ObjectProperty<Consumer<Point2D>> onNewSelectionDrag = new SimpleObjectProperty<>(p -> {
CharacterHit hit = hit(p.getX(), p.getY());
moveTo(hit.getInsertionIndex(), SelectionPolicy.ADJUST);
});
@Override public final ObjectProperty<Consumer<Point2D>> onNewSelectionDragProperty() { return onNewSelectionDrag; }
@Override public final EventHandler<MouseEvent> getOnNewSelectionDragFinished() { return onNewSelectionDragFinished.get(); }
@Override public final void setOnNewSelectionDragFinished(EventHandler<MouseEvent> handler) { onNewSelectionDragFinished.set( handler ); }
@Override public final ObjectProperty<EventHandler<MouseEvent>> onNewSelectionDragFinishedProperty() { return onNewSelectionDragFinished; }
private final ObjectProperty<EventHandler<MouseEvent>> onNewSelectionDragFinished = new SimpleObjectProperty<>( e -> {
CharacterHit hit = hit(e.getX(), e.getY());
moveTo(hit.getInsertionIndex(), SelectionPolicy.ADJUST);
});
private final ObjectProperty<Consumer<Point2D>> onSelectionDrag = new SimpleObjectProperty<>(p -> {
CharacterHit hit = hit(p.getX(), p.getY());
displaceCaret(hit.getInsertionIndex());
});
@Override public final ObjectProperty<Consumer<Point2D>> onSelectionDragProperty() { return onSelectionDrag; }
@Override public final EventHandler<MouseEvent> getOnSelectionDropped() { return onSelectionDropped.get(); }
@Override public final void setOnSelectionDropped(EventHandler<MouseEvent> handler) { onSelectionDropped.set( handler ); }
@Override public final ObjectProperty<EventHandler<MouseEvent>> onSelectionDroppedProperty() { return onSelectionDropped; }
private final ObjectProperty<EventHandler<MouseEvent>> onSelectionDropped = new SimpleObjectProperty<>( e -> {
moveSelectedText( hit( e.getX(), e.getY() ).getInsertionIndex() );
});
// not a hook, but still plays a part in the default mouse behavior
private final BooleanProperty autoScrollOnDragDesired = new SimpleBooleanProperty(true);
@Override public final BooleanProperty autoScrollOnDragDesiredProperty() { return autoScrollOnDragDesired; }
// Don't remove as FXMLLoader doesn't recognise default methods !
@Override public void setAutoScrollOnDragDesired(boolean val) { autoScrollOnDragDesired.set(val); }
@Override public boolean isAutoScrollOnDragDesired() { return autoScrollOnDragDesired.get(); }
/* ********************************************************************** *
* *
* Observables *
* *
* Observables are "dynamic" (i.e. changing) characteristics of this *
* control. They are not directly settable by the client code, but change *
* in response to user input and/or API actions. *
* *
* ********************************************************************** */
// text
@Override public final ObservableValue<String> textProperty() { return content.textProperty(); }
// rich text
@Override public final StyledDocument<PS, SEG, S> getDocument() { return content; }
private CaretSelectionBind<PS, SEG, S> caretSelectionBind;
@Override public final CaretSelectionBind<PS, SEG, S> getCaretSelectionBind() { return caretSelectionBind; }
// length
@Override public final ObservableValue<Integer> lengthProperty() { return content.lengthProperty(); }
// paragraphs
@Override public LiveList<Paragraph<PS, SEG, S>> getParagraphs() { return content.getParagraphs(); }
private final SuspendableList<Paragraph<PS, SEG, S>> visibleParagraphs;
@Override public final LiveList<Paragraph<PS, SEG, S>> getVisibleParagraphs() { return visibleParagraphs; }
// beingUpdated
private final SuspendableNo beingUpdated = new SuspendableNo();
@Override public final SuspendableNo beingUpdatedProperty() { return beingUpdated; }
// total width estimate
@Override public Val<Double> totalWidthEstimateProperty() { return virtualFlow.totalWidthEstimateProperty(); }
// total height estimate
@Override public Val<Double> totalHeightEstimateProperty() { return virtualFlow.totalHeightEstimateProperty(); }
/* ********************************************************************** *
* *
* Event streams *
* *
* ********************************************************************** */
@Override public EventStream<List<RichTextChange<PS, SEG, S>>> multiRichChanges() { return content.multiRichChanges(); }
@Override public EventStream<List<PlainTextChange>> multiPlainChanges() { return content.multiPlainChanges(); }
// text changes
@Override public final EventStream<PlainTextChange> plainTextChanges() { return content.plainChanges(); }
// rich text changes
@Override public final EventStream<RichTextChange<PS, SEG, S>> richChanges() { return content.richChanges(); }
private final SuspendableEventStream<?> viewportDirty;
@Override public final EventStream<?> viewportDirtyEvents() { return viewportDirty; }
/* ********************************************************************** *
* *
* Private fields *
* *
* ********************************************************************** */
private Subscription subscriptions = () -> {};
private final VirtualFlow<Paragraph<PS, SEG, S>, Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> virtualFlow;
// used for two-level navigation, where on the higher level are
// paragraphs and on the lower level are lines within a paragraph
private final TwoLevelNavigator paragraphLineNavigator;
private boolean paging, followCaretRequested = false;
/* ********************************************************************** *
* *
* Fields necessary for Cloning *
* *
* ********************************************************************** */
private final EditableStyledDocument<PS, SEG, S> content;
@Override public final EditableStyledDocument<PS, SEG, S> getContent() { return content; }
private final S initialTextStyle;
@Override public final S getInitialTextStyle() { return initialTextStyle; }
private final PS initialParagraphStyle;
@Override public final PS getInitialParagraphStyle() { return initialParagraphStyle; }
private final BiConsumer<TextFlow, PS> applyParagraphStyle;
@Override public final BiConsumer<TextFlow, PS> getApplyParagraphStyle() { return applyParagraphStyle; }
// TODO: Currently, only undo/redo respect this flag.
private final boolean preserveStyle;
@Override public final boolean isPreserveStyle() { return preserveStyle; }
/* ********************************************************************** *
* *
* Miscellaneous *
* *
* ********************************************************************** */
private final TextOps<SEG, S> segmentOps;
@Override public final TextOps<SEG, S> getSegOps() { return segmentOps; }
private final EventStream<Boolean> autoCaretBlinksSteam;
final EventStream<Boolean> autoCaretBlink() { return autoCaretBlinksSteam; }
/* ********************************************************************** *
* *
* Constructors *
* *
* ********************************************************************** */
/**
* Creates a text area with empty text content.
*
* @param initialParagraphStyle style to use in places where no other style is
* specified (yet).
* @param applyParagraphStyle function that, given a {@link TextFlow} node and
* a style, applies the style to the paragraph node. This function is
* used by the default skin to apply style to paragraph nodes.
* @param initialTextStyle style to use in places where no other style is
* specified (yet).
* @param segmentOps The operations which are defined on the text segment objects.
* @param nodeFactory A function which is used to create the JavaFX scene nodes for a
* particular segment.
*/
public GenericStyledArea(@NamedArg("initialParagraphStyle") PS initialParagraphStyle,
@NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle,
@NamedArg("initialTextStyle") S initialTextStyle,
@NamedArg("segmentOps") TextOps<SEG, S> segmentOps,
@NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) {
this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, segmentOps, true, nodeFactory);
}
/**
* Same as {@link #GenericStyledArea(Object, BiConsumer, Object, TextOps, Function)} but also allows one
* to specify whether the undo manager should be a plain or rich undo manager via {@code preserveStyle}.
*
* @param initialParagraphStyle style to use in places where no other style is specified (yet).
* @param applyParagraphStyle function that, given a {@link TextFlow} node and
* a style, applies the style to the paragraph node. This function is
* used by the default skin to apply style to paragraph nodes.
* @param initialTextStyle style to use in places where no other style is specified (yet).
* @param segmentOps The operations which are defined on the text segment objects.
* @param preserveStyle whether to use an undo manager that can undo/redo {@link RichTextChange}s or
* {@link PlainTextChange}s
* @param nodeFactory A function which is used to create the JavaFX scene node for a particular segment.
*/
public GenericStyledArea(@NamedArg("initialParagraphStyle") PS initialParagraphStyle,
@NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle,
@NamedArg("initialTextStyle") S initialTextStyle,
@NamedArg("segmentOps") TextOps<SEG, S> segmentOps,
@NamedArg("preserveStyle") boolean preserveStyle,
@NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) {
this(initialParagraphStyle, applyParagraphStyle, initialTextStyle,
new GenericEditableStyledDocument<>(initialParagraphStyle, initialTextStyle, segmentOps), segmentOps, preserveStyle, nodeFactory);
}
/**
* The same as {@link #GenericStyledArea(Object, BiConsumer, Object, TextOps, Function)} except that
* this constructor can be used to create another {@code GenericStyledArea} that renders and edits the same
* {@link EditableStyledDocument} or when one wants to use a custom {@link EditableStyledDocument} implementation.
*/
public GenericStyledArea(
@NamedArg("initialParagraphStyle") PS initialParagraphStyle,
@NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle,
@NamedArg("initialTextStyle") S initialTextStyle,
@NamedArg("document") EditableStyledDocument<PS, SEG, S> document,
@NamedArg("segmentOps") TextOps<SEG, S> segmentOps,
@NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) {
this(initialParagraphStyle, applyParagraphStyle, initialTextStyle, document, segmentOps, true, nodeFactory);
}
/**
* Creates an area with flexibility in all of its options.
*
* @param initialParagraphStyle style to use in places where no other style is specified (yet).
* @param applyParagraphStyle function that, given a {@link TextFlow} node and
* a style, applies the style to the paragraph node. This function is
* used by the default skin to apply style to paragraph nodes.
* @param initialTextStyle style to use in places where no other style is specified (yet).
* @param document the document to render and edit
* @param segmentOps The operations which are defined on the text segment objects.
* @param preserveStyle whether to use an undo manager that can undo/redo {@link RichTextChange}s or
* {@link PlainTextChange}s
* @param nodeFactory A function which is used to create the JavaFX scene node for a particular segment.
*/
public GenericStyledArea(
@NamedArg("initialParagraphStyle") PS initialParagraphStyle,
@NamedArg("applyParagraphStyle") BiConsumer<TextFlow, PS> applyParagraphStyle,
@NamedArg("initialTextStyle") S initialTextStyle,
@NamedArg("document") EditableStyledDocument<PS, SEG, S> document,
@NamedArg("segmentOps") TextOps<SEG, S> segmentOps,
@NamedArg("preserveStyle") boolean preserveStyle,
@NamedArg("nodeFactory") Function<StyledSegment<SEG, S>, Node> nodeFactory) {
this.initialTextStyle = initialTextStyle;
this.initialParagraphStyle = initialParagraphStyle;
this.preserveStyle = preserveStyle;
this.content = document;
this.applyParagraphStyle = applyParagraphStyle;
this.segmentOps = segmentOps;
undoManager = UndoUtils.defaultUndoManager(this);
// allow tab traversal into area
setFocusTraversable(true);
this.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
getStyleClass().add("styled-text-area");
getStylesheets().add(StyledTextArea.class.getResource("styled-text-area.css").toExternalForm());
// keeps track of currently used non-empty cells
@SuppressWarnings("unchecked")
ObservableSet<ParagraphBox<PS, SEG, S>> nonEmptyCells = FXCollections.observableSet();
caretSet = new SubscribeableContentsObsSet<>();
manageSubscription(() -> {
List<CaretNode> l = new ArrayList<>(caretSet);
caretSet.clear();
l.forEach(CaretNode::dispose);
});
selectionSet = new SubscribeableContentsObsSet<>();
manageSubscription(() -> {
List<Selection<PS, SEG, S>> l = new ArrayList<>(selectionSet);
selectionSet.clear();
l.forEach(Selection::dispose);
});
// Initialize content
virtualFlow = VirtualFlow.createVertical(
getParagraphs(),
par -> {
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = createCell(
par,
applyParagraphStyle,
nodeFactory);
nonEmptyCells.add(cell.getNode());
return cell.beforeReset(() -> nonEmptyCells.remove(cell.getNode()))
.afterUpdateItem(p -> nonEmptyCells.add(cell.getNode()));
});
getChildren().add(virtualFlow);
// initialize navigator
IntSupplier cellCount = () -> getParagraphs().size();
IntUnaryOperator cellLength = i -> virtualFlow.getCell(i).getNode().getLineCount();
paragraphLineNavigator = new TwoLevelNavigator(cellCount, cellLength);
viewportDirty = merge(
// no need to check for width & height invalidations as scroll values update when these do
// scale
invalidationsOf(scaleXProperty()),
invalidationsOf(scaleYProperty()),
// scroll
invalidationsOf(estimatedScrollXProperty()),
invalidationsOf(estimatedScrollYProperty())
).suppressible();
autoCaretBlinksSteam = EventStreams.valuesOf(focusedProperty()
.and(editableProperty())
.and(disabledProperty().not())
);
caretSelectionBind = new CaretSelectionBindImpl<>("main-caret", "main-selection",this);
caretSelectionBind.paragraphIndexProperty().addListener( this::skipOverFoldedParagraphs );
caretSet.add(caretSelectionBind.getUnderlyingCaret());
selectionSet.add(caretSelectionBind.getUnderlyingSelection());
visibleParagraphs = LiveList.map(virtualFlow.visibleCells(), c -> c.getNode().getParagraph()).suspendable();
final Suspendable omniSuspendable = Suspendable.combine(
beingUpdated, // must be first, to be the last one to release
visibleParagraphs
);
manageSubscription(omniSuspendable.suspendWhen(content.beingUpdatedProperty()));
// dispatch MouseOverTextEvents when mouseOverTextDelay is not null
EventStreams.valuesOf(mouseOverTextDelayProperty())
.flatMap(delay -> delay != null
? mouseOverTextEvents(nonEmptyCells, delay)
: EventStreams.never())
.subscribe(evt -> Event.fireEvent(this, evt));
new GenericStyledAreaBehavior(this);
// Setup place holder visibility & placement
final Val<Boolean> showPlaceholder = Val.create
(
() -> getLength() == 0 && ! isFocused(),
lengthProperty(), focusedProperty()
);
placeHolderProp.addListener( (ob,ov,newNode) -> displayPlaceHolder( showPlaceholder.getValue(), newNode ) );
showPlaceholder.addListener( (ob,ov,show) -> displayPlaceHolder( show, getPlaceholder() ) );
if ( Platform.isFxApplicationThread() ) initInputMethodHandling();
else Platform.runLater( () -> initInputMethodHandling() );
}
private void initInputMethodHandling()
{
if( Platform.isSupported( ConditionalFeature.INPUT_METHOD ) )
{
setOnInputMethodTextChanged( event -> handleInputMethodEvent(event) );
// Both of these have to be set for input composition to work !
setInputMethodRequests( new InputMethodRequests()
{
@Override public Point2D getTextLocation( int offset ) {
Bounds charBounds = getCaretBounds().get();
return new Point2D( charBounds.getMaxX() - 5, charBounds.getMaxY() );
}
@Override public int getLocationOffset( int x, int y ) {
return 0;
}
@Override public void cancelLatestCommittedText() {}
@Override public String getSelectedText() {
return getSelectedText();
}
});
}
}
// Start/Length of the text under input method composition
private int imstart;
private int imlength;
protected void handleInputMethodEvent( InputMethodEvent event )
{
if ( isEditable() && !isDisabled() )
{
// remove previous input method text (if any) or selected text
if ( imlength != 0 ) {
selectRange( imstart, imstart + imlength );
}
// Insert committed text
if ( event.getCommitted().length() != 0 ) {
replaceText( getSelection(), event.getCommitted() );
}
// Replace composed text
imstart = getSelection().getStart();
StringBuilder composed = new StringBuilder();
for ( InputMethodTextRun run : event.getComposed() ) {
composed.append( run.getText() );
}
replaceText( getSelection(), composed.toString() );
imlength = composed.length();
if ( imlength != 0 )
{
int pos = imstart;
for ( InputMethodTextRun run : event.getComposed() ) {
int endPos = pos + run.getText().length();
pos = endPos;
}
// Set caret position in composed text
int caretPos = event.getCaretPosition();
if ( caretPos >= 0 && caretPos < imlength ) {
selectRange( imstart + caretPos, imstart + caretPos );
}
}
}
}
private Node placeholder;
private boolean positionPlaceholder = false;
private void displayPlaceHolder( boolean show, Node newNode )
{
if ( placeholder != null && (! show || newNode != placeholder) )
{
placeholder.layoutXProperty().unbind();
placeholder.layoutYProperty().unbind();
getChildren().remove( placeholder );
placeholder = null;
setClip( null );
}
if ( newNode != null && show && newNode != placeholder )
{
configurePlaceholder( newNode );
getChildren().add( newNode );
placeholder = newNode;
}
}
/**
* Override this to customize the placeholder's layout.
* <br>The default position is centered over the area.
*/
protected void configurePlaceholder( Node placeholder )
{
positionPlaceholder = true;
}
/* ********************************************************************** *
* *
* Queries *
* *
* Queries are parameterized observables. *
* *
* ********************************************************************** */
@Override
public final double getViewportHeight() {
return virtualFlow.getHeight();
}
@Override
public final Optional<Integer> allParToVisibleParIndex(int allParIndex) {
if (allParIndex < 0) {
throw new IllegalArgumentException("The given paragraph index (allParIndex) cannot be negative but was " + allParIndex);
}
if (allParIndex >= getParagraphs().size()) {
throw new IllegalArgumentException(String.format(
"Paragraphs' last index is [%s] but allParIndex was [%s]",
getParagraphs().size() - 1, allParIndex)
);
}
List<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> visibleList = virtualFlow.visibleCells();
int firstVisibleParIndex = visibleList.get( 0 ).getNode().getIndex();
int targetIndex = allParIndex - firstVisibleParIndex;
if ( allParIndex >= firstVisibleParIndex && targetIndex < visibleList.size() )
{
if ( visibleList.get( targetIndex ).getNode().getIndex() == allParIndex )
{
return Optional.of( targetIndex );
}
}
return Optional.empty();
}
@Override
public final int visibleParToAllParIndex(int visibleParIndex) {
if (visibleParIndex < 0) {
throw new IllegalArgumentException("Visible paragraph index cannot be negative but was " + visibleParIndex);
}
if (visibleParIndex > 0 && visibleParIndex >= getVisibleParagraphs().size()) {
throw new IllegalArgumentException(String.format(
"Visible paragraphs' last index is [%s] but visibleParIndex was [%s]",
getVisibleParagraphs().size() - 1, visibleParIndex)
);
}
Cell<Paragraph<PS,SEG,S>, ParagraphBox<PS,SEG,S>> visibleCell = null;
if ( visibleParIndex > 0 ) visibleCell = virtualFlow.visibleCells().get( visibleParIndex );
else visibleCell = virtualFlow.getCellIfVisible( virtualFlow.getFirstVisibleIndex() )
.orElseGet( () -> virtualFlow.visibleCells().get( visibleParIndex ) );
return visibleCell.getNode().getIndex();
}
@Override
public CharacterHit hit(double x, double y) {
// mouse position used, so account for padding
double adjustedX = x - getInsets().getLeft();
double adjustedY = y - getInsets().getTop();
VirtualFlowHit<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> hit = virtualFlow.hit(adjustedX, adjustedY);
if(hit.isBeforeCells()) {
return CharacterHit.insertionAt(0);
} else if(hit.isAfterCells()) {
return CharacterHit.insertionAt(getLength());
} else {
int parIdx = hit.getCellIndex();
int parOffset = getParagraphOffset(parIdx);
ParagraphBox<PS, SEG, S> cell = hit.getCell().getNode();
Point2D cellOffset = hit.getCellOffset();
CharacterHit parHit = cell.hit(cellOffset);
return parHit.offset(parOffset);
}
}
@Override
public final int lineIndex(int paragraphIndex, int columnPosition) {
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(paragraphIndex);
return cell.getNode().getCurrentLineIndex(columnPosition);
}
@Override
public int getParagraphLinesCount(int paragraphIndex) {
return virtualFlow.getCell(paragraphIndex).getNode().getLineCount();
}
@Override
public Optional<Bounds> getCharacterBoundsOnScreen(int from, int to) {
if (from < 0) {
throw new IllegalArgumentException("From is negative: " + from);
}
if (from > to) {
throw new IllegalArgumentException(String.format("From is greater than to. from=%s to=%s", from, to));
}
if (to > getLength()) {
throw new IllegalArgumentException(String.format("To is greater than area's length. length=%s, to=%s", getLength(), to));
}
// no bounds exist if range is just a newline character
if (getText(from, to).equals("\n")) {
return Optional.empty();
}
// if 'from' is the newline character at the end of a multi-line paragraph, it returns a Bounds that whose
// minX & minY are the minX and minY of the paragraph itself, not the newline character. So, ignore it.
int realFrom = getText(from, from + 1).equals("\n") ? from + 1 : from;
Position startPosition = offsetToPosition(realFrom, Bias.Forward);
int startRow = startPosition.getMajor();
Position endPosition = startPosition.offsetBy(to - realFrom, Bias.Forward);
int endRow = endPosition.getMajor();
if (startRow == endRow) {
return getRangeBoundsOnScreen(startRow, startPosition.getMinor(), endPosition.getMinor());
} else {
Optional<Bounds> rangeBounds = getRangeBoundsOnScreen(startRow, startPosition.getMinor(),
getParagraph(startRow).length());
for (int i = startRow + 1; i <= endRow; i++) {
Optional<Bounds> nextLineBounds = getRangeBoundsOnScreen(i, 0,
i == endRow
? endPosition.getMinor()
: getParagraph(i).length()
);
if (nextLineBounds.isPresent()) {
if (rangeBounds.isPresent()) {
Bounds lineBounds = nextLineBounds.get();
rangeBounds = rangeBounds.map(b -> {
double minX = Math.min(b.getMinX(), lineBounds.getMinX());
double minY = Math.min(b.getMinY(), lineBounds.getMinY());
double maxX = Math.max(b.getMaxX(), lineBounds.getMaxX());
double maxY = Math.max(b.getMaxY(), lineBounds.getMaxY());
return new BoundingBox(minX, minY, maxX - minX, maxY - minY);
});
} else {
rangeBounds = nextLineBounds;
}
}
}
return rangeBounds;
}
}
@Override
public final String getText(int start, int end) {
return content.getText(start, end);
}
@Override
public String getText(int paragraph) {
return content.getText(paragraph);
}
@Override
public String getText(IndexRange range) {
return content.getText(range);
}
@Override
public StyledDocument<PS, SEG, S> subDocument(int start, int end) {
return content.subSequence(start, end);
}
@Override
public StyledDocument<PS, SEG, S> subDocument(int paragraphIndex) {
return content.subDocument(paragraphIndex);
}
@Override
public IndexRange getParagraphSelection(Selection selection, int paragraph) {
int startPar = selection.getStartParagraphIndex();
int endPar = selection.getEndParagraphIndex();
if(selection.getLength() == 0 || paragraph < startPar || paragraph > endPar) {
return EMPTY_RANGE;
}
int start = paragraph == startPar ? selection.getStartColumnPosition() : 0;
int end = paragraph == endPar ? selection.getEndColumnPosition() : getParagraphLength(paragraph) + 1;
// force rangeProperty() to be valid
selection.getRange();
return new IndexRange(start, end);
}
@Override
public S getStyleOfChar(int index) {
return content.getStyleOfChar(index);
}
@Override
public S getStyleAtPosition(int position) {
return content.getStyleAtPosition(position);
}
@Override
public IndexRange getStyleRangeAtPosition(int position) {
return content.getStyleRangeAtPosition(position);
}
@Override
public StyleSpans<S> getStyleSpans(int from, int to) {
return content.getStyleSpans(from, to);
}
@Override
public S getStyleOfChar(int paragraph, int index) {
return content.getStyleOfChar(paragraph, index);
}
@Override
public S getStyleAtPosition(int paragraph, int position) {
return content.getStyleAtPosition(paragraph, position);
}
@Override
public IndexRange getStyleRangeAtPosition(int paragraph, int position) {
return content.getStyleRangeAtPosition(paragraph, position);
}
@Override
public StyleSpans<S> getStyleSpans(int paragraph) {
return content.getStyleSpans(paragraph);
}
@Override
public StyleSpans<S> getStyleSpans(int paragraph, int from, int to) {
return content.getStyleSpans(paragraph, from, to);
}
@Override
public int getAbsolutePosition(int paragraphIndex, int columnIndex) {
return content.getAbsolutePosition(paragraphIndex, columnIndex);
}
@Override
public Position position(int row, int col) {
return content.position(row, col);
}
@Override
public Position offsetToPosition(int charOffset, Bias bias) {
return content.offsetToPosition(charOffset, bias);
}
@Override
public Bounds getVisibleParagraphBoundsOnScreen(int visibleParagraphIndex) {
return getParagraphBoundsOnScreen(virtualFlow.visibleCells().get(visibleParagraphIndex));
}
@Override
public Optional<Bounds> getParagraphBoundsOnScreen(int paragraphIndex) {
return virtualFlow.getCellIfVisible(paragraphIndex).map(this::getParagraphBoundsOnScreen);
}
@Override
public final <T extends Node & Caret> Optional<Bounds> getCaretBoundsOnScreen(T caret) {
return virtualFlow.getCellIfVisible(caret.getParagraphIndex())
.map(c -> c.getNode().getCaretBoundsOnScreen(caret));
}
/* ********************************************************************** *
* *
* Actions *
* *
* Actions change the state of this control. They typically cause a *
* change of one or more observables and/or produce an event. *
* *
* ********************************************************************** */
@Override
public void scrollXToPixel(double pixel) {
suspendVisibleParsWhile(() -> virtualFlow.scrollXToPixel(pixel));
}
@Override
public void scrollYToPixel(double pixel) {
suspendVisibleParsWhile(() -> virtualFlow.scrollYToPixel(pixel));
}
@Override
public void scrollXBy(double deltaX) {
suspendVisibleParsWhile(() -> virtualFlow.scrollXBy(deltaX));
}
@Override
public void scrollYBy(double deltaY) {
suspendVisibleParsWhile(() -> virtualFlow.scrollYBy(deltaY));
}
@Override
public void scrollBy(Point2D deltas) {
suspendVisibleParsWhile(() -> virtualFlow.scrollBy(deltas));
}
@Override
public void showParagraphInViewport(int paragraphIndex) {
suspendVisibleParsWhile(() -> virtualFlow.show(paragraphIndex));
}
@Override
public void showParagraphAtTop(int paragraphIndex) {
suspendVisibleParsWhile(() -> virtualFlow.showAsFirst(paragraphIndex));
}
@Override
public void showParagraphAtBottom(int paragraphIndex) {
suspendVisibleParsWhile(() -> virtualFlow.showAsLast(paragraphIndex));
}
@Override
public void showParagraphRegion(int paragraphIndex, Bounds region) {
suspendVisibleParsWhile(() -> virtualFlow.show(paragraphIndex, region));
}
@Override
public void requestFollowCaret() {
followCaretRequested = true;
requestLayout();
}
@Override
public void lineStart(SelectionPolicy policy) {
moveTo(getCurrentParagraph(), getCurrentLineStartInParargraph(), policy);
}
@Override
public void lineEnd(SelectionPolicy policy) {
moveTo(getCurrentParagraph(), getCurrentLineEndInParargraph(), policy);
}
public int getCurrentLineStartInParargraph() {
return virtualFlow.getCell(getCurrentParagraph()).getNode().getCurrentLineStartPosition(caretSelectionBind.getUnderlyingCaret());
}
public int getCurrentLineEndInParargraph() {
return virtualFlow.getCell(getCurrentParagraph()).getNode().getCurrentLineEndPosition(caretSelectionBind.getUnderlyingCaret());
}
private double caretPrevY = -1;
private LineSelection<PS, SEG, S> lineHighlighter;
private ObjectProperty<Paint> lineHighlighterFill;
/**
* The default fill is "highlighter" yellow. It can also be styled using CSS with:<br>
* <code>.styled-text-area .line-highlighter { -fx-fill: lime; }</code><br>
* CSS selectors from Path, Shape, and Node can also be used.
*/
public void setLineHighlighterFill( Paint highlight )
{
if ( lineHighlighterFill != null && highlight != null ) {
lineHighlighterFill.set( highlight );
}
else {
boolean lineHighlightOn = isLineHighlighterOn();
if ( lineHighlightOn ) setLineHighlighterOn( false );
if ( highlight == null ) lineHighlighterFill = null;
else lineHighlighterFill = new SimpleObjectProperty( highlight );
if ( lineHighlightOn ) setLineHighlighterOn( true );
}
}
public boolean isLineHighlighterOn() {
return lineHighlighter != null && selectionSet.contains( lineHighlighter ) ;
}
/**
* Highlights the line that the main caret is on.<br>
* Line highlighting automatically follows the caret.
*/
public void setLineHighlighterOn( boolean show )
{
if ( show )
{
if ( lineHighlighter != null ) return;
lineHighlighter = new LineSelection<>( this, lineHighlighterFill );
Consumer<Bounds> caretListener = b ->
{
if ( lineHighlighter != null && (b.getMinY() != caretPrevY || getCaretColumn() == 1) ) {
lineHighlighter.selectCurrentLine();
caretPrevY = b.getMinY();
}
};
caretBoundsProperty().addListener( (ob,ov,nv) -> nv.ifPresent( caretListener ) );
getCaretBounds().ifPresent( caretListener );
selectionSet.add( lineHighlighter );
}
else if ( lineHighlighter != null ) {
selectionSet.remove( lineHighlighter );
lineHighlighter.deselect();
lineHighlighter = null;
caretPrevY = -1;
}
}
@Override
public void prevPage(SelectionPolicy selectionPolicy) {
// Paging up and we're in the first frame then move/select to start.
if ( firstVisibleParToAllParIndex() == 0 ) {
caretSelectionBind.moveTo( 0, selectionPolicy );
}
else page( -1, selectionPolicy );
}
@Override
public void nextPage(SelectionPolicy selectionPolicy) {
// Paging down and we're in the last frame then move/select to end.
if ( lastVisibleParToAllParIndex() == getParagraphs().size()-1 ) {
caretSelectionBind.moveTo( getLength(), selectionPolicy );
}
else page( +1, selectionPolicy );
}
/**
* @param pgCount the number of pages to page up/down.
* <br>Negative numbers for paging up and positive for down.
*/
private void page(int pgCount, SelectionPolicy selectionPolicy)
{
// Use underlying caret to get the same behaviour as navigating up/down a line where the x position is sticky
Optional<Bounds> cb = caretSelectionBind.getUnderlyingCaret().getCaretBounds();
paging = true; // Prevent scroll from reverting back to the current caret position
scrollYBy( pgCount * getViewportHeight() );
cb.map( this::screenToLocal ) // Place caret near the same on screen position as before
.map( b -> hit( b.getMinX(), b.getMinY()+b.getHeight()/2.0 ).getInsertionIndex() )
.ifPresent( i -> caretSelectionBind.moveTo( i, selectionPolicy ) );
// Adjust scroll by a few pixels to get the caret at the exact on screen location as before
cb.ifPresent( prev -> getCaretBounds().map( newB -> newB.getMinY() - prev.getMinY() )
.filter( delta -> delta != 0.0 ).ifPresent( delta -> scrollYBy( delta ) ) );
}
@Override
public void displaceCaret(int pos) {
caretSelectionBind.displaceCaret(pos);
}
@Override
public void setStyle(int from, int to, S style) {
content.setStyle(from, to, style);
}
@Override
public void setStyle(int paragraph, S style) {
content.setStyle(paragraph, style);
}
@Override
public void setStyle(int paragraph, int from, int to, S style) {
content.setStyle(paragraph, from, to, style);
}
@Override
public void setStyleSpans(int from, StyleSpans<? extends S> styleSpans) {
content.setStyleSpans(from, styleSpans);
}
@Override
public void setStyleSpans(int paragraph, int from, StyleSpans<? extends S> styleSpans) {
content.setStyleSpans(paragraph, from, styleSpans);
}
@Override
public void setParagraphStyle(int paragraph, PS paragraphStyle) {
content.setParagraphStyle(paragraph, paragraphStyle);
}
/**
* If you want to preset the style to be used for inserted text. Note that useInitialStyleForInsertion overrides this if true.
*/
public final void setTextInsertionStyle( S txtStyle ) { insertionTextStyle = txtStyle; }
public final S getTextInsertionStyle() { return insertionTextStyle; }
private S insertionTextStyle;
@Override
public final S getTextStyleForInsertionAt(int pos) {
if ( insertionTextStyle != null ) {
return insertionTextStyle;
} else if ( useInitialStyleForInsertion.get() ) {
return initialTextStyle;
} else {
return content.getStyleAtPosition(pos);
}
}
private PS insertionParagraphStyle;
/**
* If you want to preset the style to be used. Note that useInitialStyleForInsertion overrides this if true.
*/
public final void setParagraphInsertionStyle( PS paraStyle ) { insertionParagraphStyle = paraStyle; }
public final PS getParagraphInsertionStyle() { return insertionParagraphStyle; }
@Override
public final PS getParagraphStyleForInsertionAt(int pos) {
if ( insertionParagraphStyle != null ) {
return insertionParagraphStyle;
} else if ( useInitialStyleForInsertion.get() ) {
return initialParagraphStyle;
} else {
return content.getParagraphStyleAtPosition(pos);
}
}
@Override
public void replaceText(int start, int end, String text) {
StyledDocument<PS, SEG, S> doc = ReadOnlyStyledDocument.fromString(
text, getParagraphStyleForInsertionAt(start), getTextStyleForInsertionAt(start), segmentOps
);
replace(start, end, doc);
}
@Override
public void replace(int start, int end, SEG seg, S style) {
StyledDocument<PS, SEG, S> doc = ReadOnlyStyledDocument.fromSegment(
seg, getParagraphStyleForInsertionAt(start), style, segmentOps
);
replace(start, end, doc);
}
@Override
public void replace(int start, int end, StyledDocument<PS, SEG, S> replacement) {
content.replace(start, end, replacement);
int newCaretPos = start + replacement.length();
selectRange(newCaretPos, newCaretPos);
}
void replaceMulti(List<Replacement<PS, SEG, S>> replacements) {
content.replaceMulti(replacements);
// don't update selection as this is not the main method through which the area is updated
// leave that up to the developer using it to determine what to do
}
@Override
public MultiChangeBuilder<PS, SEG, S> createMultiChange() {
return new MultiChangeBuilder<>(this);
}
@Override
public MultiChangeBuilder<PS, SEG, S> createMultiChange(int initialNumOfChanges) {
return new MultiChangeBuilder<>(this, initialNumOfChanges);
}
/**
* Convenience method to fold (hide/collapse) the currently selected paragraphs,
* into (i.e. excluding) the first paragraph of the range.
*
* @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that will activate folding.
*
* <p>See {@link #fold(int, int, UnaryOperator)} for more info.</p>
*/
protected void foldSelectedParagraphs( UnaryOperator<PS> styleMixin )
{
IndexRange range = getSelection();
fold( range.getStart(), range.getEnd(), styleMixin );
}
/**
* Folds (hides/collapses) paragraphs from <code>start</code> to <code>
* end</code>, into (i.e. excluding) the first paragraph of the range.
*
* @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that will activate folding.
*
* <p>See {@link #fold(int, int, UnaryOperator)} for more info.</p>
*/
protected void foldParagraphs( int start, int end, UnaryOperator<PS> styleMixin )
{
start = getAbsolutePosition( start, 0 );
end = getAbsolutePosition( end, getParagraphLength( end ) );
fold( start, end, styleMixin );
}
/**
* Folds (hides/collapses) paragraphs from character position <code>startPos</code>
* to <code>endPos</code>, into (i.e. excluding) the first paragraph of the range.
*
* <p>Folding is achieved with the help of paragraph styling, which is applied to the paragraph's
* TextFlow object through the applyParagraphStyle BiConsumer (supplied in the constructor to
* GenericStyledArea). When applyParagraphStyle is to apply fold styling it just needs to set
* the TextFlow's visibility to collapsed for it to be folded. See {@code InlineCssTextArea},
* {@code StyleClassedTextArea}, and {@code RichTextDemo} for different ways of doing this.
* Also read the GitHub Wiki.</p>
*
* <p>The UnaryOperator <code>styleMixin</code> must return a
* different paragraph style Object to what was submitted.</p>
*
* @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that will activate folding.
*/
protected void fold( int startPos, int endPos, UnaryOperator<PS> styleMixin )
{
ReadOnlyStyledDocument<PS, SEG, S> subDoc;
UnaryOperator<Paragraph<PS, SEG, S>> mapper;
subDoc = (ReadOnlyStyledDocument<PS, SEG, S>) subDocument( startPos, endPos );
mapper = p -> p.setParagraphStyle( styleMixin.apply( p.getParagraphStyle() ) );
for ( int p = 1; p < subDoc.getParagraphCount(); p++ ) {
subDoc = subDoc.replaceParagraph( p, mapper ).get1();
}
replace( startPos, endPos, subDoc );
recreateParagraphGraphic( offsetToPosition( startPos, Bias.Backward ).getMajor() );
moveTo( startPos );
foldCheck = true;
}
protected boolean foldCheck = false;
private void skipOverFoldedParagraphs( ObservableValue<? extends Integer> ob, Integer prevParagraph, Integer newParagraph )
{
if ( foldCheck && getCell( newParagraph ).isFolded() )
{
// Prevent Ctrl+A and Ctrl+End breaking when the last paragraph is folded
// github.com/FXMisc/RichTextFX/pull/965#issuecomment-706268116
if ( newParagraph == getParagraphs().size() - 1 ) return;
int skip = (newParagraph - prevParagraph > 0) ? +1 : -1;
int p = newParagraph + skip;
while ( p > 0 && p < getParagraphs().size() ) {
if ( getCell( p ).isFolded() ) p += skip;
else break;
}
if ( p < 0 || p == getParagraphs().size() ) p = prevParagraph;
int col = Math.min( getCaretColumn(), getParagraphLength( p ) );
if ( getSelection().getLength() == 0 ) moveTo( p, col );
else moveTo( p, col, SelectionPolicy.EXTEND );
}
}
/**
* Unfolds paragraphs <code>startingFrom</code> onwards for the currently folded block.
*
* <p>The UnaryOperator <code>styleMixin</code> must return a
* different paragraph style Object to what was submitted.</p>
*
* @param isFolded Given a paragraph style PS check if it's folded.
* @param styleMixin Given a paragraph style PS, return a <b>new</b> PS that excludes fold styling.
*/
protected void unfoldParagraphs( int startingFrom, Predicate<PS> isFolded, UnaryOperator<PS> styleMixin )
{
LiveList<Paragraph<PS, SEG, S>> pList = getParagraphs();
int to = startingFrom;
while ( ++to < pList.size() )
{
if ( ! isFolded.test( pList.get( to ).getParagraphStyle() ) ) break;
}
if ( --to > startingFrom )
{
ReadOnlyStyledDocument<PS, SEG, S> subDoc;
UnaryOperator<Paragraph<PS, SEG, S>> mapper;
int startPos = getAbsolutePosition( startingFrom, 0 );
int endPos = getAbsolutePosition( to, getParagraphLength( to ) );
subDoc = (ReadOnlyStyledDocument<PS, SEG, S>) subDocument( startPos, endPos );
mapper = p -> p.setParagraphStyle( styleMixin.apply( p.getParagraphStyle() ) );
for ( int p = 1; p < subDoc.getParagraphCount(); p++ ) {
subDoc = subDoc.replaceParagraph( p, mapper ).get1();
}
replace( startPos, endPos, subDoc );
moveTo( startingFrom, getParagraphLength( startingFrom ) );
recreateParagraphGraphic( startingFrom );
}
}
/* ********************************************************************** *
* *
* Public API *
* *
* ********************************************************************** */
@Override
public void dispose() {
if (undoManager != null) {
undoManager.close();
}
subscriptions.unsubscribe();
virtualFlow.dispose();
}
/* ********************************************************************** *
* *
* Layout *
* *
* ********************************************************************** */
private BooleanProperty autoHeightProp = new SimpleBooleanProperty();
public BooleanProperty autoHeightProperty() {
return autoHeightProp;
}
public void setAutoHeight( boolean value ) {
autoHeightProp.set( value );
}
public boolean isAutoHeight() {
return autoHeightProp.get();
}
@Override
protected double computePrefHeight( double width )
{
if ( autoHeightProp.get() )
{
if ( getWidth() == 0.0 ) Platform.runLater( () -> requestLayout() );
else
{
double height = 0.0;
Insets in = getInsets();
for ( int p = 0; p < getParagraphs().size(); p++ ) {
height += getCell( p ).getHeight();
}
if ( height > 0.0 ) {
return height + in.getTop() + in.getBottom();
}
}
}
return super.computePrefHeight( width );
}
@Override
protected void layoutChildren() {
Insets ins = getInsets();
visibleParagraphs.suspendWhile(() -> {
virtualFlow.resizeRelocate(
ins.getLeft(), ins.getTop(),
getWidth() - ins.getLeft() - ins.getRight(),
getHeight() - ins.getTop() - ins.getBottom());
if(followCaretRequested && ! paging) {
try (Guard g = viewportDirty.suspend()) {
followCaret();
}
}
followCaretRequested = false;
paging = false;
});
Node holder = placeholder;
if (holder != null && holder.isManaged()) {
if (holder.isResizable()) holder.autosize();
if (positionPlaceholder) Region.positionInArea
(
holder, getLayoutX(), getLayoutY(), getWidth(), getHeight(), getBaselineOffset(),
ins, placeHolderPos.getHpos(), placeHolderPos.getVpos(), isSnapToPixel()
);
}
}
/* ********************************************************************** *
* *
* Package-Private methods *
* *
* ********************************************************************** */
/**
* Returns the current line as a two-level index.
* The major number is the paragraph index, the minor
* number is the line number within the paragraph.
*
* <p>This method has a side-effect of bringing the current
* paragraph to the viewport if it is not already visible.
*/
TwoDimensional.Position currentLine() {
int parIdx = getCurrentParagraph();
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx);
int lineIdx = cell.getNode().getCurrentLineIndex(caretSelectionBind.getUnderlyingCaret());
return paragraphLineNavigator.position(parIdx, lineIdx);
}
void showCaretAtBottom() {
int parIdx = getCurrentParagraph();
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx);
Bounds caretBounds = cell.getNode().getCaretBounds(caretSelectionBind.getUnderlyingCaret());
double y = caretBounds.getMaxY();
suspendVisibleParsWhile(() -> virtualFlow.showAtOffset(parIdx, getViewportHeight() - y));
}
void showCaretAtTop() {
int parIdx = getCurrentParagraph();
Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell = virtualFlow.getCell(parIdx);
Bounds caretBounds = cell.getNode().getCaretBounds(caretSelectionBind.getUnderlyingCaret());
double y = caretBounds.getMinY();
suspendVisibleParsWhile(() -> virtualFlow.showAtOffset(parIdx, -y));
}
/**
* Returns x coordinate of the caret in the current paragraph.
*/
final ParagraphBox.CaretOffsetX getCaretOffsetX(CaretNode caret) {
return getCell(caret.getParagraphIndex()).getCaretOffsetX(caret);
}
CharacterHit hit(ParagraphBox.CaretOffsetX x, TwoDimensional.Position targetLine) {
int parIdx = targetLine.getMajor();
ParagraphBox<PS, SEG, S> cell = virtualFlow.getCell(parIdx).getNode();
CharacterHit parHit = cell.hitTextLine(x, targetLine.getMinor());
return parHit.offset(getParagraphOffset(parIdx));
}
CharacterHit hit(ParagraphBox.CaretOffsetX x, double y) {
// don't account for padding here since height of virtualFlow is used, not area + potential padding
VirtualFlowHit<Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>> hit = virtualFlow.hit(0.0, y);
if(hit.isBeforeCells()) {
return CharacterHit.insertionAt(0);
} else if(hit.isAfterCells()) {
return CharacterHit.insertionAt(getLength());
} else {
int parIdx = hit.getCellIndex();
int parOffset = getParagraphOffset(parIdx);
ParagraphBox<PS, SEG, S> cell = hit.getCell().getNode();
Point2D cellOffset = hit.getCellOffset();
CharacterHit parHit = cell.hitText(x, cellOffset.getY());
return parHit.offset(parOffset);
}
}
final Optional<Bounds> getSelectionBoundsOnScreen(Selection<PS, SEG, S> selection) {
if (selection.getLength() == 0) {
return Optional.empty();
}
List<Bounds> bounds = new ArrayList<>(selection.getParagraphSpan());
for (int i = selection.getStartParagraphIndex(); i <= selection.getEndParagraphIndex(); i++) {
virtualFlow.getCellIfVisible(i)
.ifPresent(c -> c.getNode()
.getSelectionBoundsOnScreen(selection)
.ifPresent(bounds::add)
);
}
if(bounds.size() == 0) {
return Optional.empty();
}
double minX = bounds.stream().mapToDouble(Bounds::getMinX).min().getAsDouble();
double maxX = bounds.stream().mapToDouble(Bounds::getMaxX).max().getAsDouble();
double minY = bounds.stream().mapToDouble(Bounds::getMinY).min().getAsDouble();
double maxY = bounds.stream().mapToDouble(Bounds::getMaxY).max().getAsDouble();
return Optional.of(new BoundingBox(minX, minY, maxX-minX, maxY-minY));
}
void clearTargetCaretOffset() {
caretSelectionBind.clearTargetOffset();
}
ParagraphBox.CaretOffsetX getTargetCaretOffset() {
return caretSelectionBind.getTargetOffset();
}
/* ********************************************************************** *
* *
* Private methods *
* *
* ********************************************************************** */
private Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> createCell(
Paragraph<PS, SEG, S> paragraph,
BiConsumer<TextFlow, PS> applyParagraphStyle,
Function<StyledSegment<SEG, S>, Node> nodeFactory) {
ParagraphBox<PS, SEG, S> box = new ParagraphBox<>(paragraph, applyParagraphStyle, nodeFactory);
box.highlightTextFillProperty().bind(highlightTextFill);
box.wrapTextProperty().bind(wrapTextProperty());
box.graphicFactoryProperty().bind(paragraphGraphicFactoryProperty());
box.graphicOffset.bind(virtualFlow.breadthOffsetProperty());
EventStream<Integer> boxIndexValues = box.indexProperty().values().filter(i -> i != -1);
Subscription firstParPseudoClass = boxIndexValues.subscribe(idx -> box.pseudoClassStateChanged(FIRST_PAR, idx == 0));
Subscription lastParPseudoClass = EventStreams.combine(
boxIndexValues,
getParagraphs().sizeProperty().values()
).subscribe(in -> in.exec((i, n) -> box.pseudoClassStateChanged(LAST_PAR, i == n-1)));
// set up caret
Function<CaretNode, Subscription> subscribeToCaret = caret -> {
EventStream<Integer> caretIndexStream = EventStreams.nonNullValuesOf(caret.paragraphIndexProperty());
// a new event stream needs to be created for each caret added, so that it will immediately
// fire the box's current index value as an event, thereby running the code in the subscribe block
// Reusing boxIndexValues will not fire its most recent event, leading to a caret not being added
// Thus, we'll call the new event stream "fresh" box index values
EventStream<Integer> freshBoxIndexValues = box.indexProperty().values().filter(i -> i != -1);
return EventStreams.combine(caretIndexStream, freshBoxIndexValues)
.subscribe(t -> {
int caretParagraphIndex = t.get1();
int boxIndex = t.get2();
if (caretParagraphIndex == boxIndex) {
box.caretsProperty().add(caret);
} else {
box.caretsProperty().remove(caret);
}
});
};
Subscription caretSubscription = caretSet.addSubscriber(subscribeToCaret);
// TODO: how should 'hasCaret' be handled now?
Subscription hasCaretPseudoClass = EventStreams
.combine(boxIndexValues, Val.wrap(currentParagraphProperty()).values())
// box index (t1) == caret paragraph index (t2)
.map(t -> t.get1().equals(t.get2()))
.subscribe(value -> box.pseudoClassStateChanged(HAS_CARET, value));
Function<Selection<PS, SEG, S>, Subscription> subscribeToSelection = selection -> {
EventStream<Integer> startParagraphValues = EventStreams.nonNullValuesOf(selection.startParagraphIndexProperty());
EventStream<Integer> endParagraphValues = EventStreams.nonNullValuesOf(selection.endParagraphIndexProperty());
// see comment in caret section about why a new box index EventStream is needed
EventStream<Integer> freshBoxIndexValues = box.indexProperty().values().filter(i -> i != -1);
return EventStreams.combine(startParagraphValues, endParagraphValues, freshBoxIndexValues)
.subscribe(t -> {
int startPar = t.get1();
int endPar = t.get2();
int boxIndex = t.get3();
if (startPar <= boxIndex && boxIndex <= endPar) {
// So that we don't add multiple paths for the same selection,
// which leads to not removing the additional paths when selection is removed,
// this is a `Map#putIfAbsent(Key, Value)` implementation that creates the path lazily
SelectionPath p = box.selectionsProperty().get(selection);
if (p == null) {
// create & configure path
Val<IndexRange> range = Val.create(
() -> box.getIndex() != -1
? getParagraphSelection(selection, box.getIndex())
: EMPTY_RANGE,
selection.rangeProperty()
);
SelectionPath path = new SelectionPath(range);
path.getStyleClass().add( selection.getSelectionName() );
selection.configureSelectionPath(path);
box.selectionsProperty().put(selection, path);
}
} else {
box.selectionsProperty().remove(selection);
}
});
};
Subscription selectionSubscription = selectionSet.addSubscriber(subscribeToSelection);
return new Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>>() {
@Override
public ParagraphBox<PS, SEG, S> getNode() {
return box;
}
@Override
public void updateIndex(int index) {
box.setIndex(index);
}
@Override
public void dispose() {
box.highlightTextFillProperty().unbind();
box.wrapTextProperty().unbind();
box.graphicFactoryProperty().unbind();
box.graphicOffset.unbind();
box.dispose();
firstParPseudoClass.unsubscribe();
lastParPseudoClass.unsubscribe();
caretSubscription.unsubscribe();
hasCaretPseudoClass.unsubscribe();
selectionSubscription.unsubscribe();
}
};
}
/** Assumes this method is called within a {@link #suspendVisibleParsWhile(Runnable)} block */
private void followCaret() {
int parIdx = getCurrentParagraph();
ParagraphBox<PS, SEG, S> paragrafBox = virtualFlow.getCell( parIdx ).getNode();
Bounds caretBounds;
try {
// This is the default mechanism, but is also needed for https://github.com/FXMisc/RichTextFX/issues/1017
caretBounds = paragrafBox.getCaretBounds( caretSelectionBind.getUnderlyingCaret() );
}
catch ( IllegalArgumentException EX ) {
// This is an alternative mechanism, to address https://github.com/FXMisc/RichTextFX/issues/939
caretBounds = caretSelectionBind.getUnderlyingCaret().getLayoutBounds();
}
double graphicWidth = paragrafBox.getGraphicPrefWidth();
Bounds region = extendLeft(caretBounds, graphicWidth);
double scrollX = virtualFlow.getEstimatedScrollX();
// Ordinarily when a caret ends a selection in the target paragraph and scrolling left is required to follow
// the caret then the selection won't be visible. So here we check for this scenario and adjust if needed.
if ( ! isWrapText() && scrollX > 0.0 && getParagraphSelection( parIdx ).getLength() > 0 )
{
double visibleLeftX = paragrafBox.getWidth() * scrollX / 100 - getWidth() + graphicWidth;
CaretNode selectionStart = new CaretNode( "", this, getSelection().getStart() );
paragrafBox.caretsProperty().add( selectionStart );
Bounds startBounds = paragrafBox.getCaretBounds( selectionStart );
paragrafBox.caretsProperty().remove( selectionStart );
if ( startBounds.getMinX() - graphicWidth < visibleLeftX ) {
region = extendLeft( startBounds, graphicWidth );
}
}
// Addresses https://github.com/FXMisc/RichTextFX/issues/937#issuecomment-674319602
if ( parIdx == getParagraphs().size()-1 && paragrafBox.getLineCount() == 1 )
{
region = new BoundingBox // Correcting the region's height
(
region.getMinX(), region.getMinY(), region.getWidth(),
paragrafBox.getLayoutBounds().getHeight()
);
}
virtualFlow.show(parIdx, region);
}
private ParagraphBox<PS, SEG, S> getCell(int index) {
return virtualFlow.getCell(index).getNode();
}
private EventStream<MouseOverTextEvent> mouseOverTextEvents(ObservableSet<ParagraphBox<PS, SEG, S>> cells, Duration delay) {
return merge(cells, c -> c.stationaryIndices(delay).map(e -> e.unify(
l -> l.map((pos, charIdx) -> MouseOverTextEvent.beginAt(c.localToScreen(pos), getParagraphOffset(c.getIndex()) + charIdx)),
r -> MouseOverTextEvent.end())));
}
private int getParagraphOffset(int parIdx) {
return position(parIdx, 0).toOffset();
}
private Bounds getParagraphBoundsOnScreen(Cell<Paragraph<PS, SEG, S>, ParagraphBox<PS, SEG, S>> cell) {
Bounds nodeLocal = cell.getNode().getBoundsInLocal();
Bounds nodeScreen = cell.getNode().localToScreen(nodeLocal);
Bounds areaLocal = getBoundsInLocal();
Bounds areaScreen = localToScreen(areaLocal);
// use area's minX if scrolled right and paragraph's left is not visible
double minX = nodeScreen.getMinX() < areaScreen.getMinX()
? areaScreen.getMinX()
: nodeScreen.getMinX();
// use area's minY if scrolled down vertically and paragraph's top is not visible
double minY = nodeScreen.getMinY() < areaScreen.getMinY()
? areaScreen.getMinY()
: nodeScreen.getMinY();
// use area's width whether paragraph spans outside of it or not
// so that short or long paragraph takes up the entire space
double width = areaScreen.getWidth();
// use area's maxY if scrolled up vertically and paragraph's bottom is not visible
double maxY = nodeScreen.getMaxY() < areaScreen.getMaxY()
? nodeScreen.getMaxY()
: areaScreen.getMaxY();
return new BoundingBox(minX, minY, width, maxY - minY);
}
private Optional<Bounds> getRangeBoundsOnScreen(int paragraphIndex, int from, int to) {
return virtualFlow.getCellIfVisible(paragraphIndex)
.map(c -> c.getNode().getRangeBoundsOnScreen(from, to));
}
private void manageSubscription(Subscription subscription) {
subscriptions = subscriptions.and(subscription);
}
private static Bounds extendLeft(Bounds b, double w) {
if(w == 0) {
return b;
} else {
return new BoundingBox(
b.getMinX() - w, b.getMinY(),
b.getWidth() + w, b.getHeight());
}
}
private void suspendVisibleParsWhile(Runnable runnable) {
Suspendable.combine(beingUpdated, visibleParagraphs).suspendWhile(runnable);
}
/* ********************************************************************** *
* *
* CSS *
* *
* ********************************************************************** */
private static final CssMetaData<GenericStyledArea<?, ?, ?>, Paint> HIGHLIGHT_TEXT_FILL = new CustomCssMetaData<>(
"-fx-highlight-text-fill", StyleConverter.getPaintConverter(), Color.WHITE, s -> s.highlightTextFill
);
private static final List<CssMetaData<? extends Styleable, ?>> CSS_META_DATA_LIST;
static {
List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<>(Region.getClassCssMetaData());
styleables.add(HIGHLIGHT_TEXT_FILL);
CSS_META_DATA_LIST = Collections.unmodifiableList(styleables);
}
@Override
public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() {
return CSS_META_DATA_LIST;
}
public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() {
return CSS_META_DATA_LIST;
}
}
|
Fix getCaretBounds exception (#1049)
|
richtextfx/src/main/java/org/fxmisc/richtext/GenericStyledArea.java
|
Fix getCaretBounds exception (#1049)
|
|
Java
|
bsd-2-clause
|
7b30b537b659485fedadcc284de7aea72146774b
| 0
|
gab1one/imagej-ops,stelfrich/imagej-ops,kephale/imagej-ops,imagej/imagej-ops
|
/*
* #%L
* ImageJ OPS: a framework for reusable algorithms.
* %%
* Copyright (C) 2014 Board of Regents of the University of
* Wisconsin-Madison and University of Konstanz.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 HOLDERS 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.
* #L%
*/
package imagej.ops.map.parallel;
import imagej.ops.Contingent;
import imagej.ops.Op;
import imagej.ops.OpService;
import imagej.ops.Parallel;
import imagej.ops.map.AbstractFunctionMap;
import imagej.ops.map.Map;
import imagej.ops.threading.ChunkExecutor;
import imagej.ops.threading.CursorBasedChunkExecutable;
import net.imglib2.Cursor;
import net.imglib2.IterableInterval;
import org.scijava.Priority;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
/**
* Parallelized {@link FunctionalMap}, which is specialized for the case, that
* the two incoming {@link IterableInterval}s have the same IterationOrder.
*
* @author Christian Dietz
* @param <A> mapped on <B>
* @param <B> mapped from <A>
*/
@Plugin(type = Op.class, name = Map.NAME, priority = Priority.LOW_PRIORITY + 3)
public class FunctionMapIIP<A, B> extends
AbstractFunctionMap<A, B, IterableInterval<A>, IterableInterval<B>> implements
Contingent, Parallel
{
@Parameter
private OpService opService;
@Override
public boolean conforms() {
return getOutput() == null || isValid(getInput(), getOutput());
}
private boolean isValid(final IterableInterval<A> input,
final IterableInterval<B> output)
{
return getInput().iterationOrder().equals(getOutput().iterationOrder());
}
@Override
public IterableInterval<B> compute(final IterableInterval<A> input,
final IterableInterval<B> output)
{
if (!isValid(input, output)) {
throw new IllegalArgumentException(
"Input and Output do not have the same iteration order!");
}
opService.run(ChunkExecutor.class, new CursorBasedChunkExecutable() {
@Override
public void execute(final int startIndex, final int stepSize,
final int numSteps)
{
final Cursor<A> inCursor = input.cursor();
final Cursor<B> outCursor = output.cursor();
setToStart(inCursor, startIndex);
setToStart(outCursor, startIndex);
int ctr = 0;
while (ctr < numSteps) {
func.compute(inCursor.get(), outCursor.get());
inCursor.jumpFwd(stepSize);
outCursor.jumpFwd(stepSize);
ctr++;
}
}
}, input.size());
return output;
}
}
|
src/main/java/imagej/ops/map/parallel/FunctionMapIIP.java
|
/*
* #%L
* ImageJ OPS: a framework for reusable algorithms.
* %%
* Copyright (C) 2014 Board of Regents of the University of
* Wisconsin-Madison and University of Konstanz.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 HOLDERS 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.
* #L%
*/
package imagej.ops.map.parallel;
import imagej.ops.Contingent;
import imagej.ops.Op;
import imagej.ops.OpService;
import imagej.ops.Parallel;
import imagej.ops.map.AbstractFunctionMap;
import imagej.ops.map.Map;
import imagej.ops.threading.ChunkExecutor;
import imagej.ops.threading.CursorBasedChunkExecutable;
import net.imglib2.Cursor;
import net.imglib2.IterableInterval;
import org.scijava.Priority;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
/**
* Parallelized {@link FunctionalMap}, which is specialized for the case, that
* the two incoming {@link IterableInterval}s have the same IterationOrder.
*
* @author Christian Dietz
* @param <A> mapped on <B>
* @param <B> mapped from <A>
*/
@Plugin(type = Op.class, name = Map.NAME, priority = Priority.LOW_PRIORITY + 3)
public class FunctionMapIIP<A, B> extends
AbstractFunctionMap<A, B, IterableInterval<A>, IterableInterval<B>> implements
Contingent, Parallel
{
@Parameter
private OpService opService;
@Override
public boolean conforms() {
// Assumption: if output is zero, it will be provided from someone (such that it fits).
return getOutput() == null ||
getInput().iterationOrder().equals(getOutput().iterationOrder());
}
@Override
public IterableInterval<B> compute(final IterableInterval<A> input,
final IterableInterval<B> output)
{
opService.run(ChunkExecutor.class, new CursorBasedChunkExecutable() {
@Override
public void execute(final int startIndex, final int stepSize,
final int numSteps)
{
final Cursor<A> inCursor = input.cursor();
final Cursor<B> outCursor = output.cursor();
setToStart(inCursor, startIndex);
setToStart(outCursor, startIndex);
int ctr = 0;
while (ctr < numSteps) {
func.compute(inCursor.get(), outCursor.get());
inCursor.jumpFwd(stepSize);
outCursor.jumpFwd(stepSize);
ctr++;
}
}
}, input.size());
return output;
}
}
|
FunctionMapII: conforms check factored out to isValid
|
src/main/java/imagej/ops/map/parallel/FunctionMapIIP.java
|
FunctionMapII: conforms check factored out to isValid
|
|
Java
|
bsd-2-clause
|
0aac5b2ea88d3d828c1c6126028dacf1047efb3c
| 0
|
AnimeNeko/Atarashii,ratan12/Atarashii,AnimeNeko/Atarashii,ratan12/Atarashii
|
package net.somethingdreadful.MAL;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import net.somethingdreadful.MAL.api.MALApi;
public class FirstTimeInit extends SherlockActivity {
static EditText malUser;
static EditText malPass;
static String testMalUser;
static String testMalPass;
static ProgressDialog pd;
static Thread netThread;
static Context context;
static private Handler messenger;
static PrefManager prefManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstrun);
malUser = (EditText) findViewById(R.id.edittext_malUser);
malPass = (EditText) findViewById(R.id.edittext_malPass);
Button connectButton = (Button) findViewById(R.id.button_connectToMal);
Button registerButton = (Button) findViewById(R.id.registerButton);
context = getApplicationContext();
prefManager = new PrefManager(context);
connectButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
testMalUser = malUser.getText().toString().trim();
testMalPass = malPass.getText().toString().trim();
tryConnection();
}
});
registerButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://myanimelist.net/register.php"));
startActivity(browserIntent);
}
});
messenger = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 2) {
pd.dismiss();
Toast.makeText(context, context.getString(R.string.toast_VerifyProblem), Toast.LENGTH_SHORT).show();
}
if (msg.what == 3) {
pd.dismiss();
Toast.makeText(context, context.getString(R.string.toast_AccountOK), Toast.LENGTH_SHORT).show();
prefManager.setUser(testMalUser);
prefManager.setPass(testMalPass);
prefManager.setInit(true);
prefManager.commitChanges();
Intent goHome = new Intent(context, Home.class);
startActivity(goHome);
System.exit(0);
}
super.handleMessage(msg);
}
};
}
private void tryConnection() {
pd = ProgressDialog.show(this, context.getString(R.string.dialog_Verifying), context.getString(R.string.dialog_VerifyingBlurb));
netThread = new networkThread();
netThread.start();
}
public class networkThread extends Thread {
@Override
public void run() {
boolean valid = new MALApi(testMalUser, testMalPass).isAuth();
Message msg = new Message();
if (!valid) {
msg.what = 2;
messenger.sendMessage(msg);
} else {
msg.what = 3;
messenger.sendMessage(msg);
}
}
}
}
|
Atarashii/src/net/somethingdreadful/MAL/FirstTimeInit.java
|
package net.somethingdreadful.MAL;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import net.somethingdreadful.MAL.api.MALApi;
public class FirstTimeInit extends SherlockActivity {
static EditText malUser;
static EditText malPass;
static String testMalUser;
static String testMalPass;
static ProgressDialog pd;
static Thread netThread;
static Context context;
static private Handler messenger;
static PrefManager prefManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstrun);
malUser = (EditText) findViewById(R.id.edittext_malUser);
malPass = (EditText) findViewById(R.id.edittext_malPass);
Button connectButton = (Button) findViewById(R.id.button_connectToMal);
Button registerButton = (Button) findViewById(R.id.registerButton);
context = getApplicationContext();
prefManager = new PrefManager(context);
connectButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
testMalUser = malUser.getText().toString().trim();
testMalPass = malPass.getText().toString().trim();
tryConnection();
}
});
registerButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://myanimelist.net/register.php"));
startActivity(browserIntent);
}
});
messenger = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 2) {
pd.dismiss();
Toast.makeText(context, context.getString(R.string.toast_VerifyProblem), Toast.LENGTH_SHORT).show();
}
if (msg.what == 3) {
pd.dismiss();
Toast.makeText(context, context.getString(R.string.toast_AccountOK), Toast.LENGTH_SHORT).show();
prefManager.setUser(testMalUser);
prefManager.setPass(testMalPass);
prefManager.setInit(true);
prefManager.commitChanges();
Intent goHome = new Intent(context, Home.class);
goHome.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra("net.somethingdreadful.MAL.firstSync", true);
startActivity(goHome);
}
super.handleMessage(msg);
}
};
}
private void tryConnection() {
pd = ProgressDialog.show(this, context.getString(R.string.dialog_Verifying), context.getString(R.string.dialog_VerifyingBlurb));
netThread = new networkThread();
netThread.start();
}
public class networkThread extends Thread {
@Override
public void run() {
boolean valid = new MALApi(testMalUser, testMalPass).isAuth();
Message msg = new Message();
if (!valid) {
msg.what = 2;
messenger.sendMessage(msg);
} else {
msg.what = 3;
messenger.sendMessage(msg);
}
}
}
}
|
Replaced flag (FirstTimeInit.java)
|
Atarashii/src/net/somethingdreadful/MAL/FirstTimeInit.java
|
Replaced flag (FirstTimeInit.java)
|
|
Java
|
bsd-3-clause
|
305a80a2360213544241b3eb03448c216f8076a4
| 0
|
masih/jetson
|
/*
* Copyright 2013 Masih Hajiarabderkani
*
* This file is part of Jetson.
*
* Jetson is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Jetson 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 Jetson. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.ac.standrews.cs.jetson;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import junit.framework.Assert;
import org.junit.Test;
import uk.ac.standrews.cs.jetson.TestService.TestObject;
import uk.ac.standrews.cs.jetson.exception.JsonRpcException;
public class NormalOperationTest extends AbstractTest<TestService> {
@Test
public void testDoVoidWithNoParams() throws JsonRpcException {
client.doVoidWithNoParams();
}
@Test
public void testSaySomething() throws JsonRpcException {
final String something = client.saySomething();
Assert.assertEquals("something", something);
}
@Test
public void testSay65535() throws JsonRpcException {
final Integer _65535 = client.say65535();
Assert.assertEquals(new Integer(65535), _65535);
}
@Test
public void testSayMinus65535() throws JsonRpcException {
final Integer minus65535 = client.sayMinus65535();
Assert.assertEquals(new Integer(-65535), minus65535);
}
@Test
public void testSayTrue() throws JsonRpcException {
final Boolean _true = client.sayTrue();
Assert.assertTrue(_true);
}
@Test
public void testSayFalse() throws JsonRpcException {
final Boolean _false = client.sayFalse();
Assert.assertFalse(_false);
}
@Test
public void testThrowException() {
try {
client.throwException();
fail("expected exception");
}
catch (final Exception e) {
Assert.assertEquals(NormalOperationTestService.TEST_EXCEPTION.getClass(), e.getClass());
Assert.assertEquals(NormalOperationTestService.TEST_EXCEPTION.getMessage(), e.getMessage());
}
}
@Test
public void testThrowExceptionOnRemote() {
try {
client.throwExceptionOnRemote(temp_server_port);
fail("expected exception");
}
catch (final Exception e) {
Assert.assertEquals(NormalOperationTestService.TEST_EXCEPTION.getClass(), e.getClass());
Assert.assertEquals(NormalOperationTestService.TEST_EXCEPTION.getMessage(), e.getMessage());
}
}
@Test
public void testAdd() throws JsonRpcException {
testAddOnClient(client);
}
private void testAddOnClient(final TestService client) throws JsonRpcException {
final Integer three = client.add(1, 2);
Assert.assertEquals(new Integer(1 + 2), three);
final Integer eleven = client.add(12, -1);
Assert.assertEquals(new Integer(12 + -1), eleven);
final Integer fifty_one = client.add(-61, 112);
Assert.assertEquals(new Integer(-61 + 112), fifty_one);
final Integer minus_seven = client.add(-4, -3);
Assert.assertEquals(new Integer(-4 + -3), minus_seven);
}
@Test
public void testAddOnRemote() throws JsonRpcException {
testAddOnRemoteClient(client);
}
private void testAddOnRemoteClient(final TestService client) throws JsonRpcException {
final Integer three = client.addOnRemote(1, 2, temp_server_port);
Assert.assertEquals(new Integer(1 + 2), three);
final Integer eleven = client.addOnRemote(12, -1, temp_server_port);
Assert.assertEquals(new Integer(12 + -1), eleven);
final Integer fifty_one = client.addOnRemote(-61, 112, temp_server_port);
Assert.assertEquals(new Integer(-61 + 112), fifty_one);
final Integer minus_seven = client.addOnRemote(-4, -3, temp_server_port);
Assert.assertEquals(new Integer(-4 + -3), minus_seven);
}
@Test
public void testGetObject() throws JsonRpcException {
Assert.assertEquals(NormalOperationTestService.TEST_OBJECT_MESSAGE, client.getObject().getMessage());
}
@Test
public void testSayFalseOnRemote() throws IOException {
final Boolean _false = client.sayFalseOnRemote(temp_server_port);
Assert.assertFalse(_false);
}
@Test
public void testGetObjectOnRemote() throws IOException {
Assert.assertEquals(NormalOperationTestService.TEST_OBJECT_MESSAGE, client.getObjectOnRemote(temp_server_port).getMessage());
}
@Test
public void testConcatinate() throws JsonRpcException {
final String text = "ssss";
final int integer = 8852456;
final TestObject object = new TestObject("X_1_23");
final char character = '=';
final String result = client.concatinate(text, integer, object, character);
Assert.assertEquals(text + integer + object + character, result);
}
@Test
public void testConcurrentClients() throws JsonRpcException, InterruptedException, ExecutionException {
final ExecutorService executor = Executors.newFixedThreadPool(500);
try {
final CountDownLatch start_latch = new CountDownLatch(1);
final List<Future<Void>> future_concurrent_tests = new ArrayList<Future<Void>>();
for (int i = 0; i < 500; i++) {
future_concurrent_tests.add(executor.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
start_latch.await();
testAdd();
testAddOnRemote();
testDoVoidWithNoParams();
testGetObject();
testGetObjectOnRemote();
testSay65535();
testSayFalse();
testSayFalseOnRemote();
testSayMinus65535();
testSaySomething();
testSayTrue();
testThrowException();
testThrowExceptionOnRemote();
return null;
}
}));
}
start_latch.countDown();
for (final Future<Void> f : future_concurrent_tests) {
f.get();
}
}
finally {
executor.shutdown();
}
}
@Test
public void testConcurrentServers() throws JsonRpcException, InterruptedException, ExecutionException {
final ExecutorService executor = Executors.newFixedThreadPool(500);
try {
final CountDownLatch start_latch = new CountDownLatch(1);
final List<Future<Void>> future_concurrent_tests = new ArrayList<Future<Void>>();
for (int i = 0; i < 500; i++) {
future_concurrent_tests.add(executor.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
start_latch.await();
final JsonRpcServer server = startJsonRpcTestServer();
final InetSocketAddress server_address = server.getLocalSocketAddress();
final TestService client = (TestService) proxy_factory.get(server_address);
try {
testAddOnClient(client);
testAddOnRemoteClient(client);
}
finally {
server.shutdown();
}
return null;
}
}));
}
start_latch.countDown();
for (final Future<Void> f : future_concurrent_tests) {
f.get();
}
}
finally {
executor.shutdown();
}
}
@Override
protected Class<TestService> getServiceType() {
return TestService.class;
}
@Override
protected TestService getService() {
return new NormalOperationTestService(proxy_factory);
}
public static void main(final String[] args) throws IOException {
final NormalOperationTest t = new NormalOperationTest();
int i = 0;
while (!Thread.currentThread().isInterrupted()) {
new JsonRpcServer(t.getServiceType(), t.getService(), t.json_factory).expose();
System.out.println(i++);
}
}
}
|
src/test/java/uk/ac/standrews/cs/jetson/NormalOperationTest.java
|
/*
* Copyright 2013 Masih Hajiarabderkani
*
* This file is part of Jetson.
*
* Jetson is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Jetson 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 Jetson. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.ac.standrews.cs.jetson;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import junit.framework.Assert;
import org.junit.Test;
import uk.ac.standrews.cs.jetson.TestService.TestObject;
import uk.ac.standrews.cs.jetson.exception.JsonRpcException;
public class NormalOperationTest extends AbstractTest<TestService> {
@Test
public void testDoVoidWithNoParams() throws JsonRpcException {
client.doVoidWithNoParams();
}
@Test
public void testSaySomething() throws JsonRpcException {
final String something = client.saySomething();
Assert.assertEquals("something", something);
}
@Test
public void testSay65535() throws JsonRpcException {
final Integer _65535 = client.say65535();
Assert.assertEquals(new Integer(65535), _65535);
}
@Test
public void testSayMinus65535() throws JsonRpcException {
final Integer minus65535 = client.sayMinus65535();
Assert.assertEquals(new Integer(-65535), minus65535);
}
@Test
public void testSayTrue() throws JsonRpcException {
final Boolean _true = client.sayTrue();
Assert.assertTrue(_true);
}
@Test
public void testSayFalse() throws JsonRpcException {
final Boolean _false = client.sayFalse();
Assert.assertFalse(_false);
}
@Test
public void testThrowException() {
try {
client.throwException();
fail("expected exception");
}
catch (final Exception e) {
Assert.assertEquals(NormalOperationTestService.TEST_EXCEPTION.getClass(), e.getClass());
Assert.assertEquals(NormalOperationTestService.TEST_EXCEPTION.getMessage(), e.getMessage());
}
}
@Test
public void testThrowExceptionOnRemote() {
try {
client.throwExceptionOnRemote(temp_server_port);
fail("expected exception");
}
catch (final Exception e) {
Assert.assertEquals(NormalOperationTestService.TEST_EXCEPTION.getClass(), e.getClass());
Assert.assertEquals(NormalOperationTestService.TEST_EXCEPTION.getMessage(), e.getMessage());
}
}
@Test
public void testAdd() throws JsonRpcException {
testAddOnClient(client);
}
private void testAddOnClient(final TestService client) throws JsonRpcException {
final Integer three = client.add(1, 2);
Assert.assertEquals(new Integer(1 + 2), three);
final Integer eleven = client.add(12, -1);
Assert.assertEquals(new Integer(12 + -1), eleven);
final Integer fifty_one = client.add(-61, 112);
Assert.assertEquals(new Integer(-61 + 112), fifty_one);
final Integer minus_seven = client.add(-4, -3);
Assert.assertEquals(new Integer(-4 + -3), minus_seven);
}
@Test
public void testAddOnRemote() throws JsonRpcException {
testAddOnRemoteClient(client);
}
private void testAddOnRemoteClient(final TestService client) throws JsonRpcException {
final Integer three = client.addOnRemote(1, 2, temp_server_port);
Assert.assertEquals(new Integer(1 + 2), three);
final Integer eleven = client.addOnRemote(12, -1, temp_server_port);
Assert.assertEquals(new Integer(12 + -1), eleven);
final Integer fifty_one = client.addOnRemote(-61, 112, temp_server_port);
Assert.assertEquals(new Integer(-61 + 112), fifty_one);
final Integer minus_seven = client.addOnRemote(-4, -3, temp_server_port);
Assert.assertEquals(new Integer(-4 + -3), minus_seven);
}
@Test
public void testGetObject() throws JsonRpcException {
Assert.assertEquals(NormalOperationTestService.TEST_OBJECT_MESSAGE, client.getObject().getMessage());
}
@Test
public void testSayFalseOnRemote() throws IOException {
final Boolean _false = client.sayFalseOnRemote(temp_server_port);
Assert.assertFalse(_false);
}
@Test
public void testGetObjectOnRemote() throws IOException {
Assert.assertEquals(NormalOperationTestService.TEST_OBJECT_MESSAGE, client.getObjectOnRemote(temp_server_port).getMessage());
}
@Test
public void testConcatinate() throws JsonRpcException {
final String text = "ssss";
final int integer = 8852456;
final TestObject object = new TestObject("X_1_23");
final char character = '=';
final String result = client.concatinate(text, integer, object, character);
Assert.assertEquals(text + integer + object + character, result);
}
@Test
public void testConcurrentClients() throws JsonRpcException, InterruptedException, ExecutionException {
final ExecutorService executor = Executors.newFixedThreadPool(500);
try {
final CountDownLatch start_latch = new CountDownLatch(1);
final List<Future<Void>> future_concurrent_tests = new ArrayList<Future<Void>>();
for (int i = 0; i < 10000; i++) {
future_concurrent_tests.add(executor.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
start_latch.await();
testAdd();
testAddOnRemote();
testDoVoidWithNoParams();
testGetObject();
testGetObjectOnRemote();
testSay65535();
testSayFalse();
testSayFalseOnRemote();
testSayMinus65535();
testSaySomething();
testSayTrue();
testThrowException();
testThrowExceptionOnRemote();
return null;
}
}));
}
start_latch.countDown();
for (final Future<Void> f : future_concurrent_tests) {
f.get();
}
}
finally {
executor.shutdown();
}
}
@Test
public void testConcurrentServers() throws JsonRpcException, InterruptedException, ExecutionException {
final ExecutorService executor = Executors.newFixedThreadPool(500);
try {
final CountDownLatch start_latch = new CountDownLatch(1);
final List<Future<Void>> future_concurrent_tests = new ArrayList<Future<Void>>();
for (int i = 0; i < 5000; i++) {
future_concurrent_tests.add(executor.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
start_latch.await();
final JsonRpcServer server = startJsonRpcTestServer();
final InetSocketAddress server_address = server.getLocalSocketAddress();
final TestService client = (TestService) proxy_factory.get(server_address);
try {
testAddOnClient(client);
testAddOnRemoteClient(client);
}
finally {
server.shutdown();
}
return null;
}
}));
}
start_latch.countDown();
for (final Future<Void> f : future_concurrent_tests) {
f.get();
}
}
finally {
executor.shutdown();
}
}
@Override
protected Class<TestService> getServiceType() {
return TestService.class;
}
@Override
protected TestService getService() {
return new NormalOperationTestService(proxy_factory);
}
public static void main(final String[] args) throws IOException {
final NormalOperationTest t = new NormalOperationTest();
int i = 0;
while (!Thread.currentThread().isInterrupted()) {
new JsonRpcServer(t.getServiceType(), t.getService(), t.json_factory).expose();
System.out.println(i++);
}
}
}
|
decreased the number of concurrent connections in concurrent test, since jenkins cant cope with it
|
src/test/java/uk/ac/standrews/cs/jetson/NormalOperationTest.java
|
decreased the number of concurrent connections in concurrent test, since jenkins cant cope with it
|
|
Java
|
isc
|
5e05f5af764ff4891b86c5b67c3a556c64c8e47f
| 0
|
dclements/riak-java-crdt,dclements/riak-java-crdt
|
package com.readytalk.crdt.sets;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.readytalk.crdt.util.CollectionUtils.checkCollectionDoesNotContainNull;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Nullable;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import com.readytalk.crdt.AbstractCRDT;
public class ORSet<E> extends AbstractCRDT<ImmutableSet<E>, ORSet<E>> implements
CRDTSet<E, ImmutableSet<E>, ORSet<E>> {
private static final String ELEMENTS_TOKEN = "e";
private static final String TOMBSTONES_TOKEN = "t";
private final Multimap<E, UUID> elements = LinkedHashMultimap.create();
private final Multimap<E, UUID> tombstones = LinkedHashMultimap.create();
public ORSet(final ObjectMapper mapper) {
super(mapper);
}
public ORSet(final ObjectMapper mapper, final byte[] value) {
super(mapper);
TypeReference<Map<String, Map<E, Collection<UUID>>>> ref =
new TypeReference<Map<String, Map<E, Collection<UUID>>>>() {
};
try {
Map<String, Map<E, Collection<UUID>>> s1 = mapper.readValue(value,
ref);
Map<E, Collection<UUID>> e = s1.get(ELEMENTS_TOKEN);
Map<E, Collection<UUID>> t = s1.get(TOMBSTONES_TOKEN);
for (Map.Entry<E, Collection<UUID>> o : e.entrySet()) {
elements.putAll(o.getKey(), o.getValue());
}
for (Map.Entry<E, Collection<UUID>> o : t.entrySet()) {
tombstones.putAll(o.getKey(), o.getValue());
}
} catch (IOException ex) {
throw new IllegalArgumentException("Unable to deserialize.");
}
}
@Override
public boolean add(final E value) {
checkNotNull(value);
UUID uuid = UUID.randomUUID();
boolean retval = !elements.containsKey(value);
elements.put(value, uuid);
return retval;
}
@Override
public boolean addAll(final Collection<? extends E> values) {
checkNotNull(values);
checkCollectionDoesNotContainNull(values);
boolean retval = false;
for (E o : values) {
retval |= this.add(o);
}
return retval;
}
@Override
public void clear() {
this.tombstones.putAll(this.elements);
this.elements.clear();
}
@Override
public boolean contains(final Object value) {
checkNotNull(value);
return this.elements.containsKey(value);
}
@Override
public boolean containsAll(final Collection<?> values) {
checkCollectionDoesNotContainNull(values);
return this.value().containsAll(values);
}
@Override
public boolean isEmpty() {
return elements.isEmpty();
}
@Override
public Iterator<E> iterator() {
return Iterators
.unmodifiableIterator(this.elements.keySet().iterator());
}
@SuppressWarnings("unchecked")
@Override
public boolean remove(final Object value) {
checkNotNull(value);
this.tombstones.putAll((E) value, elements.get((E) value));
return elements.removeAll(value).size() > 0;
}
@Override
public boolean removeAll(final Collection<?> values) {
checkNotNull(values);
checkCollectionDoesNotContainNull(values);
Multimap<E, UUID> subset = Multimaps.filterKeys(elements,
new Predicate<E>() {
@Override
public boolean apply(final E input) {
return values.contains(input);
}
});
if (subset.isEmpty()) {
return false;
}
for (E o : Sets.newLinkedHashSet(subset.keySet())) {
Collection<UUID> result = this.elements.removeAll(o);
this.tombstones.putAll(o, result);
}
return true;
}
@Override
@SuppressWarnings("unchecked")
public boolean retainAll(final Collection<?> values) {
checkNotNull(values);
checkCollectionDoesNotContainNull(values);
Set<E> input = Sets.newHashSet((Collection<E>)values);
Set<E> diff = Sets.difference(this.elements.keySet(), input);
return this.removeAll(diff);
}
@Override
public int size() {
return elements.keySet().size();
}
@Override
public Object[] toArray() {
return elements.keySet().toArray();
}
@Override
public <T> T[] toArray(final T[] arg) {
return elements.keySet().toArray(arg);
}
@Override
public ORSet<E> merge(final ORSet<E> other) {
ORSet<E> retval = new ORSet<E>(serializer());
retval.elements.putAll(this.elements);
retval.elements.putAll(other.elements);
retval.tombstones.putAll(this.tombstones);
retval.tombstones.putAll(other.elements);
retval.elements.removeAll(retval.tombstones);
return retval;
}
@Override
public ImmutableSet<E> value() {
return ImmutableSet.copyOf(elements.keySet());
}
@Override
public byte[] payload() {
Map<String, Object> retval = Maps.newLinkedHashMap();
retval.put(ELEMENTS_TOKEN, elements.asMap());
retval.put(TOMBSTONES_TOKEN, tombstones.asMap());
try {
return serializer().writeValueAsBytes(retval);
} catch (IOException ex) {
throw new IllegalStateException("Unable to serialize object.", ex);
}
}
@Override
public final boolean equals(@Nullable final Object o) {
if (!(o instanceof ORSet)) {
return false;
}
ORSet<?> t = (ORSet<?>) o;
if (this == t) {
return true;
} else {
return this.value().equals(t.value());
}
}
@Override
public final int hashCode() {
return this.value().hashCode();
}
@Override
public String toString() {
return this.value().toString();
}
}
|
src/main/java/com/readytalk/crdt/sets/ORSet.java
|
package com.readytalk.crdt.sets;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.readytalk.crdt.util.CollectionUtils.checkCollectionDoesNotContainNull;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Nullable;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import com.readytalk.crdt.AbstractCRDT;
public class ORSet<E> extends AbstractCRDT<ImmutableSet<E>, ORSet<E>> implements
CRDTSet<E, ImmutableSet<E>, ORSet<E>> {
private static final String ELEMENTS_TOKEN = "e";
private static final String TOMBSTONES_TOKEN = "t";
private final Multimap<E, UUID> elements = LinkedHashMultimap.create();
private final Multimap<E, UUID> tombstones = LinkedHashMultimap.create();
public ORSet(final ObjectMapper mapper) {
super(mapper);
}
public ORSet(final ObjectMapper mapper, final byte[] value) {
super(mapper);
TypeReference<Map<String, Map<E, Collection<UUID>>>> ref =
new TypeReference<Map<String, Map<E, Collection<UUID>>>>() {
};
try {
Map<String, Map<E, Collection<UUID>>> s1 = mapper.readValue(value,
ref);
Map<E, Collection<UUID>> e = s1.get(ELEMENTS_TOKEN);
Map<E, Collection<UUID>> t = s1.get(TOMBSTONES_TOKEN);
for (Map.Entry<E, Collection<UUID>> o : e.entrySet()) {
elements.putAll(o.getKey(), o.getValue());
}
for (Map.Entry<E, Collection<UUID>> o : t.entrySet()) {
tombstones.putAll(o.getKey(), o.getValue());
}
} catch (IOException ex) {
throw new IllegalArgumentException("Unable to deserialize.");
}
}
@Override
public boolean add(final E value) {
checkNotNull(value);
UUID uuid = UUID.randomUUID();
boolean retval = !elements.containsKey(value);
elements.put(value, uuid);
return retval;
}
@Override
public boolean addAll(final Collection<? extends E> values) {
checkNotNull(values);
checkCollectionDoesNotContainNull(values);
boolean retval = false;
for (E o : values) {
retval |= this.add(o);
}
return retval;
}
@Override
public void clear() {
this.tombstones.putAll(this.elements);
this.elements.clear();
}
@Override
public boolean contains(final Object value) {
checkNotNull(value);
return this.elements.containsKey(value);
}
@Override
public boolean containsAll(final Collection<?> values) {
checkCollectionDoesNotContainNull(values);
return this.value().containsAll(values);
}
@Override
public boolean isEmpty() {
return elements.isEmpty();
}
@Override
public Iterator<E> iterator() {
return Iterators
.unmodifiableIterator(this.elements.keySet().iterator());
}
@SuppressWarnings("unchecked")
@Override
public boolean remove(final Object value) {
checkNotNull(value);
this.tombstones.putAll((E) value, elements.get((E) value));
return elements.removeAll(value).size() > 0;
}
@Override
public boolean removeAll(final Collection<?> values) {
checkNotNull(values);
checkCollectionDoesNotContainNull(values);
Multimap<E, UUID> subset = Multimaps.filterKeys(elements,
new Predicate<E>() {
@Override
public boolean apply(final E input) {
return values.contains(input);
}
});
if (subset.isEmpty()) {
return false;
}
for (E o : Sets.newLinkedHashSet(subset.keySet())) {
Collection<UUID> result = this.elements.removeAll(o);
this.tombstones.putAll(o, result);
}
return true;
}
@Override
@SuppressWarnings("unchecked")
public boolean retainAll(final Collection<?> values) {
checkNotNull(values);
checkCollectionDoesNotContainNull(values);
Set<E> input = Sets.newHashSet((Collection<E>)values);
Set<E> diff = Sets.difference(this.elements.keySet(), input);
return this.removeAll(diff);
}
@Override
public int size() {
return elements.size();
}
@Override
public Object[] toArray() {
return elements.keySet().toArray();
}
@Override
public <T> T[] toArray(final T[] arg) {
return elements.keySet().toArray(arg);
}
@Override
public ORSet<E> merge(final ORSet<E> other) {
ORSet<E> retval = new ORSet<E>(serializer());
retval.elements.putAll(this.elements);
retval.elements.putAll(other.elements);
retval.tombstones.putAll(this.tombstones);
retval.tombstones.putAll(other.elements);
retval.elements.removeAll(retval.tombstones);
return retval;
}
@Override
public ImmutableSet<E> value() {
return ImmutableSet.copyOf(elements.keySet());
}
@Override
public byte[] payload() {
Map<String, Object> retval = Maps.newLinkedHashMap();
retval.put(ELEMENTS_TOKEN, elements.asMap());
retval.put(TOMBSTONES_TOKEN, tombstones.asMap());
try {
return serializer().writeValueAsBytes(retval);
} catch (IOException ex) {
throw new IllegalStateException("Unable to serialize object.", ex);
}
}
@Override
public final boolean equals(@Nullable final Object o) {
if (!(o instanceof ORSet)) {
return false;
}
ORSet<?> t = (ORSet<?>) o;
if (this == t) {
return true;
} else {
return this.value().equals(t.value());
}
}
@Override
public final int hashCode() {
return this.value().hashCode();
}
@Override
public String toString() {
return this.value().toString();
}
}
|
Fixed bug with ORSet sizes after repeated adds.
The Multimap that backs the system would return a size of the number of unique instances in the map,
so (key, uuid1) (key, uuid2) are each counted in the multimaps size. This fix looks only at the size
of the keySet.
|
src/main/java/com/readytalk/crdt/sets/ORSet.java
|
Fixed bug with ORSet sizes after repeated adds.
|
|
Java
|
isc
|
5d3dd47f1752c66d09931efe8c0152d36824c325
| 0
|
Major-/apollo,SJ19/apollo,ryleykimmel/apollo,Major-/apollo,apollo-rsps/apollo,apollo-rsps/apollo,ryleykimmel/apollo,LegendSky/apollo,SJ19/apollo,apollo-rsps/apollo,LegendSky/apollo,garyttierney/apollo,garyttierney/apollo
|
package org.apollo.game.model;
/**
* A class which contains an {@link Item} and its corresponding slot.
*
* @author Graham
*/
public final class SlottedItem {
/**
* The item.
*/
private final Item item;
/**
* The slot.
*/
private final int slot;
/**
* Creates a new slotted item.
*
* @param slot The slot.
* @param item The item.
*/
public SlottedItem(int slot, Item item) {
this.slot = slot;
this.item = item;
}
/**
* Gets the id of the {@link Item}.
*
* @return The id.
*/
public int getId() {
return item.getId();
}
/**
* Gets the amount of the {@link Item}.
*
* @return The amount.
*/
public int getamount() {
return item.getAmount();
}
/**
* Gets the item.
*
* @return The item.
*/
public Item getItem() {
return item;
}
/**
* Gets the slot.
*
* @return The slot.
*/
public int getSlot() {
return slot;
}
}
|
src/org/apollo/game/model/SlottedItem.java
|
package org.apollo.game.model;
/**
* A class which contains an {@link Item} and its corresponding slot.
*
* @author Graham
*/
public final class SlottedItem {
/**
* The item.
*/
private final Item item;
/**
* The slot.
*/
private final int slot;
/**
* Creates a new slotted item.
*
* @param slot The slot.
* @param item The item.
*/
public SlottedItem(int slot, Item item) {
this.slot = slot;
this.item = item;
}
/**
* Gets the item.
*
* @return The item.
*/
public Item getItem() {
return item;
}
/**
* Gets the slot.
*
* @return The slot.
*/
public int getSlot() {
return slot;
}
}
|
Add utility methods to SlottedItem.
|
src/org/apollo/game/model/SlottedItem.java
|
Add utility methods to SlottedItem.
|
|
Java
|
mit
|
a1bb67d972ddd5113f206ab0593061506224772b
| 0
|
jarex410/Dziennik
|
package com.diary.dao;
import com.diary.model.DiaryUser;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* Created by JaroLP on 2016-11-05.
*/
@Repository
public class UserDAO<T> extends AbstractDAO<DiaryUser> {
@Autowired
SessionFactory sessionFactory;
private Class<T> type;
public UserDAO() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
type = (Class) pt.getActualTypeArguments()[0];
}
public T getUser(Class clazz, Object t) {
return (T) (this.sessionFactory.getCurrentSession().get(clazz, (Serializable) t));
}
public DiaryUser findByLogin(String login) {
return (DiaryUser) sessionFactory.getCurrentSession().createQuery("FROM DiaryUser WHERE login = ?").setParameter(0, login);
}
}
|
src/main/java/com/diary/dao/UserDAO.java
|
package com.diary.dao;
import com.diary.model.DiaryUser;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* Created by JaroLP on 2016-11-05.
*/
@Repository
public abstract class UserDAO<T> extends AbstractDAO<DiaryUser> {
@Autowired
SessionFactory sessionFactory;
private Class<T> type;
public UserDAO() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
type = (Class) pt.getActualTypeArguments()[0];
}
public T getUser(Class clazz, Object t) {
return (T) (this.sessionFactory.getCurrentSession().get(clazz, (Serializable) t));
}
public DiaryUser findByLogin(String login) {
return (DiaryUser) sessionFactory.getCurrentSession().createQuery("FROM DiaryUser WHERE login = ?").setParameter(0, login);
}
}
|
Fix dla wstrzykiwania
|
src/main/java/com/diary/dao/UserDAO.java
|
Fix dla wstrzykiwania
|
|
Java
|
mit
|
be04a36f78c563ea4284b5b5c4eb4e3f60553385
| 0
|
CS2103AUG2016-T09-C2/main,CS2103AUG2016-T09-C2/main
|
package seedu.jimi.logic.parser;
import static seedu.jimi.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.jimi.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import seedu.jimi.commons.exceptions.IllegalValueException;
import seedu.jimi.commons.util.StringUtil;
import seedu.jimi.logic.commands.*;
/**
* Parses user input.
*/
public class JimiParser {
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)");
private static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
private static final Pattern TASK_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes
Pattern.compile("(?<detailsArguments>[^/]+)(?<tagArguments>(?: t/[^/]+)?)"); // zero or one tag only
private static final Pattern EDIT_DATA_ARGS_FORMAT = // accepts index at beginning, follows task/event patterns after
Pattern.compile("(?<targetIndex>\\d+\\s)(?<name>[^/]+)(?<tagArguments>(?: t/[^/]+)?)");
private static final Pattern DETAILS_ARGS_FORMAT =
Pattern.compile("(\"(?<taskDetails>.+)\")( by (?<dateTime>.+))?");
public JimiParser() {}
/**
* Parses user input into command for execution.
*
* @param userInput full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
if (AddCommand.isCommandWord(commandWord)) {
return prepareAdd(arguments);
} else if (EditCommand.isCommandWord(commandWord)) {
return prepareEdit(arguments);
} else if (SelectCommand.isCommandWord(commandWord)) {
return prepareSelect(arguments);
} else if (DeleteCommand.isCommandWord(commandWord)) {
return prepareDelete(arguments);
} else if (ClearCommand.isCommandWord(commandWord)) {
return new ClearCommand();
} else if (FindCommand.isCommandWord(commandWord)) {
return prepareFind(arguments);
} else if (ListCommand.isCommandWord(commandWord)) {
return new ListCommand();
} else if (ExitCommand.COMMAND_WORD.equals(commandWord)) {
return new ExitCommand();
} else if (HelpCommand.isCommandWord(commandWord)) {
return new HelpCommand();
} else {
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
/**
* Parses arguments in the context of the add task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareAdd(String args){
final Matcher detailsAndTagsMatcher = TASK_DATA_ARGS_FORMAT.matcher(args.trim());
// Validate entire args string format
if (!detailsAndTagsMatcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
final Matcher detailsMatcher =
DETAILS_ARGS_FORMAT.matcher(detailsAndTagsMatcher.group("detailsArguments").trim());
// Validate details args format
if (!detailsMatcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
try {
return new AddCommand(
detailsMatcher.group("taskDetails"),
detailsMatcher.group("dateTime"),
getTagsFromArgs(detailsAndTagsMatcher.group("tagArguments"))
);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
/**
* Parses arguments in context of the edit task command.
*
* @param args Full user command input args
* @return the prepared edit command
*/
private Command prepareEdit(String args){
final Matcher matcher = EDIT_DATA_ARGS_FORMAT.matcher(args.trim());
// Validate arg string format
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
try {
return new EditCommand(
matcher.group("name"),
getTagsFromArgs(matcher.group("tagArguments")),
Integer.parseInt(matcher.group("targetIndex").trim())
);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
/**
* Extracts the new task's tags from the add command's tag arguments string.
* Merges duplicate tag strings.
*/
private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException {
// no tags
if (tagArguments.isEmpty()) {
return Collections.emptySet();
}
// replace first delimiter prefix, then split
final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/"));
return new HashSet<>(tagStrings);
}
/**
* Parses arguments in the context of the delete task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareDelete(String args) {
Optional<Integer> index = parseIndex(args);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(index.get());
}
/**
* Parses arguments in the context of the select task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareSelect(String args) {
Optional<Integer> index = parseIndex(args);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE));
}
return new SelectCommand(index.get());
}
/**
* Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index.
* Returns an {@code Optional.empty()} otherwise.
*/
private Optional<Integer> parseIndex(String command) {
final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if(!StringUtil.isUnsignedInteger(index)){
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
/**
* Parses arguments in the context of the find task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareFind(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
FindCommand.MESSAGE_USAGE));
}
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
return new FindCommand(keywordSet);
}
}
|
src/main/java/seedu/jimi/logic/parser/JimiParser.java
|
package seedu.jimi.logic.parser;
import static seedu.jimi.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.jimi.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import seedu.jimi.commons.exceptions.IllegalValueException;
import seedu.jimi.commons.util.StringUtil;
import seedu.jimi.logic.commands.*;
/**
* Parses user input.
*/
public class JimiParser {
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)");
private static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
private static final Pattern TASK_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes
Pattern.compile("(?<detailsArguments>[^/]+)(?<tagArguments>(?: t/[^/]+)?)"); // zero or one tag only
private static final Pattern EDIT_DATA_ARGS_FORMAT = // accepts index at beginning, follows task/event patterns after
Pattern.compile("(?<targetIndex>\\d+\\s)(?<name>[^/]+)(?<tagArguments>(?: t/[^/]+)?)");
private static final Pattern DETAILS_ARGS_FORMAT =
Pattern.compile("(\"(?<taskDetails>.+)\")( by (?<dateTime>.+))?");
public JimiParser() {}
/**
* Parses user input into command for execution.
*
* @param userInput full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
if (AddCommand.isCommandWord(commandWord)) {
return prepareAdd(arguments);
} else if (EditCommand.isCommandWord(commandWord)) {
return prepareEdit(arguments);
} else if (SelectCommand.isCommandWord(commandWord)) {
return prepareSelect(arguments);
} else if (DeleteCommand.isCommandWord(commandWord)) {
return prepareDelete(arguments);
} else if (ClearCommand.isCommandWord(commandWord)) {
return new ClearCommand();
} else if (FindCommand.isCommandWord(commandWord)) {
return prepareFind(arguments);
} else if (ListCommand.isCommandWord(commandWord)) {
return new ListCommand();
} else if (ExitCommand.COMMAND_WORD.equals(commandWord)) {
return new ExitCommand();
} else if (HelpCommand.isCommandWord(commandWord)) {
return new HelpCommand();
} else {
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
/**
* Parses arguments in the context of the add task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareAdd(String args){
final Matcher detailsAndTagsMatcher = TASK_DATA_ARGS_FORMAT.matcher(args.trim());
// Validate entire args string format
if (!detailsAndTagsMatcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
final Matcher detailsMatcher =
DETAILS_ARGS_FORMAT.matcher(detailsAndTagsMatcher.group("detailsArguments").trim());
// Validate details args format
if (!detailsMatcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
try {
return new AddCommand(
detailsMatcher.group("taskDetails"),
detailsMatcher.group("dateTime"),
getTagsFromArgs(detailsAndTagsMatcher.group("tagArguments"))
);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
/**
* Parses arguments in context of the edit task command.
*
* @param args Full user command input args
* @return the prepared edit command
*/
private Command prepareEdit(String args){
final Matcher matcher = EDIT_DATA_ARGS_FORMAT.matcher(args.trim());
// Validate arg string format
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
try {
return new EditCommand(
matcher.group("name"),
getTagsFromArgs(matcher.group("tagArguments")),
Integer.parseInt(matcher.group("targetIndex").trim())
);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
/**
* Extracts the new task's tags from the add command's tag arguments string.
* Merges duplicate tag strings.
*/
private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException {
// no tags
if (tagArguments.isEmpty()) {
return Collections.emptySet();
}
// replace first delimiter prefix, then split
final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/"));
return new HashSet<>(tagStrings);
}
/**
* Parses arguments in the context of the delete task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareDelete(String args) {
Optional<Integer> index = parseIndex(args);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(index.get());
}
/**
* Parses arguments in the context of the select task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareSelect(String args) {
Optional<Integer> index = parseIndex(args);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE));
}
return new SelectCommand(index.get());
}
/**
* Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index.
* Returns an {@code Optional.empty()} otherwise.
*/
private Optional<Integer> parseIndex(String command) {
final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if(!StringUtil.isUnsignedInteger(index)){
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
/**
* Parses arguments in the context of the find task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareFind(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
FindCommand.MESSAGE_USAGE));
}
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
return new FindCommand(keywordSet);
}
}
|
JimiParser: format
|
src/main/java/seedu/jimi/logic/parser/JimiParser.java
|
JimiParser: format
|
|
Java
|
mit
|
872d4c55c571a47e0ef995e0a22de9464c4aad56
| 0
|
floatec/meteor-storm-libGDX,FollowJack/GameJamV
|
package de.floatec.meteorstorm;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
public class MeteorAnimation {
public static final int FRAME_COUNT = 8;
public static final float FRAME_DURATION = 0.025f;
Animation animation;
Texture sheet;
TextureRegion[] frames;
TextureRegion currentFrame;
private float stateTime;
private float x, y;
private float scale;
private float fulltime = 0 ;
public MeteorAnimation(float x,float y,float scale) {
this.x=x;
this.y=y;
this.scale=scale;
sheet = new Texture(Gdx.files.internal("animation.png"));
TextureRegion[][] tmp = TextureRegion.split(sheet, sheet.getWidth()/ FRAME_COUNT, sheet.getHeight());
frames = new TextureRegion[FRAME_COUNT];
int index = 0;
for (int i = 0; i < FRAME_COUNT; i++) {
frames[index++] = tmp[0][i];
}
animation = new Animation(FRAME_DURATION, frames);
stateTime = 0f;
}
public void update(float dt) {
stateTime += dt;
fulltime += dt;
currentFrame = animation.getKeyFrame(stateTime, false);
}
public void draw(SpriteBatch batch){
batch.draw(currentFrame, x, y,sheet.getWidth()/FRAME_COUNT*scale,sheet.getHeight()*scale);
}
public boolean isRunnung(){
return fulltime<=FRAME_DURATION*FRAME_COUNT;
}
}
|
core/src/de/floatec/meteorstorm/MeteorAnimation.java
|
package de.floatec.meteorstorm;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
public class MeteorAnimation {
Animation animation;
Texture sheet;
TextureRegion[] frames;
TextureRegion currentFrame;
private float stateTime;
private float x, y;
private float scale;
private float fulltime = 0 ;
public MeteorAnimation(float x,float y,float scale) {
this.x=x;
this.y=y;
this.scale=scale;
sheet = new Texture(Gdx.files.internal("animation.png"));
TextureRegion[][] tmp = TextureRegion.split(sheet, sheet.getWidth()/8, sheet.getHeight());
frames = new TextureRegion[8];
int index = 0;
for (int i = 0; i < 8; i++) {
frames[index++] = tmp[0][i];
}
animation = new Animation(0.025f, frames);
stateTime = 0f;
}
public void update(float dt) {
stateTime += dt;
fulltime += dt;
currentFrame = animation.getKeyFrame(stateTime, false);
}
public void draw(SpriteBatch batch){
batch.draw(currentFrame, x, y,sheet.getWidth()/8*scale,sheet.getHeight()*scale);
}
public boolean isRunnung(){
return fulltime<=0.025*8;
}
}
|
konstanten
|
core/src/de/floatec/meteorstorm/MeteorAnimation.java
|
konstanten
|
|
Java
|
mit
|
70bffd661648402ef43000ee2111618ee52f4268
| 0
|
JosueDanielBust/EventsManagerSoftware
|
package Main;
import java.sql.*;
//import java.sql.Connection;
//import java.sql.DriverManager;
public class dbAccess {
//objeto de conexion
private Connection conexion;
public static void main(String[] args) {
dbAccess obconeccion=new dbAccess();
obconeccion.Conectar();
}
public Connection getConexion() { return conexion; }
public void setConexion(Connection conexion) { this.conexion = conexion; }
public dbAccess Conectar() {
try {
Class.forName("oracle.jdbc.OracleDriver");
String DB = "jdbc:oracle:thin:@dbeafit.cyzd3byk9uno.us-east-1.rds.amazonaws.com:1521:DB20161";
conexion= DriverManager.getConnection(DB,"jbusta16","mlyBQM93");
if(conexion!=null){
System.out.println("Conexion exitosa a esquema JBUSTA16");
} else {
System.out.println("Conexion fallida");
}
ResultSet st = conexion.createStatement().executeQuery("SELECT * FROM CITY C INNER JOIN PLACE P ON P.CITY_ID = C.CITY_ID");
while (st.next()) {
Array []data;
data.add(st.getString(1), st.getString(2), st.getString(3), st.getString(4), st.getString(5), st.getString(6));
}
} catch(Exception e){ e.printStackTrace(); }
return this;
}
public boolean ejecutar(String sql){
try{
Statement st = getConexion().createStatement(
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
st.executeUpdate(sql);
getConexion().commit();
}catch(SQLException e){
e.printStackTrace();
return false;
}
return true;
}
public ResultSet Consultar(String sql){
ResultSet salida=null;
try{
Statement st = getConexion().createStatement();
salida = st.executeQuery(sql);
}catch(SQLException e){
e.printStackTrace();
}
return salida;
}
}
|
EVS/src/Main/dbAccess.java
|
package Main;
import java.sql.*;
//import java.sql.Connection;
//import java.sql.DriverManager;
public class dbAccess {
//objeto de conexion
private Connection conexion;
public static void main(String[] args) {
dbAccess obconeccion=new dbAccess();
obconeccion.Conectar();
}
public Connection getConexion() { return conexion; }
public void setConexion(Connection conexion) { this.conexion = conexion; }
public dbAccess Conectar() {
try {
Class.forName("oracle.jdbc.OracleDriver");
String DB = "jdbc:oracle:thin:@dbeafit.cyzd3byk9uno.us-east-1.rds.amazonaws.com:1521:DB20161";
conexion= DriverManager.getConnection(DB,"jbusta16","mlyBQM93");
if(conexion!=null){
System.out.println("Conexion exitosa a esquema JBUSTA16");
} else {
System.out.println("Conexion fallida");
}
ResultSet st = conexion.createStatement().executeQuery("SELECT * FROM CITY C INNER JOIN PLACE P ON P.CITY_ID = C.CITY_ID");
while (st.next()) {
Array []data;
data.add(st.getString(1), st.getString(2), st.getString(3), st.getString(4), st.getString(5), st.getString(6));
}
} catch(Exception e){ e.printStackTrace(); }
return this;
}
public boolean ejecutar(String sql){
try{
Statement st = getConexion().createStatement(
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
st.executeUpdate(sql);
getConexion().commit();
}catch(SQLException e){
e.printStackTrace();
return false;
}
return true;
}
public ResultSet Consultar(String sql){
}}
|
Creando metodo de consulta
|
EVS/src/Main/dbAccess.java
|
Creando metodo de consulta
|
|
Java
|
mit
|
ca9d1d5cf85eab77ba0c400df1e75d21d366609b
| 0
|
ryan-williams/Hadoop-BAM,fnothaft/Hadoop-BAM,HadoopGenomics/Hadoop-BAM,HadoopGenomics/Hadoop-BAM,ryan-williams/Hadoop-BAM,cmnbroad/Hadoop-BAM,HadoopGenomics/Hadoop-BAM,fnothaft/Hadoop-BAM,fnothaft/Hadoop-BAM,cmnbroad/Hadoop-BAM
|
// Copyright (c) 2012 Aalto University
//
// 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.
// File created: 2012-02-22 20:40:39
package org.seqdoop.hadoop_bam;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathNotFoundException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
/** An {@link org.apache.hadoop.mapreduce.InputFormat} for SAM, BAM, and CRAM files.
* Values are the individual records; see {@link BAMRecordReader} for the
* meaning of the key.
*
* <p>By default, files are recognized as SAM, BAM, or CRAM based on their file
* extensions: see {@link #TRUST_EXTS_PROPERTY}. If that fails, or this
* behaviour is disabled, the first byte of each file is read to determine the
* file type.</p>
*/
public class AnySAMInputFormat
extends FileInputFormat<LongWritable,SAMRecordWritable>
{
/** A Boolean property: are file extensions trusted? The default is
* <code>true</code>.
*
* @see SAMFormat#inferFromFilePath
*/
public static final String TRUST_EXTS_PROPERTY =
"hadoopbam.anysam.trust-exts";
private final BAMInputFormat bamIF = new BAMInputFormat();
private final CRAMInputFormat cramIF = new CRAMInputFormat();
private final SAMInputFormat samIF = new SAMInputFormat();
private final Map<Path,SAMFormat> formatMap;
private final boolean givenMap;
private Configuration conf;
private boolean trustExts;
/** Creates a new input format, which will use the
* <code>Configuration</code> from the first public method called. Thus this
* will behave as though constructed with a <code>Configuration</code>
* directly, but only after it has received it in
* <code>createRecordReader</code> (via the <code>TaskAttemptContext</code>)
* or <code>isSplitable</code> or <code>getSplits</code> (via the
* <code>JobContext</code>). Until then, other methods will throw an {@link
* IllegalStateException}.
*
* This constructor exists mainly as a convenience, e.g. so that
* <code>AnySAMInputFormat</code> can be used directly in
* <code>Job.setInputFormatClass</code>.
*/
public AnySAMInputFormat() {
this.formatMap = new HashMap<Path,SAMFormat>();
this.givenMap = false;
this.conf = null;
}
/** Creates a new input format, reading {@link #TRUST_EXTS_PROPERTY} from
* the given <code>Configuration</code>.
*/
public AnySAMInputFormat(Configuration conf) {
this.formatMap = new HashMap<Path,SAMFormat>();
this.conf = conf;
this.trustExts = conf.getBoolean(TRUST_EXTS_PROPERTY, true);
this.givenMap = false;
}
/** Creates a new input format, trusting the given <code>Map</code> to
* define the file-to-format associations. Neither file paths nor their
* contents are looked at, only the <code>Map</code> is used.
*
* <p>The <code>Map</code> is not copied, so it should not be modified while
* this input format is in use!</p>
* */
public AnySAMInputFormat(Map<Path,SAMFormat> formatMap) {
this.formatMap = formatMap;
this.givenMap = true;
// Arbitrary values.
this.conf = null;
this.trustExts = false;
}
/** Returns the {@link SAMFormat} corresponding to the given path. Returns
* <code>null</code> if it cannot be determined even based on the file
* contents (unless future SAM/BAM formats are very different, this means
* that the path does not refer to a SAM or BAM file).
*
* <p>If this input format was constructed using a given
* <code>Map<Path,SAMFormat></code> and the path is not contained
* within that map, throws an {@link IllegalArgumentException}.</p>
*/
public SAMFormat getFormat(final Path path) throws PathNotFoundException {
SAMFormat fmt = formatMap.get(path);
if (fmt != null || formatMap.containsKey(path))
return fmt;
if (givenMap)
throw new IllegalArgumentException(
"SAM format for '"+path+"' not in given map");
if (this.conf == null)
throw new IllegalStateException("Don't have a Configuration yet");
if (trustExts) {
final SAMFormat f = SAMFormat.inferFromFilePath(path);
if (f != null) {
formatMap.put(path, f);
return f;
}
}
try {
FileSystem fileSystem = path.getFileSystem(conf);
if (!fileSystem.exists(path)) {
throw new PathNotFoundException(path.toString());
}
fmt = SAMFormat.inferFromData(fileSystem.open(path));
} catch (IOException e) {}
formatMap.put(path, fmt);
return fmt;
}
/** Returns a {@link BAMRecordReader} or {@link SAMRecordReader} as
* appropriate, initialized with the given parameters.
*
* <p>Throws {@link IllegalArgumentException} if the given input split is
* not a {@link FileVirtualSplit} (used by {@link BAMInputFormat}) or a
* {@link FileSplit} (used by {@link SAMInputFormat}), or if the path
* referred to is not recognized as a SAM, BAM, or CRAM file (see {@link
* #getFormat}).</p>
*/
@Override public RecordReader<LongWritable,SAMRecordWritable>
createRecordReader(InputSplit split, TaskAttemptContext ctx)
throws InterruptedException, IOException
{
final Path path;
if (split instanceof FileSplit)
path = ((FileSplit)split).getPath();
else if (split instanceof FileVirtualSplit)
path = ((FileVirtualSplit)split).getPath();
else
throw new IllegalArgumentException(
"split '"+split+"' has unknown type: cannot extract path");
if (this.conf == null)
this.conf = ctx.getConfiguration();
final SAMFormat fmt = getFormat(path);
if (fmt == null)
throw new IllegalArgumentException(
"unknown SAM format, cannot create RecordReader: "+path);
switch (fmt) {
case SAM: return samIF.createRecordReader(split, ctx);
case BAM: return bamIF.createRecordReader(split, ctx);
case CRAM: return cramIF.createRecordReader(split, ctx);
default: assert false; return null;
}
}
/** Defers to {@link BAMInputFormat}, {@link CRAMInputFormat}, or
* {@link SAMInputFormat} as appropriate for the given path.
*/
@Override public boolean isSplitable(JobContext job, Path path) {
if (this.conf == null)
this.conf = job.getConfiguration();
try {
final SAMFormat fmt = getFormat(path);
if (fmt == null)
return super.isSplitable(job, path);
switch (fmt) {
case SAM: return samIF.isSplitable(job, path);
case BAM: return bamIF.isSplitable(job, path);
case CRAM: return cramIF.isSplitable(job, path);
default: assert false; return false;
}
} catch (PathNotFoundException e) {
return super.isSplitable(job, path);
}
}
/** Defers to {@link BAMInputFormat} or {@link CRAMInputFormat} as appropriate for each
* individual path. SAM paths do not require special handling, so their splits are left
* unchanged.
*/
@Override public List<InputSplit> getSplits(JobContext job)
throws IOException
{
if (this.conf == null)
this.conf = job.getConfiguration();
final List<InputSplit> origSplits = super.getSplits(job);
// We have to partition the splits by input format and hand them over to
// the *InputFormats for any further handling.
//
// BAMInputFormat and CRAMInputFormat need to change the split boundaries, so we can
// just extract the BAM and CRAM ones and leave the rest as they are.
final List<InputSplit>
bamOrigSplits = new ArrayList<InputSplit>(origSplits.size()),
cramOrigSplits = new ArrayList<InputSplit>(origSplits.size()),
newSplits = new ArrayList<InputSplit>(origSplits.size());
for (final InputSplit iSplit : origSplits) {
final FileSplit split = (FileSplit)iSplit;
if (SAMFormat.BAM.equals(getFormat(split.getPath())))
bamOrigSplits.add(split);
else if (SAMFormat.CRAM.equals(getFormat(split.getPath())))
cramOrigSplits.add(split);
else
newSplits.add(split);
}
newSplits.addAll(bamIF.getSplits(bamOrigSplits, job.getConfiguration()));
newSplits.addAll(cramIF.getSplits(cramOrigSplits, job.getConfiguration()));
return newSplits;
}
}
|
src/main/java/org/seqdoop/hadoop_bam/AnySAMInputFormat.java
|
// Copyright (c) 2012 Aalto University
//
// 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.
// File created: 2012-02-22 20:40:39
package org.seqdoop.hadoop_bam;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
/** An {@link org.apache.hadoop.mapreduce.InputFormat} for SAM, BAM, and CRAM files.
* Values are the individual records; see {@link BAMRecordReader} for the
* meaning of the key.
*
* <p>By default, files are recognized as SAM, BAM, or CRAM based on their file
* extensions: see {@link #TRUST_EXTS_PROPERTY}. If that fails, or this
* behaviour is disabled, the first byte of each file is read to determine the
* file type.</p>
*/
public class AnySAMInputFormat
extends FileInputFormat<LongWritable,SAMRecordWritable>
{
/** A Boolean property: are file extensions trusted? The default is
* <code>true</code>.
*
* @see SAMFormat#inferFromFilePath
*/
public static final String TRUST_EXTS_PROPERTY =
"hadoopbam.anysam.trust-exts";
private final BAMInputFormat bamIF = new BAMInputFormat();
private final CRAMInputFormat cramIF = new CRAMInputFormat();
private final SAMInputFormat samIF = new SAMInputFormat();
private final Map<Path,SAMFormat> formatMap;
private final boolean givenMap;
private Configuration conf;
private boolean trustExts;
/** Creates a new input format, which will use the
* <code>Configuration</code> from the first public method called. Thus this
* will behave as though constructed with a <code>Configuration</code>
* directly, but only after it has received it in
* <code>createRecordReader</code> (via the <code>TaskAttemptContext</code>)
* or <code>isSplitable</code> or <code>getSplits</code> (via the
* <code>JobContext</code>). Until then, other methods will throw an {@link
* IllegalStateException}.
*
* This constructor exists mainly as a convenience, e.g. so that
* <code>AnySAMInputFormat</code> can be used directly in
* <code>Job.setInputFormatClass</code>.
*/
public AnySAMInputFormat() {
this.formatMap = new HashMap<Path,SAMFormat>();
this.givenMap = false;
this.conf = null;
}
/** Creates a new input format, reading {@link #TRUST_EXTS_PROPERTY} from
* the given <code>Configuration</code>.
*/
public AnySAMInputFormat(Configuration conf) {
this.formatMap = new HashMap<Path,SAMFormat>();
this.conf = conf;
this.trustExts = conf.getBoolean(TRUST_EXTS_PROPERTY, true);
this.givenMap = false;
}
/** Creates a new input format, trusting the given <code>Map</code> to
* define the file-to-format associations. Neither file paths nor their
* contents are looked at, only the <code>Map</code> is used.
*
* <p>The <code>Map</code> is not copied, so it should not be modified while
* this input format is in use!</p>
* */
public AnySAMInputFormat(Map<Path,SAMFormat> formatMap) {
this.formatMap = formatMap;
this.givenMap = true;
// Arbitrary values.
this.conf = null;
this.trustExts = false;
}
/** Returns the {@link SAMFormat} corresponding to the given path. Returns
* <code>null</code> if it cannot be determined even based on the file
* contents (unless future SAM/BAM formats are very different, this means
* that the path does not refer to a SAM or BAM file).
*
* <p>If this input format was constructed using a given
* <code>Map<Path,SAMFormat></code> and the path is not contained
* within that map, throws an {@link IllegalArgumentException}.</p>
*/
public SAMFormat getFormat(final Path path) {
SAMFormat fmt = formatMap.get(path);
if (fmt != null || formatMap.containsKey(path))
return fmt;
if (givenMap)
throw new IllegalArgumentException(
"SAM format for '"+path+"' not in given map");
if (this.conf == null)
throw new IllegalStateException("Don't have a Configuration yet");
if (trustExts) {
final SAMFormat f = SAMFormat.inferFromFilePath(path);
if (f != null) {
formatMap.put(path, f);
return f;
}
}
try {
fmt = SAMFormat.inferFromData(path.getFileSystem(conf).open(path));
} catch (IOException e) {}
formatMap.put(path, fmt);
return fmt;
}
/** Returns a {@link BAMRecordReader} or {@link SAMRecordReader} as
* appropriate, initialized with the given parameters.
*
* <p>Throws {@link IllegalArgumentException} if the given input split is
* not a {@link FileVirtualSplit} (used by {@link BAMInputFormat}) or a
* {@link FileSplit} (used by {@link SAMInputFormat}), or if the path
* referred to is not recognized as a SAM, BAM, or CRAM file (see {@link
* #getFormat}).</p>
*/
@Override public RecordReader<LongWritable,SAMRecordWritable>
createRecordReader(InputSplit split, TaskAttemptContext ctx)
throws InterruptedException, IOException
{
final Path path;
if (split instanceof FileSplit)
path = ((FileSplit)split).getPath();
else if (split instanceof FileVirtualSplit)
path = ((FileVirtualSplit)split).getPath();
else
throw new IllegalArgumentException(
"split '"+split+"' has unknown type: cannot extract path");
if (this.conf == null)
this.conf = ctx.getConfiguration();
final SAMFormat fmt = getFormat(path);
if (fmt == null)
throw new IllegalArgumentException(
"unknown SAM format, cannot create RecordReader: "+path);
switch (fmt) {
case SAM: return samIF.createRecordReader(split, ctx);
case BAM: return bamIF.createRecordReader(split, ctx);
case CRAM: return cramIF.createRecordReader(split, ctx);
default: assert false; return null;
}
}
/** Defers to {@link BAMInputFormat}, {@link CRAMInputFormat}, or
* {@link SAMInputFormat} as appropriate for the given path.
*/
@Override public boolean isSplitable(JobContext job, Path path) {
if (this.conf == null)
this.conf = job.getConfiguration();
final SAMFormat fmt = getFormat(path);
if (fmt == null)
return super.isSplitable(job, path);
switch (fmt) {
case SAM: return samIF.isSplitable(job, path);
case BAM: return bamIF.isSplitable(job, path);
case CRAM: return cramIF.isSplitable(job, path);
default: assert false; return false;
}
}
/** Defers to {@link BAMInputFormat} or {@link CRAMInputFormat} as appropriate for each
* individual path. SAM paths do not require special handling, so their splits are left
* unchanged.
*/
@Override public List<InputSplit> getSplits(JobContext job)
throws IOException
{
if (this.conf == null)
this.conf = job.getConfiguration();
final List<InputSplit> origSplits = super.getSplits(job);
// We have to partition the splits by input format and hand them over to
// the *InputFormats for any further handling.
//
// BAMInputFormat and CRAMInputFormat need to change the split boundaries, so we can
// just extract the BAM and CRAM ones and leave the rest as they are.
final List<InputSplit>
bamOrigSplits = new ArrayList<InputSplit>(origSplits.size()),
cramOrigSplits = new ArrayList<InputSplit>(origSplits.size()),
newSplits = new ArrayList<InputSplit>(origSplits.size());
for (final InputSplit iSplit : origSplits) {
final FileSplit split = (FileSplit)iSplit;
if (SAMFormat.BAM.equals(getFormat(split.getPath())))
bamOrigSplits.add(split);
else if (SAMFormat.CRAM.equals(getFormat(split.getPath())))
cramOrigSplits.add(split);
else
newSplits.add(split);
}
newSplits.addAll(bamIF.getSplits(bamOrigSplits, job.getConfiguration()));
newSplits.addAll(cramIF.getSplits(cramOrigSplits, job.getConfiguration()));
return newSplits;
}
}
|
Throw PathNotFoundException if path not found in createRecordReader
|
src/main/java/org/seqdoop/hadoop_bam/AnySAMInputFormat.java
|
Throw PathNotFoundException if path not found in createRecordReader
|
|
Java
|
mit
|
8c181c04131c60014fb245be329ea8508080dbc5
| 0
|
LadyViktoria/wearDrip
|
package weardrip.weardrip;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.wearable.watchface.CanvasWatchFaceService;
import android.support.wearable.watchface.WatchFaceService;
import android.support.wearable.watchface.WatchFaceStyle;
import android.text.format.Time;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.widget.TextView;
import com.eveningoutpost.dexdrip.Models.BgReading;
import com.eveningoutpost.dexdrip.UtilityModels.CollectionServiceStarter;
import com.eveningoutpost.dexdrip.UtilityModels.Intents;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.realm.implementation.RealmLineData;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import io.realm.Realm;
import io.realm.RealmObject;
import io.realm.RealmQuery;
import io.realm.RealmResults;
public class wearDripWatchFace extends CanvasWatchFaceService {
private static final Typeface NORMAL_TYPEFACE = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL);
private static final long INTERACTIVE_UPDATE_RATE_MS = TimeUnit.SECONDS.toMillis(1);
/**
* Update rate in milliseconds for interactive mode. We update once a second since seconds are
* displayed in interactive mode.
*/
@Override
public Engine onCreateEngine() {
CollectionServiceStarter.newStart(this);
return new Engine();
}
private class Engine extends CanvasWatchFaceService.Engine implements OnChartValueSelectedListener {
static final int MSG_UPDATE_TIME = 0;
/**
* Handler to update the time periodically in interactive mode.
*/
final Handler mUpdateTimeHandler = new Handler() {
@Override
public void handleMessage(Message message) {
switch (message.what) {
case MSG_UPDATE_TIME:
invalidate();
if (shouldTimerBeRunning()) {
long timeMs = System.currentTimeMillis();
long delayMs = INTERACTIVE_UPDATE_RATE_MS
- (timeMs % INTERACTIVE_UPDATE_RATE_MS);
mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs);
}
break;
}
}
};
final BroadcastReceiver mTimeZoneReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mTime.clear(intent.getStringExtra("time-zone"));
mTime.setToNow();
}
};
final BroadcastReceiver newDataReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
showBG();
unitizedDeltaString();
//addEntry();
refreshData();
GsonBG();
invalidate();
}
};
boolean mRegisterednewDataReceiver = false;
boolean mRegisteredTimeZoneReceiver = false;
boolean mAmbient;
boolean mLowBitAmbient;
private LineChart lineChart;
ArrayList<String> XAxisTimeValue = new ArrayList<String>();
String timestamplastreading = "--";
String bgvalue = "n/a";
String deltalastreading = "---";
double calculated_value = 0.0;
Time mTime;
float mXOffset = 0;
float mYOffset = 0;
private int specW, specH;
private View myLayout;
private TextView sgv, delta, watch_time, timestamp;
private final Point displaySize = new Point();
/**
* Whether the display supports fewer bits for each color in ambient mode. When true, we
* disable anti-aliasing in ambient mode.
*/
@Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
setWatchFaceStyle(new WatchFaceStyle.Builder(wearDripWatchFace.this)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_SHORT)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setShowSystemUiTime(false)
.setAcceptsTapEvents(true)
.build());
Resources resources = wearDripWatchFace.this.getResources();
mTime = new Time();
// Inflate the layout that we're using for the watch face
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myLayout = inflater.inflate(R.layout.wear_drip_watchface_layout, null);
// Load the display spec - we'll need this later for measuring myLayout
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
display.getSize(displaySize);
// Find some views for later use
sgv = (TextView) myLayout.findViewById(R.id.sgv);
delta = (TextView) myLayout.findViewById(R.id.delta);
timestamp = (TextView) myLayout.findViewById(R.id.timestamp);
watch_time = (TextView) myLayout.findViewById(R.id.watch_time);
SetupChart();
}
Realm realm;
public void SetupChart() {
lineChart = (LineChart) myLayout.findViewById(R.id.chart);
lineChart.setDescription("");
lineChart.setDrawBorders(false);
lineChart.setNoDataTextDescription("You need to provide data for the chart.");
lineChart.setDrawGridBackground(false);
//lineChart.setBackgroundColor(-1);
lineChart.setOnChartValueSelectedListener(this);
lineChart.setTouchEnabled(false);
lineChart.setDragEnabled(false);
lineChart.setPinchZoom(false);
lineChart.setScaleXEnabled(true);
lineChart.setScaleYEnabled(true);
lineChart.invalidate();
LineData data = new LineData();
data.setValueTextColor(Color.WHITE);
// add empty data
lineChart.setData(data);
// get the legend (only possible after setting data)
Legend l = lineChart.getLegend();
l.setEnabled(false);
// x axis setup
XAxis xl = lineChart.getXAxis();
xl.setTextColor(Color.WHITE);
xl.setDrawGridLines(false);
xl.setAvoidFirstLastClipping(false);
xl.setSpaceBetweenLabels(3);
xl.setEnabled(true);
xl.setDrawAxisLine(false);
xl.removeAllLimitLines();
//right y axis setup
YAxis rightAxis = lineChart.getAxisRight();
rightAxis.setEnabled(false);
//left y axis setup
YAxis leftAxis = lineChart.getAxisLeft();
leftAxis.setTextColor(Color.WHITE);
//leftAxis.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
leftAxis.setLabelCount(7, true);
leftAxis.setAxisMaxValue(400f);
leftAxis.setAxisMinValue(0f);
leftAxis.setDrawGridLines(false);
leftAxis.setStartAtZero(true);
leftAxis.setEnabled(true);
leftAxis.setDrawAxisLine(false);
leftAxis.setDrawZeroLine(false);
leftAxis.setGranularityEnabled(false);
LimitLine max = new LimitLine(150f);
max.enableDashedLine(10f, 10f, 0f);
LimitLine min = new LimitLine(50f);
min.enableDashedLine(10f, 10f, 0f);
// reset all limit lines to avoid overlapping lines
leftAxis.removeAllLimitLines();
leftAxis.addLimitLine(max);
leftAxis.addLimitLine(min);
lineChart.invalidate();
}
private LineDataSet createSet() {
LineDataSet set = new LineDataSet(null, "BG Data");
set.setAxisDependency(YAxis.AxisDependency.LEFT);
set.setColor(ColorTemplate.getHoloBlue());
set.setCircleColor(Color.WHITE);
set.setLineWidth(2f);
set.setCircleRadius(4f);
set.setFillAlpha(65);
set.setFillColor(ColorTemplate.getHoloBlue());
set.setHighLightColor(Color.rgb(244, 117, 117));
set.setValueTextColor(Color.WHITE);
set.setValueTextSize(9f);
set.setDrawValues(false);
return set;
}
private static final int VISIBLE_NUM = 3;
private void refreshData() {
LineData data = lineChart.getData();
if(data != null) {
LineDataSet set = (LineDataSet) data.getDataSetByIndex(0);
if (set == null) {
set = createSet();
data.addDataSet(set);
}
if(set.getEntryCount() == VISIBLE_NUM) {
data.removeXValue(0);
set.removeEntry(0);
for (Entry entry : set.getYVals()) {
entry.setXIndex(entry.getXIndex() - 1);
}
}
// add x-value
Date date = new Date();
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(date);
int inthours = calendar.get(Calendar.HOUR_OF_DAY);
int intminute = calendar.get(Calendar.MINUTE);
String hourString = String.format("%02d:", inthours);
String minuteString = String.format("%02d", intminute);
XAxisTimeValue.add(hourString + minuteString);
data.addXValue(XAxisTimeValue.get(data.getXValCount()));
// choose a dataSet
data.addEntry(new Entry((float) calculated_value, set.getEntryCount()), 0);
lineChart.notifyDataSetChanged();
lineChart.setVisibleYRangeMaximum((float) calculated_value, YAxis.AxisDependency.LEFT);
// this automatically refreshes the chart (calls invalidate())
lineChart.moveViewTo(data.getXValCount(), (float) calculated_value, YAxis.AxisDependency.LEFT);
}
}
public void GsonBG() {
realm = Realm.getInstance(getApplicationContext());
BgReading mBgReading;
mBgReading = BgReading.last();
if (mBgReading != null) {
Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
})
.create();
String json = mBgReading.toS();
BGdata bgdata = gson.fromJson(json, BGdata.class);
realm.beginTransaction();
BGdata copyOfBGdata = realm.copyToRealm(bgdata);
realm.commitTransaction();
Log.v("realmio", String.valueOf(copyOfBGdata));
} else {
}
}
public void showBG() {
BgReading mBgReading;
mBgReading = BgReading.last();
if (mBgReading != null) {
calculated_value = mBgReading.calculated_value;
DecimalFormat df = new DecimalFormat("#", new DecimalFormatSymbols(Locale.ENGLISH));
bgvalue = String.valueOf(df.format(calculated_value));
} else {
bgvalue = "n/a";
}
}
public void getTimestampLastreading() {
Long mTimeStampLastreading;
mTimeStampLastreading = BgReading.getTimeSinceLastReading();
if (mTimeStampLastreading != null) {
long minutesago=((mTimeStampLastreading)/1000)/60;
timestamplastreading = String.valueOf(minutesago);
} else {
timestamplastreading = "--'";
}
}
public void unitizedDeltaString() {
List<BgReading> last2 = BgReading.latest(2);
if (BgReading.latest(2) != null) {
if (last2.size() < 2 || last2.get(0).timestamp - last2.get(1).timestamp > 20 * 60 * 1000) {
// don't show delta if there are not enough values or the values are more than 20 mintes apart
deltalastreading = "???";
}
double value = BgReading.currentSlope() * 5 * 60 * 1000;
if (Math.abs(value) > 100) {
// a delta > 100 will not happen with real BG values -> problematic sensor data
deltalastreading = "ERR";
}
DecimalFormat df = new DecimalFormat("#", new DecimalFormatSymbols(Locale.ENGLISH));
String delta_sign = "";
if (value > 0) {
delta_sign = "+";
}
deltalastreading = delta_sign + df.format(value);
} else {
deltalastreading = "---";
}
}
@Override
public void onDestroy() {
mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
super.onDestroy();
}
@Override
public void onVisibilityChanged(boolean visible) {
super.onVisibilityChanged(visible);
if (visible) {
registerReceiver();
// Update time zone in case it changed while we weren't visible.
mTime.clear(TimeZone.getDefault().getID());
mTime.setToNow();
} else {
registerReceiver();
}
// Whether the timer should be running depends on whether we're visible (as well as
// whether we're in ambient mode), so we may need to start or stop the timer.
updateTimer();
}
private void unregisterReceiver() {
if (mRegisteredTimeZoneReceiver) {
mRegisteredTimeZoneReceiver = false;
wearDripWatchFace.this.unregisterReceiver(mTimeZoneReceiver);
}
if (mRegisterednewDataReceiver) {
mRegisterednewDataReceiver = false;
wearDripWatchFace.this.unregisterReceiver(newDataReceiver);
}
}
private void registerReceiver() {
if (!mRegisteredTimeZoneReceiver) {
mRegisteredTimeZoneReceiver = true;
IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED);
wearDripWatchFace.this.registerReceiver(mTimeZoneReceiver, filter);
}
if (!mRegisterednewDataReceiver) {
mRegisterednewDataReceiver = true;
IntentFilter filter = new IntentFilter(Intents.ACTION_NEW_BG_ESTIMATE_NO_DATA);
wearDripWatchFace.this.registerReceiver(newDataReceiver, filter);
}
}
@Override
public void onApplyWindowInsets(WindowInsets insets) {
super.onApplyWindowInsets(insets);
if (insets.isRound()) {
mXOffset = mYOffset = 0;
} else {
mXOffset = mYOffset = 0;
}
// Recompute the MeasureSpec fields - these determine the actual size of the layout
specW = View.MeasureSpec.makeMeasureSpec(displaySize.x, View.MeasureSpec.EXACTLY);
specH = View.MeasureSpec.makeMeasureSpec(displaySize.y, View.MeasureSpec.EXACTLY);
}
@Override
public void onPropertiesChanged(Bundle properties) {
super.onPropertiesChanged(properties);
mLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false);
}
@Override
public void onTimeTick() {
super.onTimeTick();
invalidate();
}
@Override
public void onAmbientModeChanged(boolean inAmbientMode) {
super.onAmbientModeChanged(inAmbientMode);
if (mAmbient != inAmbientMode) {
mAmbient = inAmbientMode;
// Show/hide the seconds fields
if (inAmbientMode) {
//second.setVisibility(View.GONE);
//myLayout.findViewById(R.id.chart).setVisibility(View.GONE);
} else {
//second.setVisibility(View.VISIBLE);
//myLayout.findViewById(R.id.chart).setVisibility(View.VISIBLE);
}
invalidate();
}
// Whether the timer should be running depends on whether we're visible (as well as
// whether we're in ambient mode), so we may need to start or stop the timer.
updateTimer();
}
@Override
public void onDraw(Canvas canvas, Rect bounds) {
// Get the current Time
mTime.setToNow();
delta.setText(deltalastreading);
sgv.setText(bgvalue);
watch_time.setText(String.format("%02d:%02d", mTime.hour, mTime.minute));
getTimestampLastreading();
timestamp.setText(timestamplastreading + "′");
//realmioquerry();
if (!mAmbient) {
//second.setText(String.format("%02d", mTime.second));
}
// Update the layout
myLayout.measure(specW, specH);
myLayout.layout(0, 0, myLayout.getMeasuredWidth(), myLayout.getMeasuredHeight());
// Draw it to the Canvas
canvas.drawColor(Color.BLACK);
canvas.translate(mXOffset, mYOffset);
myLayout.draw(canvas);
}
/**
* Starts the {@link #mUpdateTimeHandler} timer if it should be running and isn't currently
* or stops it if it shouldn't be running but currently is.
*/
private void updateTimer() {
mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
if (shouldTimerBeRunning()) {
mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME);
}
}
/**
* Returns whether the {@link #mUpdateTimeHandler} timer should be running. The timer should
* only run when we're visible and in interactive mode.
*/
private boolean shouldTimerBeRunning() {
return isVisible() && !isInAmbientMode();
}
@Override
public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
}
@Override
public void onNothingSelected() {
}
@Override
public void onTapCommand(
@TapType int tapType, int x, int y, long eventTime) {
switch (tapType) {
case WatchFaceService.TAP_TYPE_TAP:
break;
case WatchFaceService.TAP_TYPE_TOUCH:
break;
case WatchFaceService.TAP_TYPE_TOUCH_CANCEL:
break;
default:
super.onTapCommand(tapType, x, y, eventTime);
break;
}
}
}
}
|
wear/src/main/java/weardrip/weardrip/wearDripWatchFace.java
|
package weardrip.weardrip;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.wearable.watchface.CanvasWatchFaceService;
import android.support.wearable.watchface.WatchFaceService;
import android.support.wearable.watchface.WatchFaceStyle;
import android.text.format.Time;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.widget.TextView;
import com.eveningoutpost.dexdrip.Models.BgReading;
import com.eveningoutpost.dexdrip.UtilityModels.CollectionServiceStarter;
import com.eveningoutpost.dexdrip.UtilityModels.Intents;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.realm.implementation.RealmLineData;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import io.realm.Realm;
import io.realm.RealmObject;
import io.realm.RealmQuery;
import io.realm.RealmResults;
public class wearDripWatchFace extends CanvasWatchFaceService {
private static final Typeface NORMAL_TYPEFACE = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL);
private static final long INTERACTIVE_UPDATE_RATE_MS = TimeUnit.SECONDS.toMillis(1);
/**
* Update rate in milliseconds for interactive mode. We update once a second since seconds are
* displayed in interactive mode.
*/
@Override
public Engine onCreateEngine() {
CollectionServiceStarter.newStart(this);
return new Engine();
}
private class Engine extends CanvasWatchFaceService.Engine implements OnChartValueSelectedListener {
static final int MSG_UPDATE_TIME = 0;
/**
* Handler to update the time periodically in interactive mode.
*/
final Handler mUpdateTimeHandler = new Handler() {
@Override
public void handleMessage(Message message) {
switch (message.what) {
case MSG_UPDATE_TIME:
invalidate();
if (shouldTimerBeRunning()) {
long timeMs = System.currentTimeMillis();
long delayMs = INTERACTIVE_UPDATE_RATE_MS
- (timeMs % INTERACTIVE_UPDATE_RATE_MS);
mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs);
}
break;
}
}
};
final BroadcastReceiver mTimeZoneReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mTime.clear(intent.getStringExtra("time-zone"));
mTime.setToNow();
}
};
final BroadcastReceiver newDataReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
showBG();
unitizedDeltaString();
addEntry();
GsonBG();
invalidate();
}
};
boolean mRegisterednewDataReceiver = false;
boolean mRegisteredTimeZoneReceiver = false;
boolean mAmbient;
boolean mLowBitAmbient;
private LineChart lineChart;
ArrayList<String> XAxisTimeValue = new ArrayList<String>();
String timestamplastreading = "--";
String bgvalue = "n/a";
String deltalastreading = "---";
double calculated_value = 0.0;
Time mTime;
float mXOffset = 0;
float mYOffset = 0;
private int specW, specH;
private View myLayout;
private TextView sgv, delta, watch_time, timestamp;
private final Point displaySize = new Point();
/**
* Whether the display supports fewer bits for each color in ambient mode. When true, we
* disable anti-aliasing in ambient mode.
*/
@Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
setWatchFaceStyle(new WatchFaceStyle.Builder(wearDripWatchFace.this)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_SHORT)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setShowSystemUiTime(false)
.setAcceptsTapEvents(true)
.build());
Resources resources = wearDripWatchFace.this.getResources();
mTime = new Time();
// Inflate the layout that we're using for the watch face
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myLayout = inflater.inflate(R.layout.wear_drip_watchface_layout, null);
// Load the display spec - we'll need this later for measuring myLayout
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
display.getSize(displaySize);
// Find some views for later use
sgv = (TextView) myLayout.findViewById(R.id.sgv);
delta = (TextView) myLayout.findViewById(R.id.delta);
timestamp = (TextView) myLayout.findViewById(R.id.timestamp);
watch_time = (TextView) myLayout.findViewById(R.id.watch_time);
SetupChart();
}
Realm realm;
public void SetupChart() {
lineChart = (LineChart) myLayout.findViewById(R.id.chart);
lineChart.setDescription("");
lineChart.setDrawBorders(false);
lineChart.setNoDataTextDescription("You need to provide data for the chart.");
lineChart.setDrawGridBackground(false);
//lineChart.setBackgroundColor(-1);
lineChart.setOnChartValueSelectedListener(this);
lineChart.setTouchEnabled(false);
lineChart.setDragEnabled(false);
lineChart.setPinchZoom(false);
lineChart.setScaleXEnabled(true);
lineChart.setScaleYEnabled(true);
lineChart.invalidate();
LineData data = new LineData();
data.setValueTextColor(Color.WHITE);
// add empty data
lineChart.setData(data);
// get the legend (only possible after setting data)
Legend l = lineChart.getLegend();
l.setEnabled(false);
// x axis setup
XAxis xl = lineChart.getXAxis();
xl.setTextColor(Color.WHITE);
xl.setDrawGridLines(false);
xl.setAvoidFirstLastClipping(false);
xl.setSpaceBetweenLabels(5);
xl.setEnabled(true);
xl.setDrawAxisLine(false);
xl.removeAllLimitLines();
YAxis rightAxis = lineChart.getAxisRight();
rightAxis.setEnabled(false);
// y axis setup
YAxis leftAxis = lineChart.getAxisLeft();
leftAxis.setTextColor(Color.WHITE);
//leftAxis.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
leftAxis.setLabelCount(7, true);
leftAxis.setAxisMaxValue(400f);
leftAxis.setAxisMinValue(0f);
leftAxis.setDrawGridLines(false);
leftAxis.setStartAtZero(true);
leftAxis.setEnabled(true);
leftAxis.setDrawAxisLine(false);
leftAxis.setDrawZeroLine(false);
leftAxis.setGranularityEnabled(false);
LimitLine max = new LimitLine(150f);
max.enableDashedLine(10f, 10f, 0f);
LimitLine min = new LimitLine(50f);
min.enableDashedLine(10f, 10f, 0f);
// reset all limit lines to avoid overlapping lines
leftAxis.removeAllLimitLines();
leftAxis.addLimitLine(max);
leftAxis.addLimitLine(min);
lineChart.invalidate();
}
private LineDataSet createSet() {
LineDataSet set = new LineDataSet(null, "BG Data");
set.setAxisDependency(YAxis.AxisDependency.LEFT);
set.setColor(ColorTemplate.getHoloBlue());
set.setCircleColor(Color.WHITE);
set.setDrawCubic(true);
set.setLineWidth(2f);
set.setCircleRadius(4f);
set.setFillAlpha(65);
set.setFillColor(ColorTemplate.getHoloBlue());
set.setHighLightColor(Color.rgb(244, 117, 117));
set.setValueTextColor(Color.WHITE);
set.setValueTextSize(9f);
set.setDrawValues(false);
return set;
}
private void addEntry() {
LineData data = lineChart.getData();
if(data != null) {
ILineDataSet set = data.getDataSetByIndex(0);
// set.addEntry(...); // can be called as well
if (set == null) {
set = createSet();
data.addDataSet(set);
}
// add a new x-value first
Date date = new Date(); // given date
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date); // assigns calendar to given date
int inthours = calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
int intminute = calendar.get(Calendar.MINUTE);
String hourString = String.format("%02d:", inthours);
String minuteString = String.format("%02d", intminute);
XAxisTimeValue.add(hourString + minuteString);
data.addXValue(XAxisTimeValue.get(data.getXValCount()));
// choose a random dataSet
data.addEntry(new Entry((float) calculated_value, set.getEntryCount()), 0);
//int randomDataSetIndex = (int) (Math.random() * data.getDataSetCount());
//data.addEntry(new Entry((float) (Math.random() * 10) + 50f, set.getEntryCount()), randomDataSetIndex);
// let the chart know it's data has changed
lineChart.notifyDataSetChanged();
//lineChart.setVisibleXRangeMaximum(6);
lineChart.setVisibleYRangeMaximum((float)calculated_value, YAxis.AxisDependency.LEFT);
// this automatically refreshes the chart (calls invalidate())
lineChart.moveViewTo(data.getXValCount(), (float)calculated_value, YAxis.AxisDependency.LEFT);
}
}
public void GsonBG() {
realm = Realm.getInstance(getApplicationContext());
BgReading mBgReading;
mBgReading = BgReading.last();
if (mBgReading != null) {
Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
})
.create();
String json = mBgReading.toS();
BGdata bgdata = gson.fromJson(json, BGdata.class);
realm.beginTransaction();
BGdata copyOfBGdata = realm.copyToRealm(bgdata);
realm.commitTransaction();
Log.v("realmio", String.valueOf(copyOfBGdata));
} else {
}
}
public void showBG() {
BgReading mBgReading;
mBgReading = BgReading.last();
if (mBgReading != null) {
calculated_value = mBgReading.calculated_value;
DecimalFormat df = new DecimalFormat("#", new DecimalFormatSymbols(Locale.ENGLISH));
bgvalue = String.valueOf(df.format(calculated_value));
} else {
bgvalue = "n/a";
}
}
public void getTimestampLastreading() {
Long mTimeStampLastreading;
mTimeStampLastreading = BgReading.getTimeSinceLastReading();
if (mTimeStampLastreading != null) {
long minutesago=((mTimeStampLastreading)/1000)/60;
timestamplastreading = String.valueOf(minutesago);
} else {
timestamplastreading = "--'";
}
}
public void unitizedDeltaString() {
List<BgReading> last2 = BgReading.latest(2);
if (BgReading.latest(2) != null) {
if (last2.size() < 2 || last2.get(0).timestamp - last2.get(1).timestamp > 20 * 60 * 1000) {
// don't show delta if there are not enough values or the values are more than 20 mintes apart
deltalastreading = "???";
}
double value = BgReading.currentSlope() * 5 * 60 * 1000;
if (Math.abs(value) > 100) {
// a delta > 100 will not happen with real BG values -> problematic sensor data
deltalastreading = "ERR";
}
DecimalFormat df = new DecimalFormat("#", new DecimalFormatSymbols(Locale.ENGLISH));
String delta_sign = "";
if (value > 0) {
delta_sign = "+";
}
deltalastreading = delta_sign + df.format(value);
} else {
deltalastreading = "---";
}
}
@Override
public void onDestroy() {
mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
super.onDestroy();
}
@Override
public void onVisibilityChanged(boolean visible) {
super.onVisibilityChanged(visible);
if (visible) {
registerReceiver();
// Update time zone in case it changed while we weren't visible.
mTime.clear(TimeZone.getDefault().getID());
mTime.setToNow();
} else {
registerReceiver();
}
// Whether the timer should be running depends on whether we're visible (as well as
// whether we're in ambient mode), so we may need to start or stop the timer.
updateTimer();
}
private void unregisterReceiver() {
if (mRegisteredTimeZoneReceiver) {
mRegisteredTimeZoneReceiver = false;
wearDripWatchFace.this.unregisterReceiver(mTimeZoneReceiver);
}
if (mRegisterednewDataReceiver) {
mRegisterednewDataReceiver = false;
wearDripWatchFace.this.unregisterReceiver(newDataReceiver);
}
}
private void registerReceiver() {
if (!mRegisteredTimeZoneReceiver) {
mRegisteredTimeZoneReceiver = true;
IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED);
wearDripWatchFace.this.registerReceiver(mTimeZoneReceiver, filter);
}
if (!mRegisterednewDataReceiver) {
mRegisterednewDataReceiver = true;
IntentFilter filter = new IntentFilter(Intents.ACTION_NEW_BG_ESTIMATE_NO_DATA);
wearDripWatchFace.this.registerReceiver(newDataReceiver, filter);
}
}
@Override
public void onApplyWindowInsets(WindowInsets insets) {
super.onApplyWindowInsets(insets);
if (insets.isRound()) {
mXOffset = mYOffset = 0;
} else {
mXOffset = mYOffset = 0;
}
// Recompute the MeasureSpec fields - these determine the actual size of the layout
specW = View.MeasureSpec.makeMeasureSpec(displaySize.x, View.MeasureSpec.EXACTLY);
specH = View.MeasureSpec.makeMeasureSpec(displaySize.y, View.MeasureSpec.EXACTLY);
}
@Override
public void onPropertiesChanged(Bundle properties) {
super.onPropertiesChanged(properties);
mLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false);
}
@Override
public void onTimeTick() {
super.onTimeTick();
invalidate();
}
@Override
public void onAmbientModeChanged(boolean inAmbientMode) {
super.onAmbientModeChanged(inAmbientMode);
if (mAmbient != inAmbientMode) {
mAmbient = inAmbientMode;
// Show/hide the seconds fields
if (inAmbientMode) {
//second.setVisibility(View.GONE);
//myLayout.findViewById(R.id.chart).setVisibility(View.GONE);
} else {
//second.setVisibility(View.VISIBLE);
//myLayout.findViewById(R.id.chart).setVisibility(View.VISIBLE);
}
invalidate();
}
// Whether the timer should be running depends on whether we're visible (as well as
// whether we're in ambient mode), so we may need to start or stop the timer.
updateTimer();
}
@Override
public void onDraw(Canvas canvas, Rect bounds) {
// Get the current Time
mTime.setToNow();
delta.setText(deltalastreading);
sgv.setText(bgvalue);
watch_time.setText(String.format("%02d:%02d", mTime.hour, mTime.minute));
getTimestampLastreading();
timestamp.setText(timestamplastreading + "′");
//realmioquerry();
if (!mAmbient) {
//second.setText(String.format("%02d", mTime.second));
}
// Update the layout
myLayout.measure(specW, specH);
myLayout.layout(0, 0, myLayout.getMeasuredWidth(), myLayout.getMeasuredHeight());
// Draw it to the Canvas
canvas.drawColor(Color.BLACK);
canvas.translate(mXOffset, mYOffset);
myLayout.draw(canvas);
}
/**
* Starts the {@link #mUpdateTimeHandler} timer if it should be running and isn't currently
* or stops it if it shouldn't be running but currently is.
*/
private void updateTimer() {
mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
if (shouldTimerBeRunning()) {
mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME);
}
}
/**
* Returns whether the {@link #mUpdateTimeHandler} timer should be running. The timer should
* only run when we're visible and in interactive mode.
*/
private boolean shouldTimerBeRunning() {
return isVisible() && !isInAmbientMode();
}
@Override
public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
}
@Override
public void onNothingSelected() {
}
@Override
public void onTapCommand(
@TapType int tapType, int x, int y, long eventTime) {
switch (tapType) {
case WatchFaceService.TAP_TYPE_TAP:
break;
case WatchFaceService.TAP_TYPE_TOUCH:
break;
case WatchFaceService.TAP_TYPE_TOUCH_CANCEL:
break;
default:
super.onTapCommand(tapType, x, y, eventTime);
break;
}
}
}
}
|
set visible values for chart
|
wear/src/main/java/weardrip/weardrip/wearDripWatchFace.java
|
set visible values for chart
|
|
Java
|
mit
|
854f686c20dad13ece1f7c3988f1d5f35c27fdc3
| 0
|
Eadgyth/Java-Programming-Editor,Eadgyth/Java-Programming-Editor
|
package eg.ui.menu;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
/**
* The menu for view actions.
* <p>Created in {@link MenuBar}
*/
public class ViewMenu {
private final JMenu menu = new JMenu("View");
private final JCheckBoxMenuItem consoleItm
= new JCheckBoxMenuItem("Console");
private final JCheckBoxMenuItem fileViewItm
= new JCheckBoxMenuItem("Project explorer");
private final JCheckBoxMenuItem tabItm
= new JCheckBoxMenuItem("Files in tabs");
private final JMenuItem openSettingsItm
= new JMenuItem("Preferences");
public ViewMenu() {
assembleMenu();
}
public JMenu getMenu() {
return menu;
}
public void setConsoleItmAction(ActionListener al) {
consoleItm.addActionListener(al);
}
public void setFileViewItmAction(ActionListener al) {
fileViewItm.addActionListener(al);
}
public void setTabItmAction(ActionListener al) {
tabItm.addActionListener(al);
}
public void openSettingWinItmAction(ActionListener al) {
openSettingsItm.addActionListener(al);
}
public boolean isConsoleItmSelected() {
return consoleItm.isSelected();
}
public boolean isFileViewItmSelected() {
return fileViewItm.isSelected();
}
public boolean isTabItmSelected() {
return tabItm.isSelected();
}
public void doConsoleItmAct(boolean select) {
if (select != consoleItm.isSelected()) {
consoleItm.doClick();
}
}
public void doUnselectFileViewAct() {
if (fileViewItm.isSelected()) {
fileViewItm.doClick();
}
}
public void selectTabsItm(boolean select) {
tabItm.setSelected(select);
}
public void enableFileViewItm() {
fileViewItm.setEnabled(true);
}
public void enableTabItm(boolean isEnabled) {
tabItm.setEnabled(isEnabled);
}
private void assembleMenu() {
menu.add(consoleItm);
menu.add(fileViewItm);
menu.add(tabItm);
menu.addSeparator();
menu.add(openSettingsItm);
menu.setMnemonic(KeyEvent.VK_V);
}
}
|
src/eg/ui/menu/ViewMenu.java
|
package eg.ui.menu;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
/**
* The menu for view actions.
* <p>Created in {@link MenuBar}
*/
public class ViewMenu {
private final JMenu menu = new JMenu("View");
private final JCheckBoxMenuItem consoleItm
= new JCheckBoxMenuItem("Console");
private final JCheckBoxMenuItem fileViewItm
= new JCheckBoxMenuItem("Project explorer");
private final JCheckBoxMenuItem tabItm
= new JCheckBoxMenuItem("Files in tabs");
private final JMenuItem openSettingsItm
= new JMenuItem("Preferences");
public ViewMenu() {
assembleMenu();
}
public JMenu getMenu() {
return menu;
}
public void setConsoleItmAction(ActionListener al) {
consoleItm.addActionListener(al);
}
public void setFileViewItmAction(ActionListener al) {
fileViewItm.addActionListener(al);
}
public void setTabItmAction(ActionListener al) {
tabItm.addActionListener(al);
}
public void openSettingWinItmAction(ActionListener al) {
openSettingsItm.addActionListener(al);
}
public boolean isConsoleItmSelected() {
return consoleItm.isSelected();
}
public boolean isFileViewItmSelected() {
return fileViewItm.isSelected();
}
public boolean isTabItmSelected() {
return tabItm.isSelected();
}
public void doConsoleItmAct(boolean select) {
if (select != consoleItm.isSelected()) {
consoleItm.doClick();
}
}
public void doUnselectFileViewAct() {
if (fileViewItm.isSelected()) {
fileViewItm.doClick();
}
}
public void selectTabsItm(boolean select) {
tabItm.setSelected(select);
}
public void enableFileViewItm() {
fileViewItm.setEnabled(true);
}
public void enableTabItm(boolean isEnabled) {
tabItm.setEnabled(isEnabled);
}
private void assembleMenu() {
menu.add(consoleItm);
menu.add(fileViewItm);
menu.add(tabItm);
menu.addSeparator();
menu.add(openSettingsItm);
menu.setMnemonic(KeyEvent.VK_V);
fileViewItm.setEnabled(false);
}
}
|
allow to open project explorer
|
src/eg/ui/menu/ViewMenu.java
|
allow to open project explorer
|
|
Java
|
mit
|
277058ba51b341ad6f998931fe5f47bf0926cce0
| 0
|
promovicz/better-jsonrpc
|
package better.jsonrpc.core;
import better.jsonrpc.client.JsonRpcClient;
import better.jsonrpc.server.JsonRpcServer;
import better.jsonrpc.util.ProxyUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.log4j.Logger;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
/**
* JSON-RPC connections
*
* These objects represent a single, possibly virtual,
* connection between JSON-RPC speakers.
*
* Depending on the transport type, a connection can
* be used as an RPC server and/or client. Notifications
* may or may not be supported in either direction.
*
*/
public abstract class JsonRpcConnection {
/** Global logger, may be used by subclasses */
protected static final Logger LOG = Logger.getLogger(JsonRpcConnection.class);
/** Global counter for connection IDs */
private static final AtomicInteger sConnectionIdCounter = new AtomicInteger();
/** Automatically assign connections an ID for debugging and other purposes */
protected final int mConnectionId = sConnectionIdCounter.incrementAndGet();
/**
* Object mapper to be used for this connection
*
* Both client and server should always use this mapper for this connection.
*/
ObjectMapper mMapper;
/**
* Server instance attached to this client
*
* This object is responsible for handling requests and notifications.
*
* It will also send responses where appropriate.
*/
JsonRpcServer mServer;
/**
* Client instance attached to this client
*
* This object is responsible for handling responses.
*
* It will send requests and notifications where appropriate.
*/
JsonRpcClient mClient;
/**
* Handler instance for this client
*
* RPC calls will be dispatched to this through the server.
*/
Object mServerHandler;
/** Connection listeners */
Vector<Listener> mListeners = new Vector<Listener>();
/**
* Main constructor
*/
public JsonRpcConnection(ObjectMapper mapper) {
mMapper = mapper;
}
/**
* Get the numeric local connection ID
* @return
*/
public int getConnectionId() {
return mConnectionId;
}
/** @return the object mapper for this connection */
public ObjectMapper getMapper() {
return mMapper;
}
/** @return true if this connection has a client bound to it */
public boolean isClient() {
return mClient != null;
}
/** @return the client if there is one (throws otherwise!) */
public JsonRpcClient getClient() {
if(mClient == null) {
throw new RuntimeException("Connection not configured for client mode");
}
return mClient;
}
/** Bind the given client to this connection */
public void bindClient(JsonRpcClient client) {
if(mClient != null) {
throw new RuntimeException("Connection already has a client");
}
if(LOG.isDebugEnabled()) {
LOG.debug("[" + mConnectionId + "] binding client");
}
mClient = client;
mClient.bindConnection(this);
}
/** Create and return a client proxy */
public <T> T makeProxy(Class<T> clazz) {
return ProxyUtil.createClientProxy(clazz.getClassLoader(), clazz, this);
}
/** @return true if this connection has a server bound to it */
public boolean isServer() {
return mServer != null;
}
/** @return the server if there is one (throws otherwise!) */
public JsonRpcServer getServer() {
if(mServer == null) {
throw new RuntimeException("Connection not configured for server mode");
}
return mServer;
}
/** Bind the given server to this connection */
public void bindServer(JsonRpcServer server, Object handler) {
if(mServer != null) {
throw new RuntimeException("Connection already has a server");
}
if(LOG.isDebugEnabled()) {
LOG.debug("[" + mConnectionId + "] binding server");
}
mServer = server;
mServerHandler = handler;
}
/** Returns true if the connection is currently connected */
abstract public boolean isConnected();
/** Sends a request through the connection */
abstract public void sendRequest(ObjectNode request) throws Exception;
/** Sends a response through the connection */
abstract public void sendResponse(ObjectNode response) throws Exception;
/** Sends a notification through the connection */
abstract public void sendNotification(ObjectNode notification) throws Exception;
/** Dispatch connection open event (for subclasses to call) */
protected void onOpen() {
for(Listener l: mListeners) {
l.onOpen(this);
}
}
/** Dispatch connection close event (for subclasses to call) */
protected void onClose() {
for(Listener l: mListeners) {
l.onClose(this);
}
}
/** Dispatch an incoming request (for subclasses to call) */
protected void handleRequest(ObjectNode request) {
if(mServer != null) {
try {
mServer.handleRequest(mServerHandler, request, this);
} catch (Throwable throwable) {
LOG.error("Exception handling request", throwable);
}
}
}
/** Dispatch an incoming response (for subclasses to call) */
protected void handleResponse(ObjectNode response) {
if(mClient != null) {
try {
mClient.handleResponse(response, this);
} catch (Throwable throwable) {
LOG.error("Exception handling response", throwable);
}
}
}
/** Dispatch an incoming notification (for subclasses to call) */
protected void handleNotification(ObjectNode notification) {
if(mServer != null) {
try {
mServer.handleRequest(mServerHandler, notification, this);
} catch (Throwable throwable) {
LOG.error("Exception handling notification", throwable);
}
}
}
/** Interface of connection state listeners */
public interface Listener {
public void onOpen(JsonRpcConnection connection);
public void onClose(JsonRpcConnection connection);
}
/**
* Add a connection state listener
* @param l
*/
public void addListener(Listener l) {
mListeners.add(l);
}
/**
* Remove the given connection state listener
* @param l
*/
public void removeListener(Listener l) {
mListeners.remove(l);
}
}
|
common/src/main/java/better/jsonrpc/core/JsonRpcConnection.java
|
package better.jsonrpc.core;
import better.jsonrpc.client.JsonRpcClient;
import better.jsonrpc.server.JsonRpcServer;
import better.jsonrpc.util.ProxyUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.log4j.Logger;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
/**
* JSON-RPC connections
*
* These objects represent a single, possibly virtual,
* connection between JSON-RPC speakers.
*
* Depending on the transport type, a connection can
* be used as an RPC server and/or client. Notifications
* may or may not be supported in either direction.
*
*/
public abstract class JsonRpcConnection {
/** Global logger, may be used by subclasses */
protected static final Logger LOG = Logger.getLogger(JsonRpcConnection.class);
/** Global counter for connection IDs */
private static final AtomicInteger sConnectionIdCounter = new AtomicInteger();
/** Automatically assign connections an ID for debugging and other purposes */
protected final int mConnectionId = sConnectionIdCounter.incrementAndGet();
/**
* Object mapper to be used for this connection
*
* Both client and server should always use this mapper for this connection.
*/
ObjectMapper mMapper;
/**
* Server instance attached to this client
*
* This object is responsible for handling requests and notifications.
*
* It will also send responses where appropriate.
*/
JsonRpcServer mServer;
/**
* Client instance attached to this client
*
* This object is responsible for handling responses.
*
* It will send requests and notifications where appropriate.
*/
JsonRpcClient mClient;
/**
* Handler instance for this client
*
* RPC calls will be dispatched to this through the server.
*/
Object mServerHandler;
/** Connection listeners */
Vector<Listener> mListeners = new Vector<Listener>();
/**
* Main constructor
*/
public JsonRpcConnection(ObjectMapper mapper) {
mMapper = mapper;
}
/**
* Get the numeric local connection ID
* @return
*/
public int getConnectionId() {
return mConnectionId;
}
/** @return the object mapper for this connection */
public ObjectMapper getMapper() {
return mMapper;
}
/** @return true if this connection has a client bound to it */
public boolean isClient() {
return mClient != null;
}
/** @return the client if there is one (throws otherwise!) */
public JsonRpcClient getClient() {
if(mClient == null) {
throw new RuntimeException("Connection not configured for client mode");
}
return mClient;
}
/** Bind the given client to this connection */
public void bindClient(JsonRpcClient client) {
if(mClient != null) {
throw new RuntimeException("Connection already has a client");
}
if(LOG.isDebugEnabled()) {
LOG.debug("[" + mConnectionId + "] binding client");
}
mClient = client;
mClient.bindConnection(this);
}
/** Create and return a client proxy */
public <T> T makeProxy(Class<T> clazz) {
return ProxyUtil.createClientProxy(clazz.getClassLoader(), clazz, this);
}
/** @return true if this connection has a server bound to it */
public boolean isServer() {
return mServer != null;
}
/** @return the server if there is one (throws otherwise!) */
public JsonRpcServer getServer() {
if(mServer == null) {
throw new RuntimeException("Connection not configured for server mode");
}
return mServer;
}
/** Bind the given server to this connection */
public void bindServer(JsonRpcServer server, Object handler) {
if(mServer != null) {
throw new RuntimeException("Connection already has a server");
}
if(LOG.isDebugEnabled()) {
LOG.debug("[" + mConnectionId + "] binding server");
}
mServer = server;
mServerHandler = handler;
}
/** Returns true if the connection is currently connected */
abstract public boolean isConnected();
/** Sends a request through the connection */
abstract public void sendRequest(ObjectNode request) throws Exception;
/** Sends a response through the connection */
abstract public void sendResponse(ObjectNode response) throws Exception;
/** Sends a notification through the connection */
abstract public void sendNotification(ObjectNode notification) throws Exception;
/** Dispatch connection open event (for subclasses to call) */
protected void onOpen() {
for(Listener l: mListeners) {
l.onOpen(this);
}
}
/** Dispatch connection close event (for subclasses to call) */
protected void onClose() {
for(Listener l: mListeners) {
l.onClose(this);
}
}
/** Dispatch an incoming request (for subclasses to call) */
public void handleRequest(ObjectNode request) {
if(mServer != null) {
try {
mServer.handleRequest(mServerHandler, request, this);
} catch (Throwable throwable) {
LOG.error("Exception handling request", throwable);
}
}
}
/** Dispatch an incoming response (for subclasses to call) */
public void handleResponse(ObjectNode response) {
if(mClient != null) {
try {
mClient.handleResponse(response, this);
} catch (Throwable throwable) {
LOG.error("Exception handling response", throwable);
}
}
}
/** Dispatch an incoming notification (for subclasses to call) */
public void handleNotification(ObjectNode notification) {
if(mServer != null) {
try {
mServer.handleRequest(mServerHandler, notification, this);
} catch (Throwable throwable) {
LOG.error("Exception handling notification", throwable);
}
}
}
/** Interface of connection state listeners */
public interface Listener {
public void onOpen(JsonRpcConnection connection);
public void onClose(JsonRpcConnection connection);
}
/**
* Add a connection state listener
* @param l
*/
public void addListener(Listener l) {
mListeners.add(l);
}
/**
* Remove the given connection state listener
* @param l
*/
public void removeListener(Listener l) {
mListeners.remove(l);
}
}
|
These methods should be protected
|
common/src/main/java/better/jsonrpc/core/JsonRpcConnection.java
|
These methods should be protected
|
|
Java
|
cc0-1.0
|
340a80b4734c3f08fe2fd8762cf6ad9a41b20b26
| 0
|
HenryLoenwind/InfinityBlock
|
package info.loenwind.infinityblock.config;
import java.nio.charset.Charset;
import javax.annotation.Nonnull;
import info.loenwind.infinityblock.InfinityBlockMod;
import io.netty.buffer.ByteBuf;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
public enum Config {
// section, defaultValue, description, requiresWorldRestart, requiresGameRestart
usePlayerColors(Section.CLIENT, true, "Should rotor be colored according by the player's UUID or the channel.", false, false),
registerRecipe(Section.RECIPE, true, "Should the recipe be registered. If not, you need to add it to the game in an alternative way. (For modpack makers)",
true, true),
useIronBlocks(Section.RECIPE, false, "Should the recipe use iron blocks instead of iron ingot.", true, true),
useBlueGlass(Section.RECIPE, false, "Should the recipe use blue glass instead of uncolored glass.", true, true),
;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Nothing to see beyond this point. End of configuration values.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Nonnull
private final Section section;
@Nonnull
private final Object defaultValue;
@Nonnull
private final String description;
@Nonnull
private Object currentValue;
private final boolean requiresWorldRestart;
private final boolean requiresGameRestart;
private Config(@Nonnull final Section section, @Nonnull final Object defaultValue, @Nonnull final String description, final boolean requiresWorldRestart,
final boolean requiresGameRestart) {
this.section = section;
this.description = description;
this.currentValue = this.defaultValue = defaultValue;
this.requiresWorldRestart = requiresWorldRestart;
this.requiresGameRestart = requiresGameRestart;
}
private Config(@Nonnull final Section section, @Nonnull final Integer defaultValue, @Nonnull final String description, final boolean requiresWorldRestart,
final boolean requiresGameRestart) {
this(section, (Object) defaultValue, description, requiresWorldRestart, requiresGameRestart);
}
private Config(@Nonnull final Section section, @Nonnull final Double defaultValue, @Nonnull final String description, final boolean requiresWorldRestart,
final boolean requiresGameRestart) {
this(section, (Object) defaultValue, description, requiresWorldRestart, requiresGameRestart);
}
private Config(@Nonnull final Section section, @Nonnull final Boolean defaultValue, @Nonnull final String description, final boolean requiresWorldRestart,
final boolean requiresGameRestart) {
this(section, (Object) defaultValue, description, requiresWorldRestart, requiresGameRestart);
}
private Config(@Nonnull final Section section, @Nonnull final String defaultValue, @Nonnull final String description, final boolean requiresWorldRestart,
final boolean requiresGameRestart) {
this(section, (Object) defaultValue, description, requiresWorldRestart, requiresGameRestart);
}
private Config(@Nonnull final Section section, @Nonnull final Integer defaultValue, @Nonnull final String description) {
this(section, (Object) defaultValue, description, false, false);
}
private Config(@Nonnull final Section section, @Nonnull final Double defaultValue, @Nonnull final String description) {
this(section, (Object) defaultValue, description, false, false);
}
private Config(@Nonnull final Section section, @Nonnull final Boolean defaultValue, @Nonnull final String description) {
this(section, (Object) defaultValue, description, false, false);
}
private Config(@Nonnull final Section section, @Nonnull final String defaultValue, @Nonnull final String description) {
this(section, (Object) defaultValue, description, false, false);
}
void load(final Configuration config) {
Object value = null;
if (defaultValue instanceof Integer) {
value = setPropertyData(config.get(section.name, name(), (Integer) defaultValue, description)).getInt((Integer) defaultValue);
} else if (defaultValue instanceof Double) {
value = setPropertyData(config.get(section.name, name(), (Double) defaultValue, description)).getDouble((Double) defaultValue);
} else if (defaultValue instanceof Boolean) {
value = setPropertyData(config.get(section.name, name(), (Boolean) defaultValue, description)).getBoolean((Boolean) defaultValue);
} else if (defaultValue instanceof String) {
value = setPropertyData(config.get(section.name, name(), (String) defaultValue, description)).getString();
}
setField(value);
}
private Property setPropertyData(final Property property) {
property.setRequiresWorldRestart(requiresWorldRestart);
property.setRequiresMcRestart(requiresGameRestart);
property.setLanguageKey(InfinityBlockMod.MODID + ".config." + name());
return property;
}
private void setField(final Object value) {
if (value != null) {
currentValue = value;
}
}
void store(final ByteBuf buf) {
if (defaultValue instanceof Integer) {
buf.writeInt(getInt());
} else if (defaultValue instanceof Double) {
buf.writeDouble(getDouble());
} else if (defaultValue instanceof Boolean) {
buf.writeBoolean(getBoolean());
} else if (defaultValue instanceof String) {
final String value = getString();
final byte[] bytes = value.getBytes(Charset.forName("UTF-8"));
buf.writeInt(bytes.length);
buf.writeBytes(bytes);
}
}
void read(final ByteBuf buf) {
Object value = null;
if (defaultValue instanceof Integer) {
value = buf.readInt();
} else if (defaultValue instanceof Double) {
value = buf.readDouble();
} else if (defaultValue instanceof Boolean) {
value = buf.readBoolean();
} else if (defaultValue instanceof String) {
final int len = buf.readInt();
final byte[] bytes = new byte[len];
buf.readBytes(bytes, 0, len);
value = new String(bytes, Charset.forName("UTF-8"));
}
setField(value);
}
protected void resetToDefault() {
setField(defaultValue);
}
public Section getSection() {
return section;
}
//
private class DataTypeErrorInConfigException extends RuntimeException {
private static final long serialVersionUID = -7077690323202964355L;
}
public int getDefaultInt() {
if (defaultValue instanceof Integer) {
return (Integer) defaultValue;
} else if (defaultValue instanceof Double) {
return ((Double) defaultValue).intValue();
} else if (defaultValue instanceof Boolean) {
return (Boolean) defaultValue ? 1 : 0;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
public double getDefaultDouble() {
if (defaultValue instanceof Integer) {
return (Integer) defaultValue;
} else if (defaultValue instanceof Double) {
return (Double) defaultValue;
} else if (defaultValue instanceof Boolean) {
return (Boolean) defaultValue ? 1 : 0;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
public float getDefaultFloat() {
if (defaultValue instanceof Integer) {
return (Integer) defaultValue;
} else if (defaultValue instanceof Double) {
return ((Double) defaultValue).floatValue();
} else if (defaultValue instanceof Boolean) {
return (Boolean) defaultValue ? 1 : 0;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
public boolean getDefaultBoolean() {
if (defaultValue instanceof Integer) {
throw new DataTypeErrorInConfigException();
} else if (defaultValue instanceof Double) {
throw new DataTypeErrorInConfigException();
} else if (defaultValue instanceof Boolean) {
return (Boolean) defaultValue;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
@SuppressWarnings("null")
@Nonnull
public String getDefaultString() {
if (defaultValue instanceof Integer) {
return ((Integer) defaultValue).toString();
} else if (defaultValue instanceof Double) {
return ((Double) defaultValue).toString();
} else if (defaultValue instanceof Boolean) {
return ((Boolean) defaultValue).toString();
} else if (defaultValue instanceof String) {
return (String) defaultValue;
} else {
throw new DataTypeErrorInConfigException();
}
}
//
public int getInt() {
if (defaultValue instanceof Integer) {
return (Integer) currentValue;
} else if (defaultValue instanceof Double) {
return ((Double) currentValue).intValue();
} else if (defaultValue instanceof Boolean) {
return (Boolean) currentValue ? 1 : 0;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
public double getDouble() {
if (defaultValue instanceof Integer) {
return (Integer) currentValue;
} else if (defaultValue instanceof Double) {
return (Double) currentValue;
} else if (defaultValue instanceof Boolean) {
return (Boolean) currentValue ? 1 : 0;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
public float getFloat() {
if (defaultValue instanceof Integer) {
return (Integer) currentValue;
} else if (defaultValue instanceof Double) {
return ((Double) currentValue).floatValue();
} else if (defaultValue instanceof Boolean) {
return (Boolean) currentValue ? 1 : 0;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
public boolean getBoolean() {
if (defaultValue instanceof Integer) {
throw new DataTypeErrorInConfigException();
} else if (defaultValue instanceof Double) {
throw new DataTypeErrorInConfigException();
} else if (defaultValue instanceof Boolean) {
return (Boolean) currentValue;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
@SuppressWarnings("null")
@Nonnull
public String getString() {
if (defaultValue instanceof Integer) {
return ((Integer) currentValue).toString();
} else if (defaultValue instanceof Double) {
return ((Double) currentValue).toString();
} else if (defaultValue instanceof Boolean) {
return ((Boolean) currentValue).toString();
} else if (defaultValue instanceof String) {
return (String) currentValue;
} else {
throw new DataTypeErrorInConfigException();
}
}
}
|
src/main/java/info/loenwind/infinityblock/config/Config.java
|
package info.loenwind.infinityblock.config;
import java.nio.charset.Charset;
import javax.annotation.Nonnull;
import info.loenwind.infinityblock.InfinityBlockMod;
import io.netty.buffer.ByteBuf;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
public enum Config {
// section, defaultValue, description, requiresWorldRestart, requiresGameRestart
usePlayerColors(Section.CLIENT, true, "Should rotor be colored according by the player's UUID or the channel.", false, false),
registerRecipe(Section.RECIPE, false, "Should the recipe be registered. If not, you need to add it to the game in an alternative way. (For modpack makers)",
true, true),
useIronBlocks(Section.RECIPE, false, "Should the recipe use iron blocks instead of iron ingot.", true, true),
useBlueGlass(Section.RECIPE, false, "Should the recipe use blue glass instead of uncolored glass.", true, true),
;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Nothing to see beyond this point. End of configuration values.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Nonnull
private final Section section;
@Nonnull
private final Object defaultValue;
@Nonnull
private final String description;
@Nonnull
private Object currentValue;
private final boolean requiresWorldRestart;
private final boolean requiresGameRestart;
private Config(@Nonnull final Section section, @Nonnull final Object defaultValue, @Nonnull final String description, final boolean requiresWorldRestart,
final boolean requiresGameRestart) {
this.section = section;
this.description = description;
this.currentValue = this.defaultValue = defaultValue;
this.requiresWorldRestart = requiresWorldRestart;
this.requiresGameRestart = requiresGameRestart;
}
private Config(@Nonnull final Section section, @Nonnull final Integer defaultValue, @Nonnull final String description, final boolean requiresWorldRestart,
final boolean requiresGameRestart) {
this(section, (Object) defaultValue, description, requiresWorldRestart, requiresGameRestart);
}
private Config(@Nonnull final Section section, @Nonnull final Double defaultValue, @Nonnull final String description, final boolean requiresWorldRestart,
final boolean requiresGameRestart) {
this(section, (Object) defaultValue, description, requiresWorldRestart, requiresGameRestart);
}
private Config(@Nonnull final Section section, @Nonnull final Boolean defaultValue, @Nonnull final String description, final boolean requiresWorldRestart,
final boolean requiresGameRestart) {
this(section, (Object) defaultValue, description, requiresWorldRestart, requiresGameRestart);
}
private Config(@Nonnull final Section section, @Nonnull final String defaultValue, @Nonnull final String description, final boolean requiresWorldRestart,
final boolean requiresGameRestart) {
this(section, (Object) defaultValue, description, requiresWorldRestart, requiresGameRestart);
}
private Config(@Nonnull final Section section, @Nonnull final Integer defaultValue, @Nonnull final String description) {
this(section, (Object) defaultValue, description, false, false);
}
private Config(@Nonnull final Section section, @Nonnull final Double defaultValue, @Nonnull final String description) {
this(section, (Object) defaultValue, description, false, false);
}
private Config(@Nonnull final Section section, @Nonnull final Boolean defaultValue, @Nonnull final String description) {
this(section, (Object) defaultValue, description, false, false);
}
private Config(@Nonnull final Section section, @Nonnull final String defaultValue, @Nonnull final String description) {
this(section, (Object) defaultValue, description, false, false);
}
void load(final Configuration config) {
Object value = null;
if (defaultValue instanceof Integer) {
value = setPropertyData(config.get(section.name, name(), (Integer) defaultValue, description)).getInt((Integer) defaultValue);
} else if (defaultValue instanceof Double) {
value = setPropertyData(config.get(section.name, name(), (Double) defaultValue, description)).getDouble((Double) defaultValue);
} else if (defaultValue instanceof Boolean) {
value = setPropertyData(config.get(section.name, name(), (Boolean) defaultValue, description)).getBoolean((Boolean) defaultValue);
} else if (defaultValue instanceof String) {
value = setPropertyData(config.get(section.name, name(), (String) defaultValue, description)).getString();
}
setField(value);
}
private Property setPropertyData(final Property property) {
property.setRequiresWorldRestart(requiresWorldRestart);
property.setRequiresMcRestart(requiresGameRestart);
property.setLanguageKey(InfinityBlockMod.MODID + ".config." + name());
return property;
}
private void setField(final Object value) {
if (value != null) {
currentValue = value;
}
}
void store(final ByteBuf buf) {
if (defaultValue instanceof Integer) {
buf.writeInt(getInt());
} else if (defaultValue instanceof Double) {
buf.writeDouble(getDouble());
} else if (defaultValue instanceof Boolean) {
buf.writeBoolean(getBoolean());
} else if (defaultValue instanceof String) {
final String value = getString();
final byte[] bytes = value.getBytes(Charset.forName("UTF-8"));
buf.writeInt(bytes.length);
buf.writeBytes(bytes);
}
}
void read(final ByteBuf buf) {
Object value = null;
if (defaultValue instanceof Integer) {
value = buf.readInt();
} else if (defaultValue instanceof Double) {
value = buf.readDouble();
} else if (defaultValue instanceof Boolean) {
value = buf.readBoolean();
} else if (defaultValue instanceof String) {
final int len = buf.readInt();
final byte[] bytes = new byte[len];
buf.readBytes(bytes, 0, len);
value = new String(bytes, Charset.forName("UTF-8"));
}
setField(value);
}
protected void resetToDefault() {
setField(defaultValue);
}
public Section getSection() {
return section;
}
//
private class DataTypeErrorInConfigException extends RuntimeException {
private static final long serialVersionUID = -7077690323202964355L;
}
public int getDefaultInt() {
if (defaultValue instanceof Integer) {
return (Integer) defaultValue;
} else if (defaultValue instanceof Double) {
return ((Double) defaultValue).intValue();
} else if (defaultValue instanceof Boolean) {
return (Boolean) defaultValue ? 1 : 0;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
public double getDefaultDouble() {
if (defaultValue instanceof Integer) {
return (Integer) defaultValue;
} else if (defaultValue instanceof Double) {
return (Double) defaultValue;
} else if (defaultValue instanceof Boolean) {
return (Boolean) defaultValue ? 1 : 0;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
public float getDefaultFloat() {
if (defaultValue instanceof Integer) {
return (Integer) defaultValue;
} else if (defaultValue instanceof Double) {
return ((Double) defaultValue).floatValue();
} else if (defaultValue instanceof Boolean) {
return (Boolean) defaultValue ? 1 : 0;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
public boolean getDefaultBoolean() {
if (defaultValue instanceof Integer) {
throw new DataTypeErrorInConfigException();
} else if (defaultValue instanceof Double) {
throw new DataTypeErrorInConfigException();
} else if (defaultValue instanceof Boolean) {
return (Boolean) defaultValue;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
@SuppressWarnings("null")
@Nonnull
public String getDefaultString() {
if (defaultValue instanceof Integer) {
return ((Integer) defaultValue).toString();
} else if (defaultValue instanceof Double) {
return ((Double) defaultValue).toString();
} else if (defaultValue instanceof Boolean) {
return ((Boolean) defaultValue).toString();
} else if (defaultValue instanceof String) {
return (String) defaultValue;
} else {
throw new DataTypeErrorInConfigException();
}
}
//
public int getInt() {
if (defaultValue instanceof Integer) {
return (Integer) currentValue;
} else if (defaultValue instanceof Double) {
return ((Double) currentValue).intValue();
} else if (defaultValue instanceof Boolean) {
return (Boolean) currentValue ? 1 : 0;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
public double getDouble() {
if (defaultValue instanceof Integer) {
return (Integer) currentValue;
} else if (defaultValue instanceof Double) {
return (Double) currentValue;
} else if (defaultValue instanceof Boolean) {
return (Boolean) currentValue ? 1 : 0;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
public float getFloat() {
if (defaultValue instanceof Integer) {
return (Integer) currentValue;
} else if (defaultValue instanceof Double) {
return ((Double) currentValue).floatValue();
} else if (defaultValue instanceof Boolean) {
return (Boolean) currentValue ? 1 : 0;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
public boolean getBoolean() {
if (defaultValue instanceof Integer) {
throw new DataTypeErrorInConfigException();
} else if (defaultValue instanceof Double) {
throw new DataTypeErrorInConfigException();
} else if (defaultValue instanceof Boolean) {
return (Boolean) currentValue;
} else if (defaultValue instanceof String) {
throw new DataTypeErrorInConfigException();
} else {
throw new DataTypeErrorInConfigException();
}
}
@SuppressWarnings("null")
@Nonnull
public String getString() {
if (defaultValue instanceof Integer) {
return ((Integer) currentValue).toString();
} else if (defaultValue instanceof Double) {
return ((Double) currentValue).toString();
} else if (defaultValue instanceof Boolean) {
return ((Boolean) currentValue).toString();
} else if (defaultValue instanceof String) {
return (String) currentValue;
} else {
throw new DataTypeErrorInConfigException();
}
}
}
|
Fixed wrong config default
|
src/main/java/info/loenwind/infinityblock/config/Config.java
|
Fixed wrong config default
|
|
Java
|
mpl-2.0
|
efbff689a42fc4348091129382f9e3bc52b5066a
| 0
|
Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV
|
package org.helioviewer.jhv.view.simpleimage;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.awt.image.DataBufferUShort;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.Buffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.Iterator;
import javax.annotation.Nonnull;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.ImageInputStream;
//import org.helioviewer.jhv.base.XMLUtils;
import org.helioviewer.jhv.imagedata.ImageBuffer;
import org.helioviewer.jhv.imagedata.ImageData;
import org.helioviewer.jhv.io.APIRequest;
import org.helioviewer.jhv.io.NetClient;
import org.helioviewer.jhv.metadata.PixelBasedMetaData;
import org.helioviewer.jhv.metadata.XMLMetaDataContainer;
import org.helioviewer.jhv.view.BaseView;
public class SimpleImageView extends BaseView {
private String xml;
public SimpleImageView(URI _uri, APIRequest _request) throws Exception {
super(_uri, _request);
BufferedImage image = null;
try (NetClient nc = NetClient.of(uri); ImageInputStream iis = ImageIO.createImageInputStream(nc.getStream())) {
image = readStream(iis);
} catch (Exception e) {
e.printStackTrace();
}
if (image == null)
throw new Exception("Could not read image: " + uri);
int w = image.getWidth();
int h = image.getHeight();
Buffer buffer;
ImageBuffer.Format format;
switch (image.getType()) {
case BufferedImage.TYPE_BYTE_GRAY:
buffer = ByteBuffer.wrap(((DataBufferByte) image.getRaster().getDataBuffer()).getData());
format = ImageBuffer.Format.Gray8;
break;
case BufferedImage.TYPE_USHORT_GRAY:
buffer = ShortBuffer.wrap(((DataBufferUShort) image.getRaster().getDataBuffer()).getData());
format = ImageBuffer.Format.Gray16;
break;
case BufferedImage.TYPE_INT_ARGB_PRE:
buffer = IntBuffer.wrap(((DataBufferInt) image.getRaster().getDataBuffer()).getData());
format = ImageBuffer.Format.ARGB32;
break;
default:
BufferedImage conv = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
conv.getGraphics().drawImage(image, 0, 0, null);
buffer = IntBuffer.wrap(((DataBufferInt) conv.getRaster().getDataBuffer()).getData());
format = ImageBuffer.Format.ARGB32;
}
imageData = new ImageData(new ImageBuffer(w, h, format, buffer));
try {
metaData[0] = new XMLMetaDataContainer(xml).getHVMetaData(0, true);
} catch (Exception ignore) {
metaData[0] = new PixelBasedMetaData(w, h, 0);
xml = "<meta/>";
}
imageData.setRegion(metaData[0].getPhysicalRegion());
imageData.setMetaData(metaData[0]);
}
@Nonnull
@Override
public String getXMLMetaData() {
return xml;
}
@Override
public boolean isComplete() {
return true;
}
private BufferedImage readStream(ImageInputStream iis) throws Exception {
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
if (readers.hasNext()) {
// pick the first available ImageReader
ImageReader reader = readers.next();
// attach source to the reader
reader.setInput(iis, true);
// read metadata of first image
IIOMetadata metadata = reader.getImageMetadata(0);
IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree("javax_imageio_1.0");
Object text = root.getElementsByTagName("TextEntry").item(0);
if (text instanceof IIOMetadataNode) {
xml = ((IIOMetadataNode) text).getAttribute("value").trim().replace("&", "&");
}
/*
String[] names = metadata.getMetadataFormatNames();
int length = names.length;
for (int i = 0; i < length; i++) {
System.out.println("Format name: " + names[i]);
XMLUtils.displayNode(metadata.getAsTree(names[i]), 0);
}
*/
// read first image
return reader.read(0);
}
return null;
}
}
|
src/org/helioviewer/jhv/view/simpleimage/SimpleImageView.java
|
package org.helioviewer.jhv.view.simpleimage;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.awt.image.DataBufferUShort;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.Buffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.Iterator;
import javax.annotation.Nonnull;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.ImageInputStream;
//import org.helioviewer.jhv.base.XMLUtils;
import org.helioviewer.jhv.imagedata.ImageBuffer;
import org.helioviewer.jhv.imagedata.ImageData;
import org.helioviewer.jhv.io.APIRequest;
import org.helioviewer.jhv.io.NetClient;
import org.helioviewer.jhv.metadata.PixelBasedMetaData;
import org.helioviewer.jhv.metadata.XMLMetaDataContainer;
import org.helioviewer.jhv.view.BaseView;
public class SimpleImageView extends BaseView {
private String xml;
public SimpleImageView(URI _uri, APIRequest _request) throws Exception {
super(_uri, _request);
BufferedImage image;
try (NetClient nc = NetClient.of(uri); ImageInputStream iis = ImageIO.createImageInputStream(nc.getStream())) {
image = readImage(iis);
}
if (image == null)
throw new Exception("Could not read image: " + uri);
int w = image.getWidth();
int h = image.getHeight();
Buffer buffer;
ImageBuffer.Format format;
switch (image.getType()) {
case BufferedImage.TYPE_BYTE_GRAY:
buffer = ByteBuffer.wrap(((DataBufferByte) image.getRaster().getDataBuffer()).getData());
format = ImageBuffer.Format.Gray8;
break;
case BufferedImage.TYPE_USHORT_GRAY:
buffer = ShortBuffer.wrap(((DataBufferUShort) image.getRaster().getDataBuffer()).getData());
format = ImageBuffer.Format.Gray16;
break;
case BufferedImage.TYPE_INT_ARGB_PRE:
buffer = IntBuffer.wrap(((DataBufferInt) image.getRaster().getDataBuffer()).getData());
format = ImageBuffer.Format.ARGB32;
break;
default:
BufferedImage conv = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
conv.getGraphics().drawImage(image, 0, 0, null);
buffer = IntBuffer.wrap(((DataBufferInt) conv.getRaster().getDataBuffer()).getData());
format = ImageBuffer.Format.ARGB32;
}
imageData = new ImageData(new ImageBuffer(w, h, format, buffer));
try {
metaData[0] = new XMLMetaDataContainer(xml).getHVMetaData(0, true);
} catch (Exception ignore) {
metaData[0] = new PixelBasedMetaData(w, h, 0);
xml = "<meta/>";
}
imageData.setRegion(metaData[0].getPhysicalRegion());
imageData.setMetaData(metaData[0]);
}
@Nonnull
@Override
public String getXMLMetaData() {
return xml;
}
@Override
public boolean isComplete() {
return true;
}
private BufferedImage readImage(ImageInputStream iis) {
BufferedImage ret = null;
try {
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
if (readers.hasNext()) {
// pick the first available ImageReader
ImageReader reader = readers.next();
// attach source to the reader
reader.setInput(iis, true);
// read first image
ret = reader.read(0);
// read metadata of first image
IIOMetadata metadata = reader.getImageMetadata(0);
IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree("javax_imageio_1.0");
Object text = root.getElementsByTagName("TextEntry").item(0);
if (text instanceof IIOMetadataNode) {
xml = ((IIOMetadataNode) text).getAttribute("value").trim().replace("&", "&");
}
/*
String[] names = metadata.getMetadataFormatNames();
int length = names.length;
for (int i = 0; i < length; i++) {
System.out.println("Format name: " + names[i]);
XMLUtils.displayNode(metadata.getAsTree(names[i]), 0);
}
*/
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
}
|
Reduce
|
src/org/helioviewer/jhv/view/simpleimage/SimpleImageView.java
|
Reduce
|
|
Java
|
mpl-2.0
|
be4d103005501aec48da151aec181b9ff046a65c
| 0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
/*************************************************************************
*
* $RCSfile: CommandMetaData.java,v $
*
* $Revision: 1.4 $
*
* last change: $Author: pjunck $ $Date: 2004-10-27 13:29:47 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*/
package com.sun.star.wizards.db;
import com.sun.star.wizards.common.Properties;
import com.sun.star.wizards.common.*;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.IndexOutOfBoundsException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.sdbcx.KeyType;
import com.sun.star.sdbcx.XColumnsSupplier;
import com.sun.star.sdbcx.XKeysSupplier;
import com.sun.star.uno.AnyConverter;
import com.sun.star.beans.*;
import com.sun.star.uno.UnoRuntime;
import java.util.*;
import com.sun.star.lang.Locale;
import com.sun.star.util.XNumberFormats;
import com.sun.star.beans.PropertyValue;
import com.sun.star.container.XIndexAccess;
import com.sun.star.embed.EntryInitModes;
import com.sun.star.frame.*;
public class CommandMetaData extends DBMetaData {
public Map FieldTitleSet;
public String[] AllFieldNames;
public FieldColumn[] DBFieldColumns;
public String[] FieldNames = new String[] {};
public String[] GroupFieldNames = new String[] {};
public String[][] SortFieldNames = new String[][] {};
public String[] RecordFieldNames = new String[] {};
public String[][] AggregateFieldNames = new String[][] {};
public String[] NumericFieldNames = new String[] {};
public String[] NonAggregateFieldNames;
public int[] FieldTypes;
private int CommandType;
private String Command;
private XIndexAccess xIndexKeys;
public CommandMetaData(XMultiServiceFactory xMSF, Locale CharLocale, XNumberFormats NumberFormats) {
super(xMSF, CharLocale, NumberFormats);
}
public CommandMetaData(XMultiServiceFactory xMSF) {
super(xMSF);
}
public void setFieldColumns(boolean _bgetDefaultValue) {
DBFieldColumns = new FieldColumn[FieldNames.length];
for (int i = 0; i < FieldNames.length; i++) {
DBFieldColumns[i] = new FieldColumn(this, FieldNames[i]);
if (_bgetDefaultValue)
DBFieldColumns[i].getDefaultValue();
}
}
public XPropertySet getColumnObjectByFieldName(String _FieldColumnName) {
try {
FieldColumn CurFieldColumn = getFieldColumnByDisplayName(_FieldColumnName);
String CurCommandName = CurFieldColumn.getCommandName();
CommandObject oCommand = getTableByName(CurCommandName);
Object oColumn = oCommand.xColumns.getByName(CurFieldColumn.FieldName);
XPropertySet xColumn = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oColumn);
return xColumn;
} catch (Exception exception) {
exception.printStackTrace(System.out);
return null;
}
}
public FieldColumn getFieldColumn(String _ColumnName) {
for (int i = 0; i < FieldNames.length; i++) {
if (DBFieldColumns[i].FieldName.equals(_ColumnName))
return DBFieldColumns[i];
}
throw new com.sun.star.uno.RuntimeException();
}
public FieldColumn getFieldColumnByDisplayName(String _DisplayName) {
for (int i = 0; i < FieldNames.length; i++) {
if (DBFieldColumns[i].DisplayFieldName.equals(_DisplayName))
return DBFieldColumns[i];
}
throw new com.sun.star.uno.RuntimeException();
}
public void setFieldNames(String[] _FieldNames) {
this.FieldNames = _FieldNames;
}
public void getFieldNamesOfCommand(String _commandname, int _commandtype, boolean _bAppendMode) {
try {
Object oField;
java.util.Vector ResultFieldNames = new java.util.Vector(10);
String[] FieldNames;
CommandObject oCommand = this.getCommandByName(_commandname, _commandtype);
FieldNames = oCommand.xColumns.getElementNames();
if (FieldNames.length > 0) {
for (int n = 0; n < FieldNames.length; n++) {
oField = oCommand.xColumns.getByName(FieldNames[n]);
int iType = AnyConverter.toInt(Helper.getUnoPropertyValue(oField, "Type"));
// BinaryFieldTypes are not included in the WidthList
if (JavaTools.FieldInIntTable(WidthList, iType) >= 0) {
if (_bAppendMode)
ResultFieldNames.addElement(_commandname + "." + FieldNames[n]);
else
ResultFieldNames.addElement(FieldNames[n]);
}
}
FieldNames = new String[FieldNames.length];
FieldTypes = new int[FieldNames.length];
AllFieldNames = new String[ResultFieldNames.size()];
ResultFieldNames.copyInto(AllFieldNames);
}
} catch (Exception exception) {
exception.printStackTrace(System.out);
}
}
/**
* @return Returns the command.
*/
public String getCommand() {
return Command;
}
/**
* @param command The command to set.
*/
public void setCommand(String _command) {
Command = _command;
}
/**
* @return Returns the commandType.
*/
public int getCommandType() {
return CommandType;
}
/**
* @param commandType The commandType to set.
*/
public void setCommandType(int _commandType) {
CommandType = _commandType;
}
public boolean hasNumericalFields() {
return hasNumericalFields(FieldNames);
}
public boolean isnumeric(String _DisplayFieldName) {
try {
String CurCommandName = FieldColumn.getCommandName(_DisplayFieldName);
String CurFieldName = FieldColumn.getFieldName(_DisplayFieldName);
CommandObject oTable = super.getTableByName(CurCommandName);
Object oField = oTable.xColumns.getByName(CurFieldName);
int iType = AnyConverter.toInt(Helper.getUnoPropertyValue(oField, "Type"));
int ifound = java.util.Arrays.binarySearch(NumericTypes, iType);
if ((ifound < NumericTypes.length) && (ifound > 0))
return (NumericTypes[ifound] == iType);
else
return false;
} catch (Exception exception) {
exception.printStackTrace(System.out);
return false;
}
}
public String[] setNumericFields() {
try {
Vector numericfieldsvector = new java.util.Vector();
for (int i = 0; i < FieldNames.length; i++) {
if (isnumeric(FieldNames[i]))
numericfieldsvector.addElement(FieldNames[i]);
}
NumericFieldNames = new String[numericfieldsvector.size()];
numericfieldsvector.toArray(NumericFieldNames);
return NumericFieldNames;
} catch (Exception exception) {
exception.printStackTrace(System.out);
return new String[] {
};
}
}
public String[] setNonAggregateFieldNames(){
try {
Vector nonaggregatefieldsvector = new java.util.Vector();
for (int i = 0; i < FieldNames.length; i++) {
if (JavaTools.FieldInTable(AggregateFieldNames, FieldNames[i]) == -1)
nonaggregatefieldsvector.addElement(FieldNames[i]);
}
NonAggregateFieldNames = new String[nonaggregatefieldsvector.size()];
nonaggregatefieldsvector.toArray(NonAggregateFieldNames);
return NonAggregateFieldNames;
} catch (Exception exception) {
exception.printStackTrace(System.out);
return new String[] {
};
}
}
/**
* the fieldnames passed over are not necessarily the ones that are defined in the class
* @param FieldNames
* @return
*/
public boolean hasNumericalFields(String[] _DisplayFieldNames) {
if (_DisplayFieldNames != null) {
if (_DisplayFieldNames.length > 0) {
for (int i = 0; i < _DisplayFieldNames.length; i++)
if (isnumeric(_DisplayFieldNames[i]))
return true;
}
}
return false;
}
public String getFieldTitle(String FieldName) {
String FieldTitle = FieldName;
int TitleIndex = JavaTools.FieldInList(FieldNames, FieldName);
if (this.FieldTitleSet != null){
FieldTitle = (String) this.FieldTitleSet.get(FieldName); //FieldTitles[TitleIndex];
if (FieldTitle == null)
return FieldName;
}
return FieldTitle;
}
public void setGroupFieldNames(String[] GroupFieldNames) {
this.GroupFieldNames = GroupFieldNames;
}
public String[] getGroupFieldNames() {
return GroupFieldNames;
}
public void setRecordFieldNames() {
String CurFieldName;
int GroupFieldCount;
int TotFieldCount = FieldNames.length;
// int SortFieldCount = SortFieldNames[0].length;
GroupFieldCount = JavaTools.getArraylength(GroupFieldNames);
RecordFieldNames = new String[TotFieldCount - GroupFieldCount];
int a = 0;
for (int i = 0; i < TotFieldCount; i++) {
CurFieldName = FieldNames[i];
if (JavaTools.FieldInList(GroupFieldNames, CurFieldName) < 0) {
RecordFieldNames[a] = CurFieldName;
a += 1;
}
}
}
public void switchtoDesignmode(String _commandname, int _commandtype) {
PropertyValue[] rDispatchArguments = new PropertyValue[5];
rDispatchArguments[0] = Properties.createProperty("DataSourceName", this.DataSourceName);
rDispatchArguments[1] = Properties.createProperty("QueryDesignView", Boolean.TRUE);
rDispatchArguments[2] = Properties.createProperty("CreateView", Boolean.FALSE);
rDispatchArguments[3] = Properties.createProperty("ActiveConnection", this.DBConnection);
if (_commandtype == com.sun.star.sdb.CommandType.QUERY) {
rDispatchArguments[4] = Properties.createProperty("CurrentQuery", _commandname);
showCommandView(".component:DB/QueryDesign", rDispatchArguments);
} else {
rDispatchArguments[4] = Properties.createProperty("CurrentTable", _commandname);
showCommandView(".component:DB/TableDesign", rDispatchArguments);
}
}
public void switchtoDataViewmode(String _commandname, int _commandtype) {
PropertyValue[] rDispatchArguments = new PropertyValue[7];
rDispatchArguments[0] = Properties.createProperty("DataSourceName", this.DataSourceName);
rDispatchArguments[1] = Properties.createProperty("ActiveConnection", this.DBConnection);
rDispatchArguments[2] = Properties.createProperty("Command", _commandname);
rDispatchArguments[3] = Properties.createProperty("CommandType", new Integer(_commandtype));
rDispatchArguments[4] = Properties.createProperty("ShowTreeView", Boolean.FALSE);
rDispatchArguments[5] = Properties.createProperty("ShowTreeViewButton", Boolean.FALSE);
rDispatchArguments[6] = Properties.createProperty("ShowMenu", Boolean.TRUE);
showCommandView(".component:DB/DataSourceBrowser", rDispatchArguments);
}
//
public void showCommandView(String surl, PropertyValue[] _rArgs) {
try {
XDesktop xDesktop = Desktop.getDesktop(xMSF);
XComponentLoader xLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, xDesktop);
xLoader.loadComponentFromURL(surl, "_default", FrameSearchFlag.TASKS | FrameSearchFlag.CREATE, _rArgs);
//TODO ".component:DB/TableDesign"
} catch (Exception exception) {
exception.printStackTrace(System.out);
}
}
public String[] getReferencedTables(String _stablename, int _ncommandtype){
String[] sTotReferencedTables = new String[]{};
try {
if (_ncommandtype == com.sun.star.sdb.CommandType.TABLE){
if (xDBMetaData.supportsIntegrityEnhancementFacility()){
java.util.Vector TableVector = new java.util.Vector();
Object oTable = xTableNames.getByName(_stablename);
XKeysSupplier xKeysSupplier = (XKeysSupplier) UnoRuntime.queryInterface(XKeysSupplier.class, oTable);
xIndexKeys = xKeysSupplier.getKeys();
for (int i = 0; i < xIndexKeys.getCount(); i++){
XPropertySet xPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xIndexKeys.getByIndex(i) );
int curtype = AnyConverter.toInt(xPropertySet.getPropertyValue("Type"));
if (curtype == KeyType.FOREIGN){
String sreftablename = AnyConverter.toString(xPropertySet.getPropertyValue("ReferencedTable"));
if (xTableNames.hasByName(sreftablename))
TableVector.addElement(sreftablename);
}
}
if (TableVector.size() > 0){
sTotReferencedTables = new String[TableVector.size()];
TableVector.copyInto(sTotReferencedTables);
}
}
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
return sTotReferencedTables;
}
public String[][] getKeyColumns(String _sreferencedtablename){
String[][] skeycolumnnames = null;
try {
for (int i = 0; i < xIndexKeys.getCount(); i++){
XPropertySet xPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xIndexKeys.getByIndex(i) );
int curtype = AnyConverter.toInt(xPropertySet.getPropertyValue("Type"));
if (curtype == KeyType.FOREIGN){
String scurreftablename = AnyConverter.toString(xPropertySet.getPropertyValue("ReferencedTable"));
if (xTableNames.hasByName(scurreftablename)){
if (scurreftablename.equals(_sreferencedtablename)){
XColumnsSupplier xColumnsSupplier = (XColumnsSupplier) UnoRuntime.queryInterface(XColumnsSupplier.class, xPropertySet);
String[] smastercolnames = xColumnsSupplier.getColumns().getElementNames();
skeycolumnnames = new String[2][smastercolnames.length];
skeycolumnnames[1] = smastercolnames;
skeycolumnnames[0] = new String[smastercolnames.length];
for (int n = 0; n < smastercolnames.length; n++){
XPropertySet xcolPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xColumnsSupplier.getColumns().getByName(smastercolnames[n]));
skeycolumnnames[0][n] = AnyConverter.toString(xcolPropertySet.getPropertyValue("RelatedColumn"));
}
return skeycolumnnames;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return skeycolumnnames;
}
public void openFormDocument(boolean _bReadOnly){
try {
Object oEmbeddedFactory = super.xMSF.createInstance("com.sun.star.embed.OOoEmbeddedObjectFactory");
int iEntryInitMode = EntryInitModes.DEFAULT_INIT; //TRUNCATE_INIT???
} catch (Exception e) {
e.printStackTrace(System.out);
}}
}
|
wizards/com/sun/star/wizards/db/CommandMetaData.java
|
/*************************************************************************
*
* $RCSfile: CommandMetaData.java,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2004-08-02 17:19:19 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*/
package com.sun.star.wizards.db;
import com.sun.star.wizards.common.Properties;
import com.sun.star.wizards.common.*;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.AnyConverter;
import com.sun.star.beans.*;
import com.sun.star.uno.UnoRuntime;
import java.util.*;
import com.sun.star.lang.Locale;
import com.sun.star.util.XNumberFormats;
import com.sun.star.beans.PropertyValue;
import com.sun.star.frame.*;
public class CommandMetaData extends DBMetaData {
public Map FieldTitleSet;
public String[] AllFieldNames;
public FieldColumn[] DBFieldColumns;
public String[] FieldNames = new String[] {};
public String[] GroupFieldNames = new String[] {};
public String[][] SortFieldNames = new String[][] {};
public String[] RecordFieldNames = new String[] {};
public String[][] AggregateFieldNames = new String[][] {};
public String[] NumericFieldNames = new String[] {};
public String[] NonAggregateFieldNames;
public int[] FieldTypes;
public int CommandType;
public CommandMetaData(XMultiServiceFactory xMSF, Locale CharLocale, XNumberFormats NumberFormats) {
super(xMSF, CharLocale, NumberFormats);
}
public CommandMetaData(XMultiServiceFactory xMSF) {
super(xMSF);
}
public void setFieldColumns(boolean _bgetDefaultValue) {
DBFieldColumns = new FieldColumn[FieldNames.length];
for (int i = 0; i < FieldNames.length; i++) {
DBFieldColumns[i] = new FieldColumn(this, FieldNames[i]);
if (_bgetDefaultValue)
DBFieldColumns[i].getDefaultValue();
}
}
public XPropertySet getColumnObjectByFieldName(String _FieldColumnName) {
try {
FieldColumn CurFieldColumn = getFieldColumnByDisplayName(_FieldColumnName);
String CurCommandName = CurFieldColumn.getCommandName();
CommandObject oCommand = getTableByName(CurCommandName);
Object oColumn = oCommand.xColumns.getByName(CurFieldColumn.FieldName);
XPropertySet xColumn = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oColumn);
return xColumn;
} catch (Exception exception) {
exception.printStackTrace(System.out);
return null;
}
}
public FieldColumn getFieldColumn(String _ColumnName) {
for (int i = 0; i < FieldNames.length; i++) {
if (DBFieldColumns[i].FieldName.equals(_ColumnName))
return DBFieldColumns[i];
}
throw new com.sun.star.uno.RuntimeException();
}
public FieldColumn getFieldColumnByDisplayName(String _DisplayName) {
for (int i = 0; i < FieldNames.length; i++) {
if (DBFieldColumns[i].DisplayFieldName.equals(_DisplayName))
return DBFieldColumns[i];
}
throw new com.sun.star.uno.RuntimeException();
}
public void setFieldNames(String[] _FieldNames) {
this.FieldNames = _FieldNames;
}
public void getFieldNamesOfCommand(String _commandname, int _commandtype) {
try {
Object oField;
java.util.Vector ResultFieldNames = new java.util.Vector(10);
String[] FieldNames;
CommandObject oCommand = this.getCommandByName(_commandname, _commandtype);
FieldNames = oCommand.xColumns.getElementNames();
java.util.Arrays.sort(FieldNames);
if (FieldNames.length > 0) {
for (int n = 0; n < FieldNames.length; n++) {
oField = oCommand.xColumns.getByName(FieldNames[n]);
int iType = AnyConverter.toInt(Helper.getUnoPropertyValue(oField, "Type"));
// BinaryFieldTypes are not included in the WidthList
if (JavaTools.FieldInIntTable(WidthList, iType) >= 0) {
ResultFieldNames.addElement(_commandname + "." + FieldNames[n]);
}
}
FieldNames = new String[FieldNames.length];
FieldTypes = new int[FieldNames.length];
AllFieldNames = new String[ResultFieldNames.size()];
ResultFieldNames.copyInto(AllFieldNames);
}
} catch (Exception exception) {
exception.printStackTrace(System.out);
}
}
public boolean hasNumericalFields() {
return hasNumericalFields(FieldNames);
}
public boolean isnumeric(String _DisplayFieldName) {
try {
String CurCommandName = FieldColumn.getCommandName(_DisplayFieldName);
String CurFieldName = FieldColumn.getFieldName(_DisplayFieldName);
CommandObject oTable = super.getTableByName(CurCommandName);
Object oField = oTable.xColumns.getByName(CurFieldName);
int iType = AnyConverter.toInt(Helper.getUnoPropertyValue(oField, "Type"));
int ifound = java.util.Arrays.binarySearch(NumericTypes, iType);
if ((ifound < NumericTypes.length) && (ifound > 0))
return (NumericTypes[ifound] == iType);
else
return false;
} catch (Exception exception) {
exception.printStackTrace(System.out);
return false;
}
}
public String[] setNumericFields() {
try {
Vector numericfieldsvector = new java.util.Vector();
for (int i = 0; i < FieldNames.length; i++) {
if (isnumeric(FieldNames[i]))
numericfieldsvector.addElement(FieldNames[i]);
}
NumericFieldNames = new String[numericfieldsvector.size()];
numericfieldsvector.toArray(NumericFieldNames);
return NumericFieldNames;
} catch (Exception exception) {
exception.printStackTrace(System.out);
return new String[] {
};
}
}
public String[] setNonAggregateFieldNames(){
try {
Vector nonaggregatefieldsvector = new java.util.Vector();
for (int i = 0; i < FieldNames.length; i++) {
if (JavaTools.FieldInTable(AggregateFieldNames, FieldNames[i]) == -1)
nonaggregatefieldsvector.addElement(FieldNames[i]);
}
NonAggregateFieldNames = new String[nonaggregatefieldsvector.size()];
nonaggregatefieldsvector.toArray(NonAggregateFieldNames);
return NonAggregateFieldNames;
} catch (Exception exception) {
exception.printStackTrace(System.out);
return new String[] {
};
}
}
/**
* the fieldnames passed over are not necessarily the ones that are defined in the class
* @param FieldNames
* @return
*/
public boolean hasNumericalFields(String[] _DisplayFieldNames) {
if (_DisplayFieldNames != null) {
if (_DisplayFieldNames.length > 0) {
for (int i = 0; i < _DisplayFieldNames.length; i++)
if (isnumeric(_DisplayFieldNames[i]))
return true;
}
}
return false;
}
public String getFieldTitle(String FieldName) {
String FieldTitle = FieldName;
int TitleIndex = JavaTools.FieldInList(FieldNames, FieldName);
if (this.FieldTitleSet != null){
FieldTitle = (String) this.FieldTitleSet.get(FieldName); //FieldTitles[TitleIndex];
if (FieldTitle == null)
return FieldName;
}
return FieldTitle;
}
public void setGroupFieldNames(String[] GroupFieldNames) {
this.GroupFieldNames = GroupFieldNames;
}
public String[] getGroupFieldNames() {
return GroupFieldNames;
}
public void setRecordFieldNames() {
String CurFieldName;
int GroupFieldCount;
int TotFieldCount = FieldNames.length;
// int SortFieldCount = SortFieldNames[0].length;
GroupFieldCount = JavaTools.getArraylength(GroupFieldNames);
RecordFieldNames = new String[TotFieldCount - GroupFieldCount];
int a = 0;
for (int i = 0; i < TotFieldCount; i++) {
CurFieldName = FieldNames[i];
if (JavaTools.FieldInList(GroupFieldNames, CurFieldName) < 0) {
RecordFieldNames[a] = CurFieldName;
a += 1;
}
}
}
public void switchtoDesignmode(String _commandname, int _commandtype) {
PropertyValue[] rDispatchArguments = new PropertyValue[5];
rDispatchArguments[0] = Properties.createProperty("DataSourceName", this.DataSourceName);
rDispatchArguments[1] = Properties.createProperty("QueryDesignView", Boolean.TRUE);
rDispatchArguments[2] = Properties.createProperty("CreateView", Boolean.FALSE);
rDispatchArguments[3] = Properties.createProperty("ActiveConnection", this.DBConnection);
if (_commandtype == com.sun.star.sdb.CommandType.QUERY) {
rDispatchArguments[4] = Properties.createProperty("CurrentQuery", _commandname);
showCommandView(".component:DB/QueryDesign", rDispatchArguments);
} else {
rDispatchArguments[4] = Properties.createProperty("CurrentTable", _commandname);
showCommandView(".component:DB/TableDesign", rDispatchArguments);
}
}
public void switchtoDataViewmode(String _commandname, int _commandtype) {
PropertyValue[] rDispatchArguments = new PropertyValue[7];
rDispatchArguments[0] = Properties.createProperty("DataSourceName", this.DataSourceName);
rDispatchArguments[1] = Properties.createProperty("ActiveConnection", this.DBConnection);
rDispatchArguments[2] = Properties.createProperty("Command", _commandname);
rDispatchArguments[3] = Properties.createProperty("CommandType", new Integer(_commandtype));
rDispatchArguments[4] = Properties.createProperty("ShowTreeView", Boolean.FALSE);
rDispatchArguments[5] = Properties.createProperty("ShowTreeViewButton", Boolean.FALSE);
rDispatchArguments[6] = Properties.createProperty("ShowMenu", Boolean.TRUE);
showCommandView(".component:DB/DataSourceBrowser", rDispatchArguments);
}
//
public void showCommandView(String surl, PropertyValue[] _rArgs) {
try {
XDesktop xDesktop = Desktop.getDesktop(xMSF);
XComponentLoader xLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, xDesktop);
xLoader.loadComponentFromURL(surl, "_default", FrameSearchFlag.TASKS | FrameSearchFlag.CREATE, _rArgs);
//TODO ".component:DB/TableDesign"
} catch (Exception exception) {
exception.printStackTrace(System.out);
}
}
}
|
INTEGRATION: CWS dbwizard1 (1.3.4); FILE MERGED
2004/10/01 12:38:58 bc 1.3.4.5: ## several changes in dbwizards
2004/09/07 10:12:24 bc 1.3.4.4: ##several changes for the reportwizard
2004/09/01 14:50:46 bc 1.3.4.3: ##several changes
2004/09/01 10:35:55 bc 1.3.4.2: ## several changes
2004/08/19 16:49:19 bc 1.3.4.1: #i20423#several additions for TableWizard and FormWizard
|
wizards/com/sun/star/wizards/db/CommandMetaData.java
|
INTEGRATION: CWS dbwizard1 (1.3.4); FILE MERGED 2004/10/01 12:38:58 bc 1.3.4.5: ## several changes in dbwizards 2004/09/07 10:12:24 bc 1.3.4.4: ##several changes for the reportwizard 2004/09/01 14:50:46 bc 1.3.4.3: ##several changes 2004/09/01 10:35:55 bc 1.3.4.2: ## several changes 2004/08/19 16:49:19 bc 1.3.4.1: #i20423#several additions for TableWizard and FormWizard
|
|
Java
|
mpl-2.0
|
b6a879e52c01d8d88e89790c196f88449bd85546
| 0
|
CrafterKina/Pipes
|
package jp.crafterkina.pipes.common.block;
import jp.crafterkina.pipes.api.pipe.IStrategy;
import jp.crafterkina.pipes.common.block.entity.TileEntityPipe;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemDye;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import static jp.crafterkina.pipes.api.PipesConstants.MOD_ID;
/**
* Created by Kina on 2016/12/14.
*/
public class BlockPipe extends BlockContainer{
public static final PropertyBool[] CONNECT = Arrays.stream(EnumFacing.VALUES).map(f -> PropertyBool.create("c_" + f.getName())).toArray(PropertyBool[]::new);
public static final PropertyBool COVERED = PropertyBool.create("covered");
private static final AxisAlignedBB CORE = new AxisAlignedBB(5.5 / 16d, 5.5 / 16d, 5.5 / 16d, 10.5 / 16d, 10.5 / 16d, 10.5 / 16d);
private static final AxisAlignedBB[] PIPE = {new AxisAlignedBB(6 / 16d, 0d, 6 / 16d, 10 / 16d, 5.5 / 16d, 10 / 16d), new AxisAlignedBB(6 / 16d, 10.5 / 16d, 6 / 16d, 10 / 16d, 1d, 10 / 16d), new AxisAlignedBB(6 / 16d, 6 / 16d, 0d, 10 / 16d, 10 / 16d, 5.5 / 16d), new AxisAlignedBB(6 / 16d, 6 / 16d, 10.5 / 16d, 10 / 16d, 10 / 16d, 1d), new AxisAlignedBB(0d, 6 / 16d, 6 / 16d, 5.5 / 16d, 10 / 16d, 10 / 16d), new AxisAlignedBB(10.5 / 16d, 6 / 16d, 6 / 16d, 1d, 6 / 16d, 6 / 16d)};
@SuppressWarnings("deprecation")
public BlockPipe(){
super(Material.GLASS);
setUnlocalizedName(MOD_ID + ".pipe");
setCreativeTab(CreativeTabs.TRANSPORTATION);
setHardness(0.2f);
setResistance(0.1f);
IBlockState state = getBlockState().getBaseState();
for(EnumFacing f : EnumFacing.VALUES){
state = state.withProperty(CONNECT[f.getIndex()], false);
}
state = state.withProperty(COVERED, false);
setDefaultState(state);
}
public static int getColor(IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex){
if(worldIn == null || pos == null) return 0xFFFFFF;
TileEntity te = worldIn.getTileEntity(pos);
if(!(te instanceof TileEntityPipe)) return 0xFFFFFF;
TileEntityPipe pipe = (TileEntityPipe) te;
return tintIndex == 0 ? 0x9F844D : pipe.coverColor;
}
@Override
public void getSubBlocks(@Nonnull Item itemIn, @Nonnull CreativeTabs tab, @Nonnull NonNullList<ItemStack> subItems){
ItemStack stack = new ItemStack(itemIn);
NBTTagCompound compound = new NBTTagCompound();
{
stack.setTagCompound(compound);
compound.setBoolean("covered", false);
subItems.add(stack);
}
for(EnumDyeColor color : EnumDyeColor.values()){
stack = new ItemStack(itemIn);
compound = new NBTTagCompound();
{
stack.setTagCompound(compound);
compound.setBoolean("covered", true);
compound.setInteger("color", ItemDye.DYE_COLORS[color.getDyeDamage()]);
}
subItems.add(stack);
}
}
@Override
public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack){
NBTTagCompound compound = stack.getTagCompound();
if(compound == null) compound = new NBTTagCompound();
TileEntity te = worldIn.getTileEntity(pos);
if(!(te instanceof TileEntityPipe)) return;
TileEntityPipe pipe = (TileEntityPipe) te;
pipe.coverColor = compound.getBoolean("covered") ? compound.getInteger("color") : -1;
worldIn.notifyBlockUpdate(pos, state, state, 8);
}
@Override
@SuppressWarnings("deprecation")
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ){
if(playerIn.getHeldItem(hand).isEmpty()){
TileEntity te = worldIn.getTileEntity(pos);
if(te == null || !te.hasCapability(IStrategy.IStrategyHandler.CAPABILITY, facing)) return false;
IStrategy.IStrategyHandler handler = te.getCapability(IStrategy.IStrategyHandler.CAPABILITY, facing);
assert handler != null;
ItemStack removed = handler.remove();
Block.spawnAsEntity(worldIn, pos, removed);
worldIn.notifyBlockUpdate(pos, worldIn.getBlockState(pos), getActualState(worldIn.getBlockState(pos), worldIn, pos), 8);
}
return super.onBlockActivated(worldIn, pos, state, playerIn, hand, facing, hitX, hitY, hitZ);
}
@Override
public void breakBlock(World worldIn, @Nonnull BlockPos pos, @Nonnull IBlockState state){
TileEntity tileentity = worldIn.getTileEntity(pos);
if(tileentity instanceof TileEntityPipe){
TileEntityPipe pipe = (TileEntityPipe) tileentity;
pipe.dropItems();
worldIn.updateComparatorOutputLevel(pos, this);
}
super.breakBlock(worldIn, pos, state);
}
@Override
@SuppressWarnings("deprecation")
public boolean hasComparatorInputOverride(IBlockState state){
return true;
}
@Override
@SuppressWarnings("deprecation")
public int getComparatorInputOverride(IBlockState blockState, World worldIn, BlockPos pos){
TileEntity te = worldIn.getTileEntity(pos);
if(!(te instanceof TileEntityPipe)) return 0;
TileEntityPipe pipe = (TileEntityPipe) te;
return pipe.getComparatorPower();
}
@Override
@SuppressWarnings("deprecation")
public int getWeakPower(IBlockState blockState, IBlockAccess worldIn, BlockPos pos, EnumFacing side){
TileEntity te = worldIn.getTileEntity(pos);
if(!(te instanceof TileEntityPipe)) return 0;
TileEntityPipe pipe = (TileEntityPipe) te;
return pipe.getWeakPower(side);
}
@Override
@SuppressWarnings("deprecation")
public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos){
TileEntity te = worldIn.getTileEntity(pos);
if(!(te instanceof TileEntityPipe)) return;
TileEntityPipe pipe = (TileEntityPipe) te;
pipe.onRedstonePowered(worldIn.isBlockIndirectlyGettingPowered(pos));
}
@Nullable
@Override
public TileEntity createNewTileEntity(@Nonnull World worldIn, int meta){
return new TileEntityPipe();
}
@Nonnull
@Override
@Deprecated
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos){
return CORE;
}
@Nullable
@Override
@Deprecated
public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, @Nonnull IBlockAccess worldIn, @Nonnull BlockPos pos){
return CORE;
}
@Nonnull
@Override
@Deprecated
public AxisAlignedBB getSelectedBoundingBox(IBlockState state, @Nonnull World worldIn, @Nonnull BlockPos pos){
return CORE;
}
@Override
@SuppressWarnings("deprecation")
@Deprecated
public void addCollisionBoxToList(IBlockState stateIn, @Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull AxisAlignedBB entityBox, @Nonnull List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn){
addCollisionBoxToList(pos, entityBox, collidingBoxes, CORE);
Arrays.stream(EnumFacing.VALUES).filter(f -> worldIn.getBlockState(pos).getBlock().getActualState(stateIn, worldIn, pos).getValue(CONNECT[f.getIndex()])).forEach(f -> addCollisionBoxToList(pos, entityBox, collidingBoxes, PIPE[f.getIndex()]));
}
@Nullable
@Override
@SuppressWarnings("deprecation")
@Deprecated
public RayTraceResult collisionRayTrace(IBlockState state, @Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull Vec3d start, @Nonnull Vec3d end){
return Arrays.stream(EnumFacing.VALUES).filter(f -> worldIn.getBlockState(pos).getBlock().getActualState(state, worldIn, pos).getValue(CONNECT[f.getIndex()])).map(f -> rayTrace(pos, start, end, PIPE[f.getIndex()])).filter(Objects::nonNull).filter(r -> r.typeOfHit != RayTraceResult.Type.MISS).findFirst().orElseGet(() -> rayTrace(pos, start, end, CORE));
}
@Override
@Deprecated
public boolean isOpaqueCube(IBlockState state){
return false;
}
@Override
@Deprecated
public boolean isFullCube(IBlockState state){
return false;
}
@Override
@Deprecated
@SideOnly(Side.CLIENT)
public boolean shouldSideBeRendered(IBlockState blockState, @Nonnull IBlockAccess blockAccess, @Nonnull BlockPos pos, EnumFacing side){
return true;
}
@Override
@Nonnull
@SideOnly(Side.CLIENT)
public BlockRenderLayer getBlockLayer(){
return BlockRenderLayer.CUTOUT_MIPPED;
}
@Nonnull
@Override
public EnumBlockRenderType getRenderType(IBlockState state){
return EnumBlockRenderType.MODEL;
}
@SuppressWarnings("DeprecatedIsStillUsed")
@Nonnull
@Override
@Deprecated
public IBlockState getActualState(@Nonnull IBlockState state, IBlockAccess worldIn, BlockPos pos){
TileEntity te = worldIn.getTileEntity(pos);
TileEntityPipe pipe = te instanceof TileEntityPipe ? (TileEntityPipe) te : null;
for(EnumFacing face : EnumFacing.VALUES){
state = state.withProperty(CONNECT[face.getIndex()], canBeConnectedTo(worldIn, pos, face));
}
if(pipe == null) return state;
state = state.withProperty(COVERED, pipe.covered());
return state;
}
@Override
public boolean canBeConnectedTo(IBlockAccess world, BlockPos pos, EnumFacing facing){
TileEntity te = world.getTileEntity(pos);
return te instanceof TileEntityPipe && ((TileEntityPipe) te).canBeConnectedTo(facing);
}
@Override
public boolean rotateBlock(World world, @Nonnull BlockPos pos, EnumFacing axis){
TileEntity te = world.getTileEntity(pos);
if(!(te instanceof TileEntityPipe)) return false;
TileEntityPipe pipe = (TileEntityPipe) te;
return pipe.rotateProcessor(axis);
}
@Nullable
@Override
public EnumFacing[] getValidRotations(World world, @Nonnull BlockPos pos){
return EnumFacing.VALUES;
}
@Override
public boolean recolorBlock(World world, @Nonnull BlockPos pos, EnumFacing side, @Nonnull EnumDyeColor color){
TileEntity te = world.getTileEntity(pos);
if(!(te instanceof TileEntityPipe)) return false;
TileEntityPipe pipe = (TileEntityPipe) te;
pipe.recolor(ItemDye.DYE_COLORS[color.getDyeDamage()]);
return true;
}
@Nonnull
@Override
public ItemStack getPickBlock(@Nonnull IBlockState state, RayTraceResult target, @Nonnull World world, @Nonnull BlockPos pos, EntityPlayer player){
ItemStack stack = new ItemStack(this);
TileEntity te = world.getTileEntity(pos);
if(!(te instanceof TileEntityPipe)) return stack;
TileEntityPipe pipe = (TileEntityPipe) te;
NBTTagCompound compound = new NBTTagCompound();
stack.setTagCompound(compound);
compound.setBoolean("covered", pipe.covered());
compound.setInteger("color", pipe.coverColor);
return stack;
}
@Override
public int getMetaFromState(IBlockState state){
return 0;
}
@Nonnull
@Override
@Deprecated
public IBlockState getStateFromMeta(int meta){
return getDefaultState();
}
@Nonnull
@Override
protected BlockStateContainer createBlockState(){
return new BlockStateContainer(this, Arrays.stream(new IProperty<?>[][]{CONNECT, {COVERED}}).flatMap(Arrays::stream).toArray(IProperty[]::new));
}
}
|
src/main/java/jp/crafterkina/pipes/common/block/BlockPipe.java
|
package jp.crafterkina.pipes.common.block;
import jp.crafterkina.pipes.api.pipe.IStrategy;
import jp.crafterkina.pipes.common.block.entity.TileEntityPipe;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemDye;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import static jp.crafterkina.pipes.api.PipesConstants.MOD_ID;
/**
* Created by Kina on 2016/12/14.
*/
public class BlockPipe extends BlockContainer{
public static final PropertyBool[] CONNECT = Arrays.stream(EnumFacing.VALUES).map(f -> PropertyBool.create("c_" + f.getName())).toArray(PropertyBool[]::new);
public static final PropertyBool COVERED = PropertyBool.create("covered");
private static final AxisAlignedBB CORE = new AxisAlignedBB(5.5 / 16d, 5.5 / 16d, 5.5 / 16d, 10.5 / 16d, 10.5 / 16d, 10.5 / 16d);
private static final AxisAlignedBB[] PIPE = {new AxisAlignedBB(6 / 16d, 0d, 6 / 16d, 10 / 16d, 5.5 / 16d, 10 / 16d), new AxisAlignedBB(6 / 16d, 10.5 / 16d, 6 / 16d, 10 / 16d, 1d, 10 / 16d), new AxisAlignedBB(6 / 16d, 6 / 16d, 0d, 10 / 16d, 10 / 16d, 5.5 / 16d), new AxisAlignedBB(6 / 16d, 6 / 16d, 10.5 / 16d, 10 / 16d, 10 / 16d, 1d), new AxisAlignedBB(0d, 6 / 16d, 6 / 16d, 5.5 / 16d, 10 / 16d, 10 / 16d), new AxisAlignedBB(10.5 / 16d, 6 / 16d, 6 / 16d, 1d, 6 / 16d, 6 / 16d)};
@SuppressWarnings("deprecation")
public BlockPipe(){
super(Material.GLASS);
setUnlocalizedName(MOD_ID + ".pipe");
setCreativeTab(CreativeTabs.TRANSPORTATION);
setHardness(0.2f);
setResistance(0.1f);
IBlockState state = getBlockState().getBaseState();
for(EnumFacing f : EnumFacing.VALUES){
state = state.withProperty(CONNECT[f.getIndex()], false);
}
state = state.withProperty(COVERED, false);
setDefaultState(state);
}
public static int getColor(IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex){
if(worldIn == null || pos == null) return 0xFFFFFF;
TileEntity te = worldIn.getTileEntity(pos);
if(!(te instanceof TileEntityPipe)) return 0xFFFFFF;
TileEntityPipe pipe = (TileEntityPipe) te;
return tintIndex == 0 ? 0x9F844D : pipe.coverColor;
}
@Override
public void getSubBlocks(@Nonnull Item itemIn, @Nonnull CreativeTabs tab, @Nonnull NonNullList<ItemStack> subItems){
ItemStack stack = new ItemStack(itemIn);
NBTTagCompound compound = new NBTTagCompound();
{
stack.setTagCompound(compound);
compound.setBoolean("covered", false);
subItems.add(stack);
}
for(EnumDyeColor color : EnumDyeColor.values()){
stack = new ItemStack(itemIn);
compound = new NBTTagCompound();
{
stack.setTagCompound(compound);
compound.setBoolean("covered", true);
compound.setInteger("color", ItemDye.DYE_COLORS[color.getDyeDamage()]);
}
subItems.add(stack);
}
}
@Override
public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack){
NBTTagCompound compound = stack.getTagCompound();
if(compound == null) compound = new NBTTagCompound();
TileEntity te = worldIn.getTileEntity(pos);
if(!(te instanceof TileEntityPipe)) return;
TileEntityPipe pipe = (TileEntityPipe) te;
pipe.coverColor = compound.getBoolean("covered") ? compound.getInteger("color") : -1;
worldIn.notifyBlockUpdate(pos, state, state, 8);
}
@Override
@SuppressWarnings("deprecation")
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ){
if(playerIn.getHeldItem(hand).isEmpty()){
TileEntity te = worldIn.getTileEntity(pos);
if(te == null || !te.hasCapability(IStrategy.IStrategyHandler.CAPABILITY, facing)) return false;
IStrategy.IStrategyHandler handler = te.getCapability(IStrategy.IStrategyHandler.CAPABILITY, facing);
assert handler != null;
ItemStack removed = handler.remove();
Block.spawnAsEntity(worldIn, pos, removed);
worldIn.notifyBlockUpdate(pos, worldIn.getBlockState(pos), getActualState(worldIn.getBlockState(pos), worldIn, pos), 8);
}
return super.onBlockActivated(worldIn, pos, state, playerIn, hand, facing, hitX, hitY, hitZ);
}
@Override
public void breakBlock(World worldIn, @Nonnull BlockPos pos, @Nonnull IBlockState state){
TileEntity tileentity = worldIn.getTileEntity(pos);
if(tileentity instanceof TileEntityPipe){
TileEntityPipe pipe = (TileEntityPipe) tileentity;
pipe.dropItems();
worldIn.updateComparatorOutputLevel(pos, this);
}
super.breakBlock(worldIn, pos, state);
}
@Override
@SuppressWarnings("deprecation")
public boolean hasComparatorInputOverride(IBlockState state){
return true;
}
@Override
@SuppressWarnings("deprecation")
public int getComparatorInputOverride(IBlockState blockState, World worldIn, BlockPos pos){
TileEntity te = worldIn.getTileEntity(pos);
if(!(te instanceof TileEntityPipe)) return 0;
TileEntityPipe pipe = (TileEntityPipe) te;
return pipe.getComparatorPower();
}
@Override
@SuppressWarnings("deprecation")
public int getWeakPower(IBlockState blockState, IBlockAccess worldIn, BlockPos pos, EnumFacing side){
TileEntity te = worldIn.getTileEntity(pos);
if(!(te instanceof TileEntityPipe)) return 0;
TileEntityPipe pipe = (TileEntityPipe) te;
return pipe.getWeakPower(side);
}
@Override
@SuppressWarnings("deprecation")
public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos){
TileEntity te = worldIn.getTileEntity(pos);
if(!(te instanceof TileEntityPipe)) return;
TileEntityPipe pipe = (TileEntityPipe) te;
pipe.onRedstonePowered(worldIn.isBlockIndirectlyGettingPowered(pos));
}
@Nullable
@Override
public TileEntity createNewTileEntity(@Nonnull World worldIn, int meta){
return new TileEntityPipe();
}
@Nonnull
@Override
@Deprecated
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos){
return CORE;
}
@Nullable
@Override
@Deprecated
public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, @Nonnull IBlockAccess worldIn, @Nonnull BlockPos pos){
return CORE;
}
@Nonnull
@Override
@Deprecated
public AxisAlignedBB getSelectedBoundingBox(IBlockState state, @Nonnull World worldIn, @Nonnull BlockPos pos){
return CORE;
}
@Override
@SuppressWarnings("deprecation")
@Deprecated
public void addCollisionBoxToList(IBlockState stateIn, @Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull AxisAlignedBB entityBox, @Nonnull List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn){
addCollisionBoxToList(pos, entityBox, collidingBoxes, CORE);
Arrays.stream(EnumFacing.VALUES).filter(f -> worldIn.getBlockState(pos).getBlock().getActualState(stateIn, worldIn, pos).getValue(CONNECT[f.getIndex()])).forEach(f -> addCollisionBoxToList(pos, entityBox, collidingBoxes, PIPE[f.getIndex()]));
}
@Nullable
@Override
@SuppressWarnings("deprecation")
@Deprecated
public RayTraceResult collisionRayTrace(IBlockState state, @Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull Vec3d start, @Nonnull Vec3d end){
return Arrays.stream(EnumFacing.VALUES).filter(f -> worldIn.getBlockState(pos).getBlock().getActualState(state, worldIn, pos).getValue(CONNECT[f.getIndex()])).map(f -> rayTrace(pos, start, end, PIPE[f.getIndex()])).filter(Objects::nonNull).filter(r -> r.typeOfHit != RayTraceResult.Type.MISS).findFirst().orElseGet(() -> rayTrace(pos, start, end, CORE));
}
@Override
@Deprecated
public boolean isOpaqueCube(IBlockState state){
return false;
}
@Override
@Deprecated
public boolean isFullCube(IBlockState state){
return false;
}
@Override
@Deprecated
@SideOnly(Side.CLIENT)
public boolean shouldSideBeRendered(IBlockState blockState, @Nonnull IBlockAccess blockAccess, @Nonnull BlockPos pos, EnumFacing side){
return true;
}
@Override
@Nonnull
@SideOnly(Side.CLIENT)
public BlockRenderLayer getBlockLayer(){
return BlockRenderLayer.CUTOUT_MIPPED;
}
@Nonnull
@Override
public EnumBlockRenderType getRenderType(IBlockState state){
return EnumBlockRenderType.MODEL;
}
@SuppressWarnings("DeprecatedIsStillUsed")
@Nonnull
@Override
@Deprecated
public IBlockState getActualState(@Nonnull IBlockState state, IBlockAccess worldIn, BlockPos pos){
TileEntity te = worldIn.getTileEntity(pos);
TileEntityPipe pipe = te instanceof TileEntityPipe ? (TileEntityPipe) te : null;
for(EnumFacing face : EnumFacing.VALUES){
state = state.withProperty(CONNECT[face.getIndex()], canBeConnectedTo(worldIn, pos, face));
}
if(pipe == null) return state;
state = state.withProperty(COVERED, pipe.covered());
return state;
}
@Override
public boolean canBeConnectedTo(IBlockAccess world, BlockPos pos, EnumFacing facing){
TileEntity te = world.getTileEntity(pos);
return te instanceof TileEntityPipe && ((TileEntityPipe) te).canBeConnectedTo(facing);
}
@Override
public boolean rotateBlock(World world, @Nonnull BlockPos pos, EnumFacing axis){
TileEntity te = world.getTileEntity(pos);
if(!(te instanceof TileEntityPipe)) return false;
TileEntityPipe pipe = (TileEntityPipe) te;
return pipe.rotateProcessor(axis);
}
@Nullable
@Override
public EnumFacing[] getValidRotations(World world, @Nonnull BlockPos pos){
return EnumFacing.VALUES;
}
@Override
public boolean recolorBlock(World world, @Nonnull BlockPos pos, EnumFacing side, @Nonnull EnumDyeColor color){
TileEntity te = world.getTileEntity(pos);
if(!(te instanceof TileEntityPipe)) return false;
TileEntityPipe pipe = (TileEntityPipe) te;
pipe.recolor(ItemDye.DYE_COLORS[color.getDyeDamage()]);
return true;
}
@Override
public int getMetaFromState(IBlockState state){
return 0;
}
@Nonnull
@Override
@Deprecated
public IBlockState getStateFromMeta(int meta){
return getDefaultState();
}
@Nonnull
@Override
protected BlockStateContainer createBlockState(){
return new BlockStateContainer(this, Arrays.stream(new IProperty<?>[][]{CONNECT, {COVERED}}).flatMap(Arrays::stream).toArray(IProperty[]::new));
}
}
|
Implement getPickBlock
|
src/main/java/jp/crafterkina/pipes/common/block/BlockPipe.java
|
Implement getPickBlock
|
|
Java
|
lgpl-2.1
|
03ec1e40bdc5b7568a2f8bcc115f416acb994750
| 0
|
ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror
|
/*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A.
GNU Lesser General Public License
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., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*****************************************************************/
package jade.core.sam;
import jade.core.Profile;
import jade.util.Logger;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
class DefaultSAMInfoHandlerImpl implements SAMInfoHandler {
private static final String SAM_PREFIX = "SAM_";
private Map<String, PrintStream> entityFiles = new HashMap<String, PrintStream>();
// For counters we need to keep the total value together with the Stream used to write the CSV file
private Map<String, CounterInfo> counters = new HashMap<String, CounterInfo>();
private SimpleDateFormat timeStampFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private String csvSeparator = "| ";
private File samInfoDirectory;
private String fileSeparator;
private Logger myLogger = Logger.getMyLogger(getClass().getName());
public void initialize(Profile p) throws Exception {
fileSeparator = System.getProperty("file.separator");
String samInfoDirectoryName = p.getParameter("jade_core_sam_SAMService_csvdirectory", ".");
samInfoDirectory = new File(samInfoDirectoryName);
if (!samInfoDirectory.exists()) {
myLogger.log(Logger.CONFIG, "SAM csv directory "+samInfoDirectory+" does not exists. Creating it ...");
boolean success = samInfoDirectory.mkdirs();
if (!success) {
throw new IOException("Cannot create SAM csv directory "+samInfoDirectoryName+".");
}
}
else if (!samInfoDirectory.isDirectory()) {
throw new IOException("SAM csv location "+samInfoDirectoryName+" is not a directory.");
}
}
public void shutdown() {
// Close all files
for (PrintStream ps : entityFiles.values()) {
ps.close();
}
for (CounterInfo ci : counters.values()) {
ci.stream.close();
}
}
public void handle(Date timeStamp, SAMInfo info) {
// Entities
Map<String, AverageMeasure> entityMeasures = info.getEntityMeasures();
for (String entityName : entityMeasures.keySet()) {
myLogger.log(Logger.FINE, "Handling measure of entity "+entityName);
try {
AverageMeasure m = entityMeasures.get(entityName);
PrintStream stream = entityFiles.get(entityName);
if (stream == null) {
// This is the first time we get a measure for this entity --> Initialize the file
myLogger.log(Logger.INFO, "Creating CSV file for measures of entity "+entityName);
File f = createFile(entityName);
stream = new PrintStream(f);
stream.println("Time-stamp"+csvSeparator+"Average-value"+csvSeparator+"N-samples");
entityFiles.put(entityName, stream);
}
stream.println(timeStampFormatter.format(timeStamp)+csvSeparator+m.getValue()+csvSeparator+m.getNSamples());
}
catch (Exception e) {
myLogger.log(Logger.WARNING, "Error writing to CSV file of entity "+entityName, e);
// Likely someone removed the CSV file in the meanwhile. Reset everything so that at next round the file will be re-created
entityFiles.remove(entityName);
}
}
// Counters
Map<String, Long> counterValues = info.getCounterValues();
for (String counterName : counterValues.keySet()) {
myLogger.log(Logger.FINE, "Handling value of counter "+counterName);
try {
long value = counterValues.get(counterName);
CounterInfo ci = counters.get(counterName);
if (ci == null) {
// This is the first time we get a value for this counter --> Initialize its csv file
myLogger.log(Logger.INFO, "Creating CSV file for values of counter "+counterName);
File f = createFile(counterName);
PrintStream stream = new PrintStream(f);
stream.println("Time-stamp"+csvSeparator+"Value"+csvSeparator+"Total-value");
ci = new CounterInfo(stream);
counters.put(counterName, ci);
}
ci.totValue += value;
ci.stream.println(timeStampFormatter.format(timeStamp)+csvSeparator+value+csvSeparator+ci.totValue);
}
catch (Exception e) {
myLogger.log(Logger.WARNING, "Error writing to CSV file of counter "+counterName, e);
// Likely someone removed the CSV file in the meanwhile. Reset everything so that at next round the file will be re-created
counters.remove(counterName);
}
}
}
private File createFile(String name) throws IOException {
String fileName = samInfoDirectory.getPath()+fileSeparator+SAM_PREFIX+name+".csv";
File file = new File(fileName);
file.createNewFile();
return file;
}
/**
* Inner class CounterInfo
*/
private class CounterInfo {
PrintStream stream;
long totValue = 0;
CounterInfo(PrintStream ps) {
stream = ps;
}
} // END of inner class CounterInfo
}
|
src/jade/core/sam/DefaultSAMInfoHandlerImpl.java
|
/*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A.
GNU Lesser General Public License
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., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*****************************************************************/
package jade.core.sam;
import jade.core.Profile;
import jade.util.Logger;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
class DefaultSAMInfoHandlerImpl implements SAMInfoHandler {
private static final String SAM_PREFIX = "SAM_";
private Map<String, PrintStream> entityFiles = new HashMap<String, PrintStream>();
// For counters we need to keep the total value together with the Stream used to write the CSV file
private Map<String, CounterInfo> counters = new HashMap<String, CounterInfo>();
private SimpleDateFormat timeStampFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
private String csvSeparator = "| ";
private File samInfoDirectory;
private String fileSeparator;
private Logger myLogger = Logger.getMyLogger(getClass().getName());
public void initialize(Profile p) throws Exception {
fileSeparator = System.getProperty("file.separator");
String samInfoDirectoryName = p.getParameter("jade_core_sam_SAMService_csvdirectory", ".");
samInfoDirectory = new File(samInfoDirectoryName);
if (!samInfoDirectory.exists()) {
myLogger.log(Logger.CONFIG, "SAM csv directory "+samInfoDirectory+" does not exists. Creating it ...");
boolean success = samInfoDirectory.mkdirs();
if (!success) {
throw new IOException("Cannot create SAM csv directory "+samInfoDirectoryName+".");
}
}
else if (!samInfoDirectory.isDirectory()) {
throw new IOException("SAM csv location "+samInfoDirectoryName+" is not a directory.");
}
}
public void shutdown() {
// Close all files
for (PrintStream ps : entityFiles.values()) {
ps.close();
}
for (CounterInfo ci : counters.values()) {
ci.stream.close();
}
}
public void handle(Date timeStamp, SAMInfo info) {
// Entities
Map<String, AverageMeasure> entityMeasures = info.getEntityMeasures();
for (String entityName : entityMeasures.keySet()) {
myLogger.log(Logger.FINE, "Handling measure of entity "+entityName);
try {
AverageMeasure m = entityMeasures.get(entityName);
PrintStream stream = entityFiles.get(entityName);
if (stream == null) {
// This is the first time we get a measure for this entity --> Initialize the file
myLogger.log(Logger.INFO, "Creating CSV file for measures of entity "+entityName);
File f = createFile(entityName);
stream = new PrintStream(f);
stream.println("Time-stamp"+csvSeparator+"Average-value"+csvSeparator+"N-samples");
entityFiles.put(entityName, stream);
}
stream.println(timeStampFormatter.format(timeStamp)+csvSeparator+m.getValue()+csvSeparator+m.getNSamples());
}
catch (Exception e) {
// FIXME: Print a suitable log
e.printStackTrace();
}
}
// Counters
Map<String, Long> counterValues = info.getCounterValues();
for (String counterName : counterValues.keySet()) {
myLogger.log(Logger.FINE, "Handling value of counter "+counterName);
try {
long value = counterValues.get(counterName);
CounterInfo ci = counters.get(counterName);
if (ci == null) {
// This is the first time we get a value for this counter --> Initialize its csv file
myLogger.log(Logger.INFO, "Creating CSV file for values of counter "+counterName);
File f = createFile(counterName);
PrintStream stream = new PrintStream(f);
stream.println("Time-stamp"+csvSeparator+"Value"+csvSeparator+"Total-value");
ci = new CounterInfo(stream);
counters.put(counterName, ci);
}
ci.totValue += value;
ci.stream.println(timeStampFormatter.format(timeStamp)+csvSeparator+value+csvSeparator+ci.totValue);
}
catch (Exception e) {
// FIXME: Print a suitable log
e.printStackTrace();
}
}
}
private File createFile(String name) throws IOException {
String fileName = samInfoDirectory.getPath()+fileSeparator+SAM_PREFIX+name+".csv";
File file = new File(fileName);
file.createNewFile();
return file;
}
/**
* Inner class CounterInfo
*/
private class CounterInfo {
PrintStream stream;
long totValue = 0;
CounterInfo(PrintStream ps) {
stream = ps;
}
} // END of inner class CounterInfo
}
|
Modified time-stamp format.
Improved logs and managed CSV file write errors
|
src/jade/core/sam/DefaultSAMInfoHandlerImpl.java
|
Modified time-stamp format. Improved logs and managed CSV file write errors
|
|
Java
|
apache-2.0
|
03a85ccc4da5b957abda717e4c3f31482247b5c4
| 0
|
rosette-api/java,rosette-api/java,rosette-api/java
|
/*
* Copyright 2014 Basis Technology Corp.
*
* 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.basistech.rosette.api;
import com.basistech.rosette.apimodel.CategoriesOptions;
import com.basistech.rosette.apimodel.CategoriesResponse;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.EntitiesOptions;
import com.basistech.rosette.apimodel.EntitiesResponse;
import com.basistech.rosette.apimodel.ErrorResponse;
import com.basistech.rosette.apimodel.InfoResponse;
import com.basistech.rosette.apimodel.LanguageOptions;
import com.basistech.rosette.apimodel.LanguageResponse;
import com.basistech.rosette.apimodel.LinkedEntitiesResponse;
import com.basistech.rosette.apimodel.MorphologyOptions;
import com.basistech.rosette.apimodel.MorphologyResponse;
import com.basistech.rosette.apimodel.Name;
import com.basistech.rosette.apimodel.NameSimilarityRequest;
import com.basistech.rosette.apimodel.NameSimilarityResponse;
import com.basistech.rosette.apimodel.NameTranslationRequest;
import com.basistech.rosette.apimodel.NameTranslationResponse;
import com.basistech.rosette.apimodel.Options;
import com.basistech.rosette.apimodel.PingResponse;
import com.basistech.rosette.apimodel.RelationshipsOptions;
import com.basistech.rosette.apimodel.RelationshipsResponse;
import com.basistech.rosette.apimodel.Request;
import com.basistech.rosette.apimodel.Response;
import com.basistech.rosette.apimodel.SentencesResponse;
import com.basistech.rosette.apimodel.SentimentOptions;
import com.basistech.rosette.apimodel.SentimentResponse;
import com.basistech.rosette.apimodel.TokensResponse;
import com.basistech.rosette.apimodel.jackson.ApiModelMixinModule;
import com.basistech.rosette.apimodel.jackson.DocumentRequestMixin;
import com.basistech.util.LanguageCode;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.io.ByteStreams;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.annotation.Immutable;
import org.apache.http.annotation.ThreadSafe;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.FormBodyPartBuilder;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MIME;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.AbstractContentBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import static java.net.HttpURLConnection.HTTP_OK;
/**
* You can use the RosetteAPI to access Rosette API endpoints.
* RosetteAPI is thread-safe and immutable.
*/
@Immutable
@ThreadSafe
public class RosetteAPI implements Closeable {
public static final String DEFAULT_URL_BASE = "https://api.rosette.com/rest/v1";
public static final String SERVICE_NAME = "RosetteAPI";
public static final String BINDING_VERSION = getVersion();
public static final String USER_AGENT_STR = SERVICE_NAME + "-Java/" + BINDING_VERSION;
public static final String LANGUAGE_SERVICE_PATH = "/language";
public static final String MORPHOLOGY_SERVICE_PATH = "/morphology";
public static final String ENTITIES_SERVICE_PATH = "/entities";
/**
* @deprecated merged into the {@link #ENTITIES_SERVICE_PATH}.
*/
@Deprecated
public static final String ENTITIES_LINKED_SERVICE_PATH = "/entities/linked";
public static final String CATEGORIES_SERVICE_PATH = "/categories";
public static final String RELATIONSHIPS_SERVICE_PATH = "/relationships";
public static final String SENTIMENT_SERVICE_PATH = "/sentiment";
public static final String NAME_TRANSLATION_SERVICE_PATH = "/name-translation";
public static final String NAME_SIMILARITY_SERVICE_PATH = "/name-similarity";
public static final String TOKENS_SERVICE_PATH = "/tokens";
public static final String SENTENCES_SERVICE_PATH = "/sentences";
public static final String INFO_SERVICE_PATH = "/info";
public static final String PING_SERVICE_PATH = "/ping";
private static final Logger LOG = LoggerFactory.getLogger(RosetteAPI.class);
private String key;
private String urlBase = DEFAULT_URL_BASE;
private int failureRetries;
private LanguageCode language;
private Options options;
private String genre;
private ObjectMapper mapper;
private HttpClient httpClient;
private List<Header> customHeaders;
private int maxSockets = 1;
// set in initHttpClient. We don't mess with a user-specified client.
private boolean allowSocketChange;
/**
* Constructs a Rosette API instance using an API key.
*
* @param key Rosette API key
* @throws RosetteAPIException If the service is not compatible with the version of the binding.
* @throws IOException General IO exception
*
* @deprecated use RosetteAPI.Builder class
*/
@Deprecated
public RosetteAPI(String key) throws IOException, RosetteAPIException {
this(key, DEFAULT_URL_BASE);
}
/**
* Constructs a Rosette API instance using an API key and accepts an
* alternate URL for testing purposes.
*
* @param key Rosette API key
* @param alternateUrl Alternate Rosette API URL
* @throws RosetteAPIException If the service is not compatible with the version of the binding.
* @throws IOException General IO exception
*
* @deprecated use RosetteAPI.Builder class
*/
@Deprecated
public RosetteAPI(String key, String alternateUrl) throws IOException, RosetteAPIException {
Objects.requireNonNull(alternateUrl, "alternateUrl cannot be null");
this.key = key;
urlBase = alternateUrl;
if (urlBase.endsWith("/")) {
urlBase = urlBase.substring(0, urlBase.length() - 1);
}
this.failureRetries = 1;
mapper = ApiModelMixinModule.setupObjectMapper(new ObjectMapper());
customHeaders = new ArrayList<>();
initHttpClient();
}
/**
* Constructs a Rosette API instance using the builder syntax.
*
* @param key Rosette API key
* @param urlToCall Alternate Rosette API URL
* @param failureRetries Number of times to retry in case of failure; default 1
* @param language source language
* @param genre genre (ex "social-media")
* @param options options for the request
* @throws IOException General IO exception
* @throws RosetteAPIException Problem with the API request
*/
private RosetteAPI(String key, String urlToCall, int failureRetries,
LanguageCode language, String genre, Options options,
HttpClient httpClient)
throws IOException, RosetteAPIException {
this.key = key;
this.language = language;
this.genre = genre;
this.options = options;
urlBase = urlToCall.trim().replaceAll("/+$", "");
this.failureRetries = failureRetries;
mapper = ApiModelMixinModule.setupObjectMapper(new ObjectMapper());
customHeaders = new ArrayList<>();
setUpHttpClient(httpClient);
}
/**
* @param httpClient user provided http client
* @throws IOException
*/
private void setUpHttpClient(HttpClient httpClient) throws IOException {
if (httpClient == null) {
initHttpClient();
} else {
allowSocketChange = false;
this.httpClient = httpClient;
}
HttpResponse response = this.httpClient.execute(new HttpPost(urlBase));
if (response != null) {
if (response instanceof CloseableHttpResponse) {
((CloseableHttpResponse)response).close();
}
}
}
/**
* Returns the version of the binding.
*
* @return version of the binding
*/
private static String getVersion() {
Properties properties = new Properties();
try (InputStream ins = RosetteAPI.class.getClassLoader().getResourceAsStream("version.properties")) {
properties.load(ins);
} catch (IOException e) {
// should not happen
}
return properties.getProperty("version", "undefined");
}
/**
* Return failure retries.
*
* @return failure retries
*/
public int getFailureRetries() {
return failureRetries;
}
/**
* Return language code.
*
* @return source language
*/
public LanguageCode getLanguageCode() {
return language;
}
/**
* Returns the genre.
*
* @return genre if being used by API
*/
public String getGenre() {
return genre;
}
/**
* Returns options used by API.
*
* @return options
*/
public Options getOptions() {
return options;
}
/**
*
*/
private void initHttpClient() {
List<Header> defaultHeaders = new ArrayList<>();
defaultHeaders.add(new BasicHeader(HttpHeaders.USER_AGENT, USER_AGENT_STR));
defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "gzip"));
if (key != null) {
defaultHeaders.add(new BasicHeader("X-RosetteAPI-Key", key));
defaultHeaders.add(new BasicHeader("X-RosetteAPI-Binding", "java"));
defaultHeaders.add(new BasicHeader("X-RosetteAPI-Binding-Version", BINDING_VERSION));
}
if (customHeaders.size() > 0) {
defaultHeaders.addAll(customHeaders);
}
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(maxSockets);
httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultHeaders(defaultHeaders).build();
allowSocketChange = true;
}
/**
* Add a custom HTTP header to pass to Rosette API.
*
* @param name header name
* @param value header value
*/
public void addCustomHeader(String name, String value) {
addCustomHeader(new BasicHeader(name, value));
}
/**
* Add a custom HTTP header to pass to Rosette API.
*
* @param header header
*/
public void addCustomHeader(Header header) {
customHeaders.add(header);
initHttpClient();
}
/**
* Gets information about the Rosette API, returns name, version, build number and build time.
*
* @return InfoResponse
* @throws RosetteAPIException Rosette specific exception
* @throws IOException General IO exception
*/
public InfoResponse info() throws IOException, RosetteAPIException {
return sendGetRequest(urlBase + INFO_SERVICE_PATH, InfoResponse.class);
}
/**
* Pings the Rosette API for a response indicting that the service is available.
*
* @return PingResponse
* @throws RosetteAPIException Rosette specific exception
* @throws IOException General IO exception
*/
public PingResponse ping() throws IOException, RosetteAPIException {
return sendGetRequest(urlBase + PING_SERVICE_PATH, PingResponse.class);
}
/**
* Matches 2 names and returns a score in NameMatchingResponse.
*
* @param request request
* @return response
* @throws RosetteAPIException Rosette specific exception
* @throws IOException General IO exception
*
* @deprecated replaced by {@link #getNameSimilarity(Name, Name) getNameSimilarity}
*/
@Deprecated
public NameSimilarityResponse getNameSimilarity(NameSimilarityRequest request) throws RosetteAPIException, IOException {
return getNameSimilarity(request.getName1(), request.getName2());
}
/**
* Matches 2 names and returns a score in NameMatchingResponse.
*
* @param nameOne first name
* @param nameTwo second name
* @return response
* @throws RosetteAPIException Rosette specific exception
* @throws IOException General IO exception
*/
public NameSimilarityResponse getNameSimilarity(Name nameOne, Name nameTwo) throws RosetteAPIException, IOException {
NameSimilarityRequest request = new NameSimilarityRequest(nameOne, nameTwo);
return sendPostRequest(request, urlBase + NAME_SIMILARITY_SERVICE_PATH, NameSimilarityResponse.class);
}
/**
* Translates a name into the target language specified in NameTranslationRequest.
*
* @param request NameTranslationRequest contains the name to be translated and the target language.
* @return the response.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public NameTranslationResponse getNameTranslation(NameTranslationRequest request)
throws RosetteAPIException, IOException {
return sendPostRequest(request, urlBase + NAME_TRANSLATION_SERVICE_PATH, NameTranslationResponse.class);
}
/**
* Performs language identification on data read from an InputStream. Return a list of languages.
*
* @param inputStream Input stream of file.
* @param contentType the content type (e.g. text/html)
* @param options Options to Language API.
* @return An ordered list of detected languages, including language and detection confidence, sorted by
* descending confidence.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated Replaced by {@link #getLanguage(InputStream, String) getLanguage}
*/
@Deprecated
public LanguageResponse getLanguage(InputStream inputStream, String contentType, LanguageOptions options)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder().contentBytes(bytes, contentType)
.options(options).build();
return sendPostRequest(request, urlBase + LANGUAGE_SERVICE_PATH, LanguageResponse.class);
}
/**
* Performs language identification on data from an InputSteam. Builds request object from API, not parameters.
* Returns a list of languages.
*
* @param inputStream Input stream of file
* @param contentType the content type (e.g. text/html)
*
* @return An ordered list of detected languages, including language and detection confidence, sorted by
* descending confidence.
* @throws RosetteAPIException - There's a problem with the Rosette API request
* @throws IOException - There's a problem with communication or JSON serialization/deserialization
*/
public LanguageResponse getLanguage(InputStream inputStream, String contentType) throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + LANGUAGE_SERVICE_PATH, LanguageResponse.class);
}
/**
* Performs language identification on data read from an URL. Return a list of languages.
*
* @param url URL for language detection.
* @param options Options to Language API.
* @return An ordered list of detected languages, including language and detection confidence, sorted by
* descending confidence.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated Replaced by {@link #getLanguage(URL) getLanguage}
*/
@Deprecated
public LanguageResponse getLanguage(URL url, LanguageOptions options) throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.contentUri(url.toString())
.options(options)
.build();
return sendPostRequest(request, urlBase + LANGUAGE_SERVICE_PATH, LanguageResponse.class);
}
/**
* Performs language identification on data read from an URL. Builds request object from API, not parameters.
* Returns a list of languages.
*
* @param url URL for language detection
* @return An ordered list of detected languages, including language and detection confidence, sorted by
* descending confidence.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public LanguageResponse getLanguage(URL url) throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + LANGUAGE_SERVICE_PATH, LanguageResponse.class);
}
/**
* Performs language identification on data read from a string. Return a list of languages.
*
* @param content String content for language detection.
* @param options Options to Language API.
* @return An ordered list of detected languages, including language and detection confidence, sorted by
* descending confidence.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated Replaced by {@link #getLanguage(String) getLanguage}
*/
@Deprecated
public LanguageResponse getLanguage(String content, LanguageOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder().content(content)
.options(options).build();
return sendPostRequest(request, urlBase + LANGUAGE_SERVICE_PATH, LanguageResponse.class);
}
/**
* Performs language identification on data read from a string. Builds request object from API not parameters.
* Returns a list of languages.
*
* @param content String content for language detection.
*
* @return An ordered list of detected languages, including language and detection confidence, sorted by
* descending confidence.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public LanguageResponse getLanguage(String content) throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + LANGUAGE_SERVICE_PATH, LanguageResponse.class);
}
/**
* Returns morphological analysis of the input file.
* The response may include lemmas, part of speech tags, compound word components, and Han readings.
* Support for specific return types depends on language.
*
* @param morphologicalFeature Type of morphological analysis to perform.
* @param inputStream Input stream of file.
* @param contentType the content type (e.g. text/html)
* @param language Language of input if known (see {@link LanguageCode}), or null
* @param options Linguistics options
* @return MorphologyResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getMorphology(MorphologicalFeature, InputStream, String) getMorphology}
*/
@Deprecated
public MorphologyResponse getMorphology(MorphologicalFeature morphologicalFeature,
InputStream inputStream,
String contentType,
LanguageCode language, MorphologyOptions options)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.options(options)
.build();
return sendPostRequest(request, urlBase + MORPHOLOGY_SERVICE_PATH + "/" + morphologicalFeature.toString(),
MorphologyResponse.class);
}
/**
* Returns morphological analysis of the input file. The response may include lemmas, part of speech tags,
* compound word components, and Han readings. Builds request object from API rather than from parameters.
* Support for specific return types depends on language.
*
* @param inputStream Input stream of file
* @param contentType The content type (e.g. text/html)
* @return MorphologyResponse
* @throws RosetteAPIException
* @throws IOException
*/
public MorphologyResponse getMorphology(MorphologicalFeature morphologicalFeature,
InputStream inputStream,
String contentType)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + MORPHOLOGY_SERVICE_PATH + "/" + morphologicalFeature.toString(),
MorphologyResponse.class);
}
/**
* Returns morphological analysis of the URL content.
* The response may include lemmas, part of speech tags, compound word components, and Han readings.
* Support for specific return types depends on language.
*
* @param morphologicalFeature Type of morphological analysis to perform.
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null
* @param options Linguistics options
* @return MorphologyResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getMorphology(MorphologicalFeature, URL) getMorphology}
*/
@Deprecated
public MorphologyResponse getMorphology(MorphologicalFeature morphologicalFeature, URL url,
LanguageCode language,
MorphologyOptions options) throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.options(options)
.build();
return sendPostRequest(request, urlBase + MORPHOLOGY_SERVICE_PATH + "/" + morphologicalFeature.toString(),
MorphologyResponse.class);
}
/**
* Returns morphological analysis of the URL content. The response may include lemmas, part of speech tags, compound
* word components, and Han readings. Builds request object from API, rather than from parameters. Support for
* specific return types depends on language.
*
* @param url URL containing the data
* @return MorphologyResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a problem with communication or JSON serialization/deserialization.
*/
public MorphologyResponse getMorphology(MorphologicalFeature morphologicalFeature, URL url)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + MORPHOLOGY_SERVICE_PATH + "/" + morphologicalFeature.toString(),
MorphologyResponse.class);
}
/**
* Returns morphological analysis of a string.
* The response may include lemmas, part of speech tags, compound word components, and Han readings.
* Support for specific return types depends on language.
*
* @param morphologicalFeature Type of morphological analysis to perform.
* @param content String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null
* @param options Linguistics options
* @return MorphologyResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getMorphology(MorphologicalFeature, String) getMorphology}
*/
@Deprecated
public MorphologyResponse getMorphology(MorphologicalFeature morphologicalFeature, String content,
LanguageCode language, MorphologyOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.options(options)
.build();
return sendPostRequest(request, urlBase + MORPHOLOGY_SERVICE_PATH + "/" + morphologicalFeature.toString(),
MorphologyResponse.class);
}
/**
* Returns morphological analysis of a string. The response may include lemmas, part of speech tags, compound word
* components, and Han reading. Constructs request object from API information rather than from parameters. Support
* for specific return types depends on language.
*
* @param content String containing the data.
* @return MorphologyResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public MorphologyResponse getMorphology(MorphologicalFeature morphologicalFeature, String content)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + MORPHOLOGY_SERVICE_PATH + "/" + morphologicalFeature.toString(),
MorphologyResponse.class);
}
/**
* Returns entities extracted from the input file.
* <p>
* The response is a list of extracted entities.
* Each entity includes chain ID (all instances of the same entity share a chain id),
* mention (entity text in the input), normalized text (the most complete form of this entity that appears in
* the input), count (how many times this entity appears in the input), and the confidence associated with the
* extraction.
*
* @param inputStream Input stream of file.
* @param contentType the content type of the data (e.g. text/html)
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options EntityMention options.
* @return EntitiesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaces by {@link #getEntities(InputStream, String) getEntities}
*/
@Deprecated
public EntitiesResponse getEntities(InputStream inputStream,
String contentType,
LanguageCode language, EntitiesOptions options)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.options(options)
.build();
return sendPostRequest(request, urlBase + ENTITIES_SERVICE_PATH, EntitiesResponse.class);
}
/**
* Returns entities extracted from the input file. Builds request object from API fields not from parameters.
* <p>
* The response is a list of extracted entities. Each entity includes chain ID (all instances of the same
* entity share a chain id), mention (entity text in the input), normalized text (the most complete form
* of this entity that appears in the input), count (how many times this entity appears in the input), and the
* confidence associated with the extraction.
*
* @param inputStream Input stream of file.
* @param contentType The content type of the data (e.g. text/html)
* @return EntitiesResponse
* @throws RosetteAPIException
* @throws IOException
*/
public EntitiesResponse getEntities(InputStream inputStream, String contentType)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + ENTITIES_SERVICE_PATH, EntitiesResponse.class);
}
/**
* Returns entities extracted from the URL content.
* <p>
* The response is a list of extracted entities.
* Each entity includes chain ID (all instances of the same entity share a chain id),
* mention (entity text in the input), normalized text (the most complete form of this entity that appears in
* the input), count (how many times this entity appears in the input), and the confidence associated with the
* extraction.
*
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options EntityMention options.
* @return EntitiesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getEntities(URL) getEntities}
*/
@Deprecated
public EntitiesResponse getEntities(URL url, LanguageCode language, EntitiesOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.options(options)
.build();
return sendPostRequest(request, urlBase + ENTITIES_SERVICE_PATH, EntitiesResponse.class);
}
/**
*Returns entities extracted from the URL content. Request object built through API rather than parameters.
* <p>
* The response is a list of extracted entities.
* Each entity includes chain ID (all instances of the same entity share a chain id),
* mention (entity text in the input), normalized text (the most complete form of this entity that appears in
* the input), count (how many times this entity appears in the input), and the confidence associated with the
* extraction.
*
* @param url URL containing the data.
* @return EntitiesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public EntitiesResponse getEntities(URL url)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + ENTITIES_SERVICE_PATH, EntitiesResponse.class);
}
/**
* Returns entities extracted from a string.
* <p>
* The response is a list of extracted entities.
* Each entity includes chain ID (all instances of the same entity share a chain id),
* mention (entity text in the input), normalized text (the most complete form of this entity that appears in
* the input), count (how many times this entity appears in the input), and the confidence associated with the
* extraction.
*
* @param content String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options EntityMention options.
* @return EntitiesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getEntities(String) getEntities}
*/
@Deprecated
public EntitiesResponse getEntities(String content, LanguageCode language, EntitiesOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.options(options)
.build();
return sendPostRequest(request, urlBase + ENTITIES_SERVICE_PATH, EntitiesResponse.class);
}
/**
*Returns entities extracted from a string. Request object built from API rather than from parameters.
* <p>
* The response is a list of extracted entities.
* Each entity includes chain ID (all instances of the same entity share a chain id),
* mention (entity text in the input), normalized text (the most complete form of this entity that appears in
* the input), count (how many times this entity appears in the input), and the confidence associated with the
* extraction.
*
* @param content String containing the data.
* @return EntitiesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public EntitiesResponse getEntities(String content)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + ENTITIES_SERVICE_PATH, EntitiesResponse.class);
}
/**
* Links entities in the input file to entities in the knowledge base (Wikidata).
* The response identifies the entities in the input that have been linked to entities in the knowledge base.
* Each entity includes an entity id (from the knowledge base), a chain id (all instances of the same entity
* share a chain id), the mention (entity text from the input), and confidence associated with the linking.
*
* @param inputStream Input stream of file.
* @param contentType the content type for the file (e.g. text/html).
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return LinkedEntityResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated Merged into {@link #getEntities(String, LanguageCode, EntitiesOptions)}.
*/
@Deprecated
public LinkedEntitiesResponse getLinkedEntities(InputStream inputStream,
String contentType,
LanguageCode language)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.build();
return sendPostRequest(request, urlBase + ENTITIES_LINKED_SERVICE_PATH, LinkedEntitiesResponse.class);
}
/**
* Links entities in the URL content to entities in the knowledge base (Wikidata).
* The response identifies the entities in the input that have been linked to entities in the knowledge base.
* Each entity includes an entity id (from the knowledge base), a chain id (all instances of the same entity
* share a chain id), the mention (entity text from the input), and confidence associated with the linking.
*
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return LinkedEntityResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated Merged into {@link #getEntities(InputStream, String, LanguageCode, EntitiesOptions)}
*/
@Deprecated
public LinkedEntitiesResponse getLinkedEntities(URL url, LanguageCode language)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.build();
return sendPostRequest(request, urlBase + ENTITIES_LINKED_SERVICE_PATH, LinkedEntitiesResponse.class);
}
/**
* Links entities in a string to entities in the knowledge base (Wikidata).
* The response identifies the entities in the input that have been linked to entities in the knowledge base.
* Each entity includes an entity id (from the knowledge base), a chain id (all instances of the same entity
* share a chain id), the mention (entity text from the input), and confidence associated with the linking.
*
* @param content String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return LinkedEntityResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
@SuppressWarnings("deprecation")
public LinkedEntitiesResponse getLinkedEntities(String content, LanguageCode language)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.build();
return sendPostRequest(request, urlBase + ENTITIES_LINKED_SERVICE_PATH, LinkedEntitiesResponse.class);
}
/**
* Returns an ordered list of categories identified in the input file. The categories are Tier 1 contextual
* categories defined in the <a href="http://www.iab.net/QAGInitiative/overview/taxonomy">QAG Taxonomy</a>.
* <p>
* The response is the contextual categories identified in the input.
*
* @param inputStream Input stream of file.
* @param contentType the contentType of the file (e.g. text/html).
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options CategoriesOptions.
* @return CategoriesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getCategories(InputStream, String) getCategories}
*/
@Deprecated
public CategoriesResponse getCategories(InputStream inputStream,
String contentType,
LanguageCode language, CategoriesOptions options)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.options(options)
.build();
return sendPostRequest(request, urlBase + CATEGORIES_SERVICE_PATH, CategoriesResponse.class);
}
/**
* Returns an ordered list of categories identified in the input file. The categories are Tier 1 contextual
* categories defined in the <a href="http://www.iab.net/QAGInitiative/overview/taxonomy">QAG Taxonomy</a>.
* The request object is built from the API object rather than from the parameters.
* <p>
* The response is the contextual categories identified in the input.
* @param inputStream Input stream of file.
* @param contentType The contentType of the file (e.g. text/html)
* @return CategoriesResponse
* @throws RosetteAPIException
* @throws IOException
*/
public CategoriesResponse getCategories(InputStream inputStream,
String contentType)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + CATEGORIES_SERVICE_PATH, CategoriesResponse.class);
}
/**
* Returns an ordered list of categories identified in the URL content. The categories are Tier 1 contextual
* categories defined in the <a href="http://www.iab.net/QAGInitiative/overview/taxonomy">QAG Taxonomy</a>.
* <p>
* The response is the contextual categories identified in the input.
*
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options CategoriesOptions.
* @return CategoriesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated Replaced by {@link #getCategories(URL) getCategories}
*/
@Deprecated
public CategoriesResponse getCategories(URL url, LanguageCode language, CategoriesOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.options(options)
.build();
return sendPostRequest(request, urlBase + CATEGORIES_SERVICE_PATH, CategoriesResponse.class);
}
/**
* Returns an ordered list of categories identified in the input file. The categories are Tier 1 contextual
* categories defined in the <a href="http://www.iab.net/QAGInitiative/overview/taxonomy">QAG Taxonomy</a>.
* The request object is built from the API object rather than from the parameters.
* <p>
* The response is the contextual categories identified in the input.
*
* @param url URL containing the data.
* @return CategoriesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public CategoriesResponse getCategories(URL url)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + CATEGORIES_SERVICE_PATH, CategoriesResponse.class);
}
/**
* Returns an ordered list of categories identified in a string. The categories are Tier 1 contextual
* categories defined in the <a href="http://www.iab.net/QAGInitiative/overview/taxonomy">QAG Taxonomy</a>.
* <p>
* The response is the contextual categories identified in the input.
*
* @param content String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options CategoriesOptions.
* @return CategoriesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getCategories(String) getCategories}
*/
@Deprecated
public CategoriesResponse getCategories(String content, LanguageCode language, CategoriesOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.options(options)
.build();
return sendPostRequest(request, urlBase + CATEGORIES_SERVICE_PATH, CategoriesResponse.class);
}
/**
* Returns an ordered list of categories identified in the input file. The categories are Tier 1 contextual
* categories defined in the <a href="http://www.iab.net/QAGInitiative/overview/taxonomy">QAG Taxonomy</a>.
* The request object is built from the API object rather than from the parameters.
* <p>
* The response is the contextual categories identified in the input.
*
* @param content String containing the data.
* @return CategoriesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a problem with communication or JSON serialization/deserialization.
*/
public CategoriesResponse getCategories(String content)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + CATEGORIES_SERVICE_PATH, CategoriesResponse.class);
}
/**
* Returns each relationship extracted from the input.
* <p>
* The response is a list of extracted relationships. A relationship contains
* <p>
* predicate - usually the main verb, property or action that is expressed by the text
* arg1 - usually the subject, agent or main actor of the relationship
* arg2 [optional] - complements the predicate and is usually the object, theme or patient of the relationship
* arg3 [optional] - usually an additional object in ditransitive verbs
* adjuncts [optional] - contain all optional parts of a relationship which are not temporal or locative expressions
* locatives [optional] - usually express the locations the action expressed by the relationship took place
* temporals [ optional] - usually express the time in which the action expressed by the relationship took place
* confidence - a measure of quality of relationship extraction, between 0 - 1
*
* @param content, String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options RelationshipOptions
* @return RelationshipsResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getRelationships(String) getRelationships}
*/
@Deprecated
public RelationshipsResponse getRelationships(String content, LanguageCode language, RelationshipsOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.options(options)
.build();
return sendPostRequest(request, urlBase + RELATIONSHIPS_SERVICE_PATH, RelationshipsResponse.class);
}
/**
* Returns each relationship extracted from the input. Request object uses API attributes rather than parameters.
* <p>
* The response is a list of extracted relationships. A relationship contains
* <p>
* predicate - usually the main verb, property or action that is expressed by the text
* arg1 - usually the subject, agent or main actor of the relationship
* arg2 [optional] - complements the predicate and is usually the object, theme or patient of the relationship
* arg3 [optional] - usually an additional object in ditransitive verbs
* adjuncts [optional] - contain all optional parts of a relationship which are not temporal or locative expressions
* locatives [optional] - usually express the locations the action expressed by the relationship took place
* temporals [ optional] - usually express the time in which the action expressed by the relationship took place
* confidence - a measure of quality of relationship extraction, between 0 - 1
* @param content String containing the data.
* @return RelationshipsResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public RelationshipsResponse getRelationships(String content)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + RELATIONSHIPS_SERVICE_PATH, RelationshipsResponse.class);
}
/**
* Returns each relationship extracted from the input.
* <p>
* The response is a list of extracted relationships. A relationship contains
* <p>
* predicate - usually the main verb, property or action that is expressed by the text
* arg1 - usually the subject, agent or main actor of the relationship
* arg2 [optional] - complements the predicate and is usually the object, theme or patient of the relationship
* arg3 [optional] - usually an additional object in ditransitive verbs
* adjuncts [optional] - contain all optional parts of a relationship which are not temporal or locative expressions
* locatives [optional] - usually express the locations the action expressed by the relationship took place
* temporals [ optional] - usually express the time in which the action expressed by the relationship took place
* confidence - a measure of quality of relationship extraction, between 0 - 1
*
* @param inputStream Input stream of file.
* @param contentType the content type of the file.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options RelationshipOptions
* @return RelationshipsResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request
* @throws IOException - If there is a communication or JSON serialization/deserialization error
*
* @deprecated Replaced by {@link #getRelationships(InputStream, String) getRelationships}
*/
@Deprecated
public RelationshipsResponse getRelationships(InputStream inputStream,
String contentType,
LanguageCode language, RelationshipsOptions options)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.options(options)
.build();
return sendPostRequest(request, urlBase + RELATIONSHIPS_SERVICE_PATH, RelationshipsResponse.class);
}
/**
* Returns each relationship extracted from the input. Request object uses API attributes rather than parameters.
* <p>
* The response is a list of extracted relationships. A relationship contains
* <p>
* predicate - usually the main verb, property or action that is expressed by the text
* arg1 - usually the subject, agent or main actor of the relationship
* arg2 [optional] - complements the predicate and is usually the object, theme or patient of the relationship
* arg3 [optional] - usually an additional object in ditransitive verbs
* adjuncts [optional] - contain all optional parts of a relationship which are not temporal or locative expressions
* locatives [optional] - usually express the locations the action expressed by the relationship took place
* temporals [ optional] - usually express the time in which the action expressed by the relationship took place
* confidence - a measure of quality of relationship extraction, between 0 - 1
* @param inputStream Input stream of file.
* @param contentType The content type of the file.
* @return RelationshipsResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public RelationshipsResponse getRelationships(InputStream inputStream,
String contentType)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + RELATIONSHIPS_SERVICE_PATH, RelationshipsResponse.class);
}
/**
* Returns each relationship extracted from the input.
* <p>
* The response is a list of extracted relationships. A relationship contains
* <p>
* predicate - usually the main verb, property or action that is expressed by the text
* arg1 - usually the subject, agent or main actor of the relationship
* arg2 [optional] - complements the predicate and is usually the object, theme or patient of the relationship
* arg3 [optional] - usually an additional object in ditransitive verbs
* adjuncts [optional] - contain all optional parts of a relationship which are not temporal or locative expressions
* locatives [optional] - usually express the locations the action expressed by the relationship took place
* temporals [ optional] - usually express the time in which the action expressed by the relationship took place
* confidence - a measure of quality of relationship extraction, between 0 - 1
*
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options RelationshipOptions
* @return RelationshipsResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request
* @throws IOException - If there is a communication or JSON serialization/deserialization error
*
* @deprecated replaced {@link #getRelationships(URL) getRelationships}
*/
@Deprecated
public RelationshipsResponse getRelationships(URL url, LanguageCode language, RelationshipsOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.options(options)
.build();
return sendPostRequest(request, urlBase + RELATIONSHIPS_SERVICE_PATH, RelationshipsResponse.class);
}
/**
* Returns each relationship extracted from the input.
* <p>
* The response is a list of extracted relationships. A relationship contains
* <p>
* predicate - usually the main verb, property or action that is expressed by the text
* arg1 - usually the subject, agent or main actor of the relationship
* arg2 [optional] - complements the predicate and is usually the object, theme or patient of the relationship
* arg3 [optional] - usually an additional object in ditransitive verbs
* adjuncts [optional] - contain all optional parts of a relationship which are not temporal or locative expressions
* locatives [optional] - usually express the locations the action expressed by the relationship took place
* temporals [ optional] - usually express the time in which the action expressed by the relationship took place
* confidence - a measure of quality of relationship extraction, between 0 - 1
*
* @param url URL containing the data.
* @return RelationshipOptions
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a problem with communication or JSON serialization/deserialization.
*/
public RelationshipsResponse getRelationships(URL url)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + RELATIONSHIPS_SERVICE_PATH, RelationshipsResponse.class);
}
/**
* Analyzes the positive and negative sentiment expressed by the input.
* <p>
* The response contains sentiment analysis results.
*
* @param inputStream Input stream of file.
* @param contentType the content type of the file (e.g. text/html)
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options SentimentOptions.
* @return SentimentResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getSentiment(InputStream, String) getSentiment}
*/
@Deprecated
public SentimentResponse getSentiment(InputStream inputStream,
String contentType,
LanguageCode language, SentimentOptions options)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.options(options)
.build();
return sendPostRequest(request, urlBase + SENTIMENT_SERVICE_PATH, SentimentResponse.class);
}
/**
* Analyzes the positive and negative sentiment expressed by the input. Request object built from API rather than
* from individual request.
* <p>
* The response contains sentiment analysis results.
*
* @param inputStream Input stream of file.
* @param contentType The content type of the file (e.g. text/html)
* @return SentimentResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public SentimentResponse getSentiment(InputStream inputStream,
String contentType)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + SENTIMENT_SERVICE_PATH, SentimentResponse.class);
}
/**
* Analyzes the positive and negative sentiment expressed by the input.
* <p>
* The response contains sentiment analysis results.
*
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options SentimentOptions.
* @return SentimentResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getSentiment(URL) getSentiment}
*/
@Deprecated
public SentimentResponse getSentiment(URL url, LanguageCode language, SentimentOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.options(options)
.build();
return sendPostRequest(request, urlBase + SENTIMENT_SERVICE_PATH, SentimentResponse.class);
}
/**
* Analyzes the positive and negative sentiment expressed by the input. Request object built from API rather than
* from individual request.
* <p>
* The response contains sentiment analysis results.
*
* @param url URL containing the data.
* @return SentimentOptions
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public SentimentResponse getSentiment(URL url)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + SENTIMENT_SERVICE_PATH, SentimentResponse.class);
}
/**
* Analyzes the positive and negative sentiment expressed by the input.
* <p>
* The response contains sentiment analysis results.
*
* @param content String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options SentimentOptions.
* @return SentimentResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getSentiment(String) getSentiment}
*/
@Deprecated
public SentimentResponse getSentiment(String content, LanguageCode language, SentimentOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.options(options)
.build();
return sendPostRequest(request, urlBase + SENTIMENT_SERVICE_PATH, SentimentResponse.class);
}
/**
* Analyzes the positive and negative sentiment expressed by the input. Request object uses API object rather than
* parameters.
* <p>
* The response contains sentiment analysis results.
*
* @param content String containing the data.
* @return SentimentOptions
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public SentimentResponse getSentiment(String content)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + SENTIMENT_SERVICE_PATH, SentimentResponse.class);
}
/**
* Divides the input into tokens.
*
* @param inputStream Input stream of file.
* @param contentType the content type of the file (e.g. text/html)
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return The response contains a list of tokens.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getTokens(InputStream, String) getTokens}
*/
@Deprecated
public TokensResponse getTokens(InputStream inputStream, String contentType, LanguageCode language)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.build();
return sendPostRequest(request, urlBase + TOKENS_SERVICE_PATH, TokensResponse.class);
}
/**
* Divides the input into tokens. Request object built through API calls rather than from parameters.
*
* @param inputStream Input stream of file.
* @param contentType The content type of the file (e.g. text/html)
*
* @return The response contains a list of tokens.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a problem with communication or JSON serialization/deserialization
*/
public TokensResponse getTokens(InputStream inputStream, String contentType)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + TOKENS_SERVICE_PATH, TokensResponse.class);
}
/**
* Divides the input into tokens.
*
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return The response contains a list of tokens.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getTokens(URL) getTokens}
*/
@Deprecated
public TokensResponse getTokens(URL url, LanguageCode language) throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.build();
return sendPostRequest(request, urlBase + TOKENS_SERVICE_PATH, TokensResponse.class);
}
/**
* Divides the input into tokens. Request object uses API fields rather than call parameters.
*
* @param url URL containing the data.
* @return The response contains a list of tokens.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public TokensResponse getTokens(URL url) throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + TOKENS_SERVICE_PATH, TokensResponse.class);
}
/**
* Divides the input into tokens.
*
* @param content String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return The response contains a list of tokens.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getTokens(String) getTokens}
*/
@Deprecated
public TokensResponse getTokens(String content, LanguageCode language) throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.build();
return sendPostRequest(request, urlBase + TOKENS_SERVICE_PATH, TokensResponse.class);
}
/**
* Divides the input into tokens. Request object is built from the API object rather than from parameters.
*
* @param content String containing the data.
* @return The response contains a list of tokens.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public TokensResponse getTokens(String content) throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + TOKENS_SERVICE_PATH, TokensResponse.class);
}
/**
* Divides the input into sentences.
*
* @param inputStream Input stream of file.
* @param contentType the content type of the file (e.g. text/html).
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return The response contains a list of sentences.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getSentences(InputStream, String) getSentences}
*/
@Deprecated
public SentencesResponse getSentences(InputStream inputStream,
String contentType,
LanguageCode language)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.build();
return sendPostRequest(request, urlBase + SENTENCES_SERVICE_PATH, SentencesResponse.class);
}
/**
* Divides the input into sentences. Request object is built from the API object rather than from parameters.
*
* @param inputStream Input stream of file.
* @param contentType The content type of the file (e.g. text/html).
* @return The response contains a list of sentences.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a problem with communication or JSON serialization/deserialization.
*/
public SentencesResponse getSentences(InputStream inputStream,
String contentType)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + SENTENCES_SERVICE_PATH, SentencesResponse.class);
}
/**
* Divides the input into sentences.
*
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return The response contains a list of sentences.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getSentences(URL) getSentences}
*/
@Deprecated
public SentencesResponse getSentences(URL url, LanguageCode language) throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.build();
return sendPostRequest(request, urlBase + SENTENCES_SERVICE_PATH, SentencesResponse.class);
}
/**
* Divides the input into sentences. Request object is built from the API object rather than from parameters.
*
* @param url URL containing the data.
* @return The response contains a list of sentences.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication of JSON serialization/deserialization error.
*/
public SentencesResponse getSentences(URL url) throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + SENTENCES_SERVICE_PATH, SentencesResponse.class);
}
/**
* Divides the input into sentences.
*
* @param content String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return The response contains a list of sentences.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getSentences(String) getSentences}
*/
@Deprecated
public SentencesResponse getSentences(String content, LanguageCode language)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.build();
return sendPostRequest(request, urlBase + SENTENCES_SERVICE_PATH, SentencesResponse.class);
}
/**
* Divides the input into sentences. Request object is built from the API object rather than from parameters.
*
* @param content String containing the data.
* @return The response contains a list of sentences.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public SentencesResponse getSentences(String content)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + SENTENCES_SERVICE_PATH, SentencesResponse.class);
}
/**
* Provides information on Rosette API
*
* @return {@link com.basistech.rosette.apimodel.InfoResponse InfoResponse}
* @throws RosetteAPIException Rosette specific exception
* @throws IOException General IO exception
*/
public InfoResponse getInfo() throws RosetteAPIException, IOException {
return sendGetRequest(urlBase + INFO_SERVICE_PATH, InfoResponse.class);
}
/**
* Send a request to the API, return a response (or throw an exception).
* Use this method for request parameter combinations that are not covered
* by the specific endpoint methods.
* @param endpoint The endpoint, for example, '/entities'.
* @param request The request object.
* @param responseClass The class of the response object corresponding to the request object.
* @param <Req> the request type.
* @param <Res> the response type.
* @return the response.
* @throws IOException for errors in communications.
* @throws RosetteAPIException for errors returned by the API.
*/
public <Req extends Request, Res extends Response> Res doRequest(String endpoint, Req request, Class<Res> responseClass)
throws IOException, RosetteAPIException {
return sendPostRequest(request, urlBase + endpoint, responseClass);
}
/**
* Sends a GET request to Rosette API.
* <p>
* Returns a Response.
*
* @param urlStr Rosette API end point.
* @param clazz Response class
* @return Response
* @throws IOException
* @throws RosetteAPIException
*/
private <T extends Response> T sendGetRequest(String urlStr, Class<T> clazz) throws IOException, RosetteAPIException {
HttpGet get = new HttpGet(urlStr);
HttpResponse httpResponse = httpClient.execute(get);
T resp = getResponse(httpResponse, clazz);
responseHeadersToExtendedInformation(resp, httpResponse);
return resp;
}
/**
* Sends a POST request to Rosette API.
* <p>
* Returns a Response.
*
* @param urlStr Rosette API end point.
* @param clazz Response class
* @return Response
* @throws RosetteAPIException
* @throws IOException
*/
private <T extends Response> T sendPostRequest(Object request, String urlStr, Class<T> clazz)
throws RosetteAPIException, IOException {
ObjectWriter writer = mapper.writer().without(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
boolean notPlainText = false;
if (request instanceof DocumentRequest) {
Object rawContent = ((DocumentRequest) request).getRawContent();
if (rawContent instanceof String) {
writer = writer.withView(DocumentRequestMixin.Views.Content.class);
} else if (rawContent != null) {
notPlainText = true;
}
}
final ObjectWriter finalWriter = writer;
HttpPost post = new HttpPost(urlStr);
//TODO: add compression!
if (notPlainText) {
setupMultipartRequest((DocumentRequest) request, finalWriter, post);
} else {
setupPlainRequest(request, finalWriter, post);
}
RosetteAPIException lastException = null;
int numRetries = this.failureRetries;
while (numRetries-- > 0) {
HttpResponse response = null;
try {
response = httpClient.execute(post);
T resp = getResponse(response, clazz);
Header ridHeader = response.getFirstHeader("X-RosetteAPI-DocumentRequest-Id");
if (ridHeader != null && ridHeader.getValue() != null) {
LOG.debug("DocumentRequest ID " + ridHeader.getValue());
}
responseHeadersToExtendedInformation(resp, response);
return resp;
} catch (RosetteAPIException e) {
// only 5xx errors are worthy retrying, others throw right away
if (e.getHttpStatusCode() < 500) {
throw e;
} else {
lastException = e;
}
} finally {
if (response != null) {
if (response instanceof CloseableHttpResponse) {
((CloseableHttpResponse)response).close();
}
}
}
}
throw lastException;
}
@SuppressWarnings("unchecked")
private <T extends Response> void responseHeadersToExtendedInformation(T resp, HttpResponse response) {
for (Header header : response.getAllHeaders()) {
if (resp.getExtendedInformation() != null
&& resp.getExtendedInformation().containsKey(header.getName())) {
Set<Object> currentSetValue;
if (resp.getExtendedInformation().get(header.getName()) instanceof Set) {
currentSetValue = (Set<Object>) resp.getExtendedInformation().get(header.getName());
} else {
currentSetValue = new HashSet<>(Collections.singletonList(resp.getExtendedInformation().get(header.getName())));
}
currentSetValue.add(header.getValue());
resp.setExtendedInformation(header.getName(), currentSetValue);
} else {
resp.setExtendedInformation(header.getName(), header.getValue());
}
}
}
private void setupPlainRequest(final Object request, final ObjectWriter finalWriter, HttpPost post) {
// just posting json.
post.addHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
post.setEntity(new AbstractHttpEntity() {
@Override
public boolean isRepeatable() {
return false;
}
@Override
public long getContentLength() {
return -1;
}
@Override
public InputStream getContent() throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public void writeTo(OutputStream outstream) throws IOException {
finalWriter.writeValue(outstream, request);
}
@Override
public boolean isStreaming() {
return false;
}
});
}
private void setupMultipartRequest(final DocumentRequest request, final ObjectWriter finalWriter, HttpPost post) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMimeSubtype("mixed");
builder.setMode(HttpMultipartMode.STRICT);
FormBodyPartBuilder partBuilder = FormBodyPartBuilder.create("request",
// Make sure we're not mislead by someone who puts a charset into the mime type.
new AbstractContentBody(ContentType.parse(ContentType.APPLICATION_JSON.getMimeType())) {
@Override
public String getFilename() {
return null;
}
@Override
public void writeTo(OutputStream out) throws IOException {
finalWriter.writeValue(out, request);
}
@Override
public String getTransferEncoding() {
return MIME.ENC_BINARY;
}
@Override
public long getContentLength() {
return -1;
}
});
// Either one of 'name=' or 'Content-ID' would be enough.
partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"request\"");
partBuilder.setField("Content-ID", "request");
builder.addPart(partBuilder.build());
partBuilder = FormBodyPartBuilder.create("content", new InputStreamBody(request.getContentBytes(), ContentType.parse(request.getContentType())));
partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"content\"");
partBuilder.setField("Content-ID", "content");
builder.addPart(partBuilder.build());
builder.setCharset(StandardCharsets.UTF_8);
HttpEntity entity = builder.build();
post.setEntity(entity);
}
private String headerValueOrNull(Header header) {
if (header == null) {
return null;
} else {
return header.getValue();
}
}
/**
* Gets response from HTTP connection, according to the specified response class;
* throws for an error response.
*
* @param httpResponse the response object
* @param clazz Response class
* @return Response
* @throws IOException
* @throws RosetteAPIException if the status is not 200.
*/
private <T extends Response> T getResponse(HttpResponse httpResponse, Class<T> clazz)
throws IOException, RosetteAPIException {
int status = httpResponse.getStatusLine().getStatusCode();
String encoding = headerValueOrNull(httpResponse.getFirstHeader(HttpHeaders.CONTENT_ENCODING));
String connectionConcurrency = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteApi-Concurrency"));
if (connectionConcurrency != null) {
try {
int concurrencyHeader = Integer.parseInt(connectionConcurrency);
if (concurrencyHeader <= 0) {
LOG.warn(String.format("Non positive concurrency value received (%s), setting to 1", Integer.toString(concurrencyHeader)));
concurrencyHeader = 1;
} else if (concurrencyHeader > 100) {
LOG.warn(String.format("Concurrency max value 100, received %s, setting to 100", Integer.toString(concurrencyHeader)));
concurrencyHeader = 100;
}
if (allowSocketChange&& concurrencyHeader != maxSockets) {
maxSockets = concurrencyHeader;
initHttpClient();
}
} catch (NumberFormatException e) {
LOG.error(String.format("Error converting X-RosetteApi-Concurrency (%s) to a number", connectionConcurrency));
}
}
try (
InputStream stream = httpResponse.getEntity().getContent();
InputStream inputStream = "gzip".equalsIgnoreCase(encoding) ? new GZIPInputStream(stream) : stream) {
String ridHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-DocumentRequest-Id"));
if (HTTP_OK != status) {
String ecHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-Status-Code"));
String emHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-Status-Message"));
String responseContentType = headerValueOrNull(httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE));
if ("application/json".equals(responseContentType)) {
ErrorResponse errorResponse = mapper.readValue(inputStream, ErrorResponse.class);
if (ridHeader != null) {
LOG.debug("DocumentRequest ID " + ridHeader);
}
if (ecHeader != null) {
errorResponse.setCode(ecHeader);
}
if (emHeader != null) {
errorResponse.setMessage(emHeader);
}
throw new RosetteAPIException(status, errorResponse);
} else {
String errorContent;
if (inputStream != null) {
byte[] content = getBytes(inputStream);
errorContent = new String(content, "utf-8");
} else {
errorContent = "(no body)";
}
// something not from us at al
throw new RosetteAPIException(status, new ErrorResponse("invalidErrorResponse", errorContent));
}
} else {
return mapper.readValue(inputStream, clazz);
}
}
}
/**
* Returns a byte array from InputStream.
*
* @param is InputStream
* @return byte array
* @throws IOException
*/
private static byte[] getBytes(InputStream is) throws IOException {
return ByteStreams.toByteArray(is);
}
@Override
public void close() throws IOException {
if (httpClient instanceof CloseableHttpClient) {
((CloseableHttpClient)httpClient).close();
}
}
private DocumentRequest.BaseBuilder getDocumentRequestBuilder() throws IOException {
return new DocumentRequest.Builder()
.language(language)
.genre(genre)
.options(options);
}
/**
* Builder class for the RosetteAPI object.
*/
public static class Builder {
protected LanguageCode language;
protected String genre;
protected Options options;
protected String key;
protected String urlBase = DEFAULT_URL_BASE;
protected int failureRetries = 1;
protected HttpClient httpClient;
protected Builder getThis() {
return this;
}
/**
* Set the language of the input.
* @param language the language.
* @return this
*/
public Builder language(LanguageCode language) {
this.language = language;
return getThis();
}
/**
* Set the options for this request.
* @param options the options.
* @return this
*/
public Builder options(Options options) {
this.options = options;
return getThis();
}
/**
* Set the genre of the request.
* @param genre genre (ex: social-media)
* @return this
*/
public Builder genre(String genre) {
this.genre = genre;
return getThis();
}
/**
* Set the apiKey for the requests
* @param key apiKey
* @return this
*/
public Builder apiKey(String key) {
this.key = key;
return getThis();
}
/**
* Sets an alternative url for testing purposes
* @param url alternative url
* @return this
*/
public Builder alternateUrl(String url) {
if (url != null) {
this.urlBase = url;
}
return getThis();
}
/**
* Set failure retries, default 1
* @param retries number of retries
* @return this
*/
public Builder failureRetries(int retries) {
this.failureRetries = retries;
return getThis();
}
/**
* User can provide their own http client
* @param client CloseableHttpClient
* @return this
*/
public Builder httpClient(HttpClient client) {
this.httpClient = client;
return getThis();
}
/**
* Construct the api object.
* @return the api object.
*/
public RosetteAPI build() throws IOException, RosetteAPIException {
return new RosetteAPI(key, urlBase, failureRetries, language, genre, options, httpClient);
}
}
}
|
api/src/main/java/com/basistech/rosette/api/RosetteAPI.java
|
/*
* Copyright 2014 Basis Technology Corp.
*
* 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.basistech.rosette.api;
import com.basistech.rosette.apimodel.CategoriesOptions;
import com.basistech.rosette.apimodel.CategoriesResponse;
import com.basistech.rosette.apimodel.DocumentRequest;
import com.basistech.rosette.apimodel.EntitiesOptions;
import com.basistech.rosette.apimodel.EntitiesResponse;
import com.basistech.rosette.apimodel.ErrorResponse;
import com.basistech.rosette.apimodel.InfoResponse;
import com.basistech.rosette.apimodel.LanguageOptions;
import com.basistech.rosette.apimodel.LanguageResponse;
import com.basistech.rosette.apimodel.LinkedEntitiesResponse;
import com.basistech.rosette.apimodel.MorphologyOptions;
import com.basistech.rosette.apimodel.MorphologyResponse;
import com.basistech.rosette.apimodel.Name;
import com.basistech.rosette.apimodel.NameSimilarityRequest;
import com.basistech.rosette.apimodel.NameSimilarityResponse;
import com.basistech.rosette.apimodel.NameTranslationRequest;
import com.basistech.rosette.apimodel.NameTranslationResponse;
import com.basistech.rosette.apimodel.Options;
import com.basistech.rosette.apimodel.PingResponse;
import com.basistech.rosette.apimodel.RelationshipsOptions;
import com.basistech.rosette.apimodel.RelationshipsResponse;
import com.basistech.rosette.apimodel.Request;
import com.basistech.rosette.apimodel.Response;
import com.basistech.rosette.apimodel.SentencesResponse;
import com.basistech.rosette.apimodel.SentimentOptions;
import com.basistech.rosette.apimodel.SentimentResponse;
import com.basistech.rosette.apimodel.TokensResponse;
import com.basistech.rosette.apimodel.jackson.ApiModelMixinModule;
import com.basistech.rosette.apimodel.jackson.DocumentRequestMixin;
import com.basistech.util.LanguageCode;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.io.ByteStreams;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.annotation.Immutable;
import org.apache.http.annotation.ThreadSafe;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.FormBodyPartBuilder;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MIME;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.AbstractContentBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import static java.net.HttpURLConnection.HTTP_OK;
/**
* You can use the RosetteAPI to access Rosette API endpoints.
* RosetteAPI is thread-safe and immutable.
*/
@Immutable
@ThreadSafe
public class RosetteAPI implements Closeable {
public static final String DEFAULT_URL_BASE = "https://api.rosette.com/rest/v1";
public static final String SERVICE_NAME = "RosetteAPI";
public static final String BINDING_VERSION = getVersion();
public static final String USER_AGENT_STR = SERVICE_NAME + "-Java/" + BINDING_VERSION;
public static final String LANGUAGE_SERVICE_PATH = "/language";
public static final String MORPHOLOGY_SERVICE_PATH = "/morphology";
public static final String ENTITIES_SERVICE_PATH = "/entities";
/**
* @deprecated merged into the {@link #ENTITIES_SERVICE_PATH}.
*/
@Deprecated
public static final String ENTITIES_LINKED_SERVICE_PATH = "/entities/linked";
public static final String CATEGORIES_SERVICE_PATH = "/categories";
public static final String RELATIONSHIPS_SERVICE_PATH = "/relationships";
public static final String SENTIMENT_SERVICE_PATH = "/sentiment";
public static final String NAME_TRANSLATION_SERVICE_PATH = "/name-translation";
public static final String NAME_SIMILARITY_SERVICE_PATH = "/name-similarity";
public static final String TOKENS_SERVICE_PATH = "/tokens";
public static final String SENTENCES_SERVICE_PATH = "/sentences";
public static final String INFO_SERVICE_PATH = "/info";
public static final String PING_SERVICE_PATH = "/ping";
private static final Logger LOG = LoggerFactory.getLogger(RosetteAPI.class);
private String key;
private String urlBase = DEFAULT_URL_BASE;
private int failureRetries;
private LanguageCode language;
private Options options;
private String genre;
private ObjectMapper mapper;
private HttpClient httpClient;
private List<Header> customHeaders;
private int maxSockets = 1;
// set in initHttpClient. We don't mess with a user-specified client.
private boolean allowSocketChange;
/**
* Constructs a Rosette API instance using an API key.
*
* @param key Rosette API key
* @throws RosetteAPIException If the service is not compatible with the version of the binding.
* @throws IOException General IO exception
*
* @deprecated use RosetteAPI.Builder class
*/
@Deprecated
public RosetteAPI(String key) throws IOException, RosetteAPIException {
this(key, DEFAULT_URL_BASE);
}
/**
* Constructs a Rosette API instance using an API key and accepts an
* alternate URL for testing purposes.
*
* @param key Rosette API key
* @param alternateUrl Alternate Rosette API URL
* @throws RosetteAPIException If the service is not compatible with the version of the binding.
* @throws IOException General IO exception
*
* @deprecated use RosetteAPI.Builder class
*/
@Deprecated
public RosetteAPI(String key, String alternateUrl) throws IOException, RosetteAPIException {
Objects.requireNonNull(alternateUrl, "alternateUrl cannot be null");
this.key = key;
urlBase = alternateUrl;
if (urlBase.endsWith("/")) {
urlBase = urlBase.substring(0, urlBase.length() - 1);
}
this.failureRetries = 1;
mapper = ApiModelMixinModule.setupObjectMapper(new ObjectMapper());
customHeaders = new ArrayList<>();
initHttpClient();
}
/**
* Constructs a Rosette API instance using the builder syntax.
*
* @param key Rosette API key
* @param urlToCall Alternate Rosette API URL
* @param failureRetries Number of times to retry in case of failure; default 1
* @param language source language
* @param genre genre (ex "social-media")
* @param options options for the request
* @throws IOException General IO exception
* @throws RosetteAPIException Problem with the API request
*/
private RosetteAPI(String key, String urlToCall, int failureRetries,
LanguageCode language, String genre, Options options,
HttpClient httpClient)
throws IOException, RosetteAPIException {
this.key = key;
this.language = language;
this.genre = genre;
this.options = options;
urlBase = urlToCall.trim().replaceAll("/+$", "");
this.failureRetries = failureRetries;
mapper = ApiModelMixinModule.setupObjectMapper(new ObjectMapper());
customHeaders = new ArrayList<>();
setUpHttpClient(httpClient);
}
/**
* @param httpClient user provided http client
* @throws IOException
*/
private void setUpHttpClient(HttpClient httpClient) throws IOException {
if (httpClient == null) {
initHttpClient();
} else {
allowSocketChange = false;
this.httpClient = httpClient;
}
HttpResponse response = this.httpClient.execute(new HttpPost(urlBase));
if (response != null) {
if (response instanceof CloseableHttpResponse) {
((CloseableHttpResponse)response).close();
}
}
}
/**
* Returns the version of the binding.
*
* @return version of the binding
*/
private static String getVersion() {
Properties properties = new Properties();
try (InputStream ins = RosetteAPI.class.getClassLoader().getResourceAsStream("version.properties")) {
properties.load(ins);
} catch (IOException e) {
// should not happen
}
return properties.getProperty("version", "undefined");
}
/**
* Return failure retries.
*
* @return failure retries
*/
public int getFailureRetries() {
return failureRetries;
}
/**
* Return language code.
*
* @return source language
*/
public LanguageCode getLanguageCode() {
return language;
}
/**
* Returns the genre.
*
* @return genre if being used by API
*/
public String getGenre() {
return genre;
}
/**
* Returns options used by API.
*
* @return options
*/
public Options getOptions() {
return options;
}
/**
*
*/
private void initHttpClient() {
List<Header> defaultHeaders = new ArrayList<>();
defaultHeaders.add(new BasicHeader(HttpHeaders.USER_AGENT, USER_AGENT_STR));
defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "gzip"));
if (key != null) {
defaultHeaders.add(new BasicHeader("X-RosetteAPI-Key", key));
defaultHeaders.add(new BasicHeader("X-RosetteAPI-Binding", "java"));
defaultHeaders.add(new BasicHeader("X-RosetteAPI-Binding-Version", BINDING_VERSION));
}
if (customHeaders.size() > 0) {
defaultHeaders.addAll(customHeaders);
}
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(maxSockets);
httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultHeaders(defaultHeaders).build();
allowSocketChange = true;
}
/**
* Add a custom HTTP header to pass to Rosette API.
*
* @param name header name
* @param value header value
*/
public void addCustomHeader(String name, String value) {
addCustomHeader(new BasicHeader(name, value));
}
/**
* Add a custom HTTP header to pass to Rosette API.
*
* @param header header
*/
public void addCustomHeader(Header header) {
customHeaders.add(header);
initHttpClient();
}
/**
* Gets information about the Rosette API, returns name, version, build number and build time.
*
* @return InfoResponse
* @throws RosetteAPIException Rosette specific exception
* @throws IOException General IO exception
*/
public InfoResponse info() throws IOException, RosetteAPIException {
return sendGetRequest(urlBase + INFO_SERVICE_PATH, InfoResponse.class);
}
/**
* Pings the Rosette API for a response indicting that the service is available.
*
* @return PingResponse
* @throws RosetteAPIException Rosette specific exception
* @throws IOException General IO exception
*/
public PingResponse ping() throws IOException, RosetteAPIException {
return sendGetRequest(urlBase + PING_SERVICE_PATH, PingResponse.class);
}
/**
* Matches 2 names and returns a score in NameMatchingResponse.
*
* @param request request
* @return response
* @throws RosetteAPIException Rosette specific exception
* @throws IOException General IO exception
*
* @deprecated replaced by {@link #getNameSimilarity(Name, Name) getNameSimilarity}
*/
@Deprecated
public NameSimilarityResponse getNameSimilarity(NameSimilarityRequest request) throws RosetteAPIException, IOException {
return getNameSimilarity(request.getName1(), request.getName2());
}
/**
* Matches 2 names and returns a score in NameMatchingResponse.
*
* @param nameOne first name
* @param nameTwo second name
* @return response
* @throws RosetteAPIException Rosette specific exception
* @throws IOException General IO exception
*/
public NameSimilarityResponse getNameSimilarity(Name nameOne, Name nameTwo) throws RosetteAPIException, IOException {
NameSimilarityRequest request = new NameSimilarityRequest(nameOne, nameTwo);
return sendPostRequest(request, urlBase + NAME_SIMILARITY_SERVICE_PATH, NameSimilarityResponse.class);
}
/**
* Translates a name into the target language specified in NameTranslationRequest.
*
* @param request NameTranslationRequest contains the name to be translated and the target language.
* @return the response.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public NameTranslationResponse getNameTranslation(NameTranslationRequest request)
throws RosetteAPIException, IOException {
return sendPostRequest(request, urlBase + NAME_TRANSLATION_SERVICE_PATH, NameTranslationResponse.class);
}
/**
* Performs language identification on data read from an InputStream. Return a list of languages.
*
* @param inputStream Input stream of file.
* @param contentType the content type (e.g. text/html)
* @param options Options to Language API.
* @return An ordered list of detected languages, including language and detection confidence, sorted by
* descending confidence.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated Replaced by {@link #getLanguage(InputStream, String) getLanguage}
*/
@Deprecated
public LanguageResponse getLanguage(InputStream inputStream, String contentType, LanguageOptions options)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder().contentBytes(bytes, contentType)
.options(options).build();
return sendPostRequest(request, urlBase + LANGUAGE_SERVICE_PATH, LanguageResponse.class);
}
/**
* Performs language identification on data from an InputSteam. Builds request object from API, not parameters.
* Returns a list of languages.
*
* @param inputStream Input stream of file
* @param contentType the content type (e.g. text/html)
*
* @return An ordered list of detected languages, including language and detection confidence, sorted by
* descending confidence.
* @throws RosetteAPIException - There's a problem with the Rosette API request
* @throws IOException - There's a problem with communication or JSON serialization/deserialization
*/
public LanguageResponse getLanguage(InputStream inputStream, String contentType) throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + LANGUAGE_SERVICE_PATH, LanguageResponse.class);
}
/**
* Performs language identification on data read from an URL. Return a list of languages.
*
* @param url URL for language detection.
* @param options Options to Language API.
* @return An ordered list of detected languages, including language and detection confidence, sorted by
* descending confidence.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated Replaced by {@link #getLanguage(URL) getLanguage}
*/
@Deprecated
public LanguageResponse getLanguage(URL url, LanguageOptions options) throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.contentUri(url.toString())
.options(options)
.build();
return sendPostRequest(request, urlBase + LANGUAGE_SERVICE_PATH, LanguageResponse.class);
}
/**
* Performs language identification on data read from an URL. Builds request object from API, not parameters.
* Returns a list of languages.
*
* @param url URL for language detection
* @return An ordered list of detected languages, including language and detection confidence, sorted by
* descending confidence.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public LanguageResponse getLanguage(URL url) throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + LANGUAGE_SERVICE_PATH, LanguageResponse.class);
}
/**
* Performs language identification on data read from a string. Return a list of languages.
*
* @param content String content for language detection.
* @param options Options to Language API.
* @return An ordered list of detected languages, including language and detection confidence, sorted by
* descending confidence.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated Replaced by {@link #getLanguage(String) getLanguage}
*/
@Deprecated
public LanguageResponse getLanguage(String content, LanguageOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder().content(content)
.options(options).build();
return sendPostRequest(request, urlBase + LANGUAGE_SERVICE_PATH, LanguageResponse.class);
}
/**
* Performs language identification on data read from a string. Builds request object from API not parameters.
* Returns a list of languages.
*
* @param content String content for language detection.
*
* @return An ordered list of detected languages, including language and detection confidence, sorted by
* descending confidence.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public LanguageResponse getLanguage(String content) throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + LANGUAGE_SERVICE_PATH, LanguageResponse.class);
}
/**
* Returns morphological analysis of the input file.
* The response may include lemmas, part of speech tags, compound word components, and Han readings.
* Support for specific return types depends on language.
*
* @param morphologicalFeature Type of morphological analysis to perform.
* @param inputStream Input stream of file.
* @param contentType the content type (e.g. text/html)
* @param language Language of input if known (see {@link LanguageCode}), or null
* @param options Linguistics options
* @return MorphologyResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getMorphology(MorphologicalFeature, InputStream, String) getMorphology}
*/
@Deprecated
public MorphologyResponse getMorphology(MorphologicalFeature morphologicalFeature,
InputStream inputStream,
String contentType,
LanguageCode language, MorphologyOptions options)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.options(options)
.build();
return sendPostRequest(request, urlBase + MORPHOLOGY_SERVICE_PATH + "/" + morphologicalFeature.toString(),
MorphologyResponse.class);
}
/**
* Returns morphological analysis of the input file. The response may include lemmas, part of speech tags,
* compound word components, and Han readings. Builds request object from API rather than from parameters.
* Support for specific return types depends on language.
*
* @param inputStream Input stream of file
* @param contentType The content type (e.g. text/html)
* @return MorphologyResponse
* @throws RosetteAPIException
* @throws IOException
*/
public MorphologyResponse getMorphology(MorphologicalFeature morphologicalFeature,
InputStream inputStream,
String contentType)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + MORPHOLOGY_SERVICE_PATH + "/" + morphologicalFeature.toString(),
MorphologyResponse.class);
}
/**
* Returns morphological analysis of the URL content.
* The response may include lemmas, part of speech tags, compound word components, and Han readings.
* Support for specific return types depends on language.
*
* @param morphologicalFeature Type of morphological analysis to perform.
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null
* @param options Linguistics options
* @return MorphologyResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getMorphology(MorphologicalFeature, URL) getMorphology}
*/
@Deprecated
public MorphologyResponse getMorphology(MorphologicalFeature morphologicalFeature, URL url,
LanguageCode language,
MorphologyOptions options) throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.options(options)
.build();
return sendPostRequest(request, urlBase + MORPHOLOGY_SERVICE_PATH + "/" + morphologicalFeature.toString(),
MorphologyResponse.class);
}
/**
* Returns morphological analysis of the URL content. The response may include lemmas, part of speech tags, compound
* word components, and Han readings. Builds request object from API, rather than from parameters. Support for
* specific return types depends on language.
*
* @param url URL containing the data
* @return MorphologyResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a problem with communication or JSON serialization/deserialization.
*/
public MorphologyResponse getMorphology(MorphologicalFeature morphologicalFeature, URL url)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + MORPHOLOGY_SERVICE_PATH + "/" + morphologicalFeature.toString(),
MorphologyResponse.class);
}
/**
* Returns morphological analysis of a string.
* The response may include lemmas, part of speech tags, compound word components, and Han readings.
* Support for specific return types depends on language.
*
* @param morphologicalFeature Type of morphological analysis to perform.
* @param content String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null
* @param options Linguistics options
* @return MorphologyResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getMorphology(MorphologicalFeature, String) getMorphology}
*/
@Deprecated
public MorphologyResponse getMorphology(MorphologicalFeature morphologicalFeature, String content,
LanguageCode language, MorphologyOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.options(options)
.build();
return sendPostRequest(request, urlBase + MORPHOLOGY_SERVICE_PATH + "/" + morphologicalFeature.toString(),
MorphologyResponse.class);
}
/**
* Returns morphological analysis of a string. The response may include lemmas, part of speech tags, compound word
* components, and Han reading. Constructs request object from API information rather than from parameters. Support
* for specific return types depends on language.
*
* @param content String containing the data.
* @return MorphologyResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public MorphologyResponse getMorphology(MorphologicalFeature morphologicalFeature, String content)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + MORPHOLOGY_SERVICE_PATH + "/" + morphologicalFeature.toString(),
MorphologyResponse.class);
}
/**
* Returns entities extracted from the input file.
* <p>
* The response is a list of extracted entities.
* Each entity includes chain ID (all instances of the same entity share a chain id),
* mention (entity text in the input), normalized text (the most complete form of this entity that appears in
* the input), count (how many times this entity appears in the input), and the confidence associated with the
* extraction.
*
* @param inputStream Input stream of file.
* @param contentType the content type of the data (e.g. text/html)
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options EntityMention options.
* @return EntitiesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaces by {@link #getEntities(InputStream, String) getEntities}
*/
@Deprecated
public EntitiesResponse getEntities(InputStream inputStream,
String contentType,
LanguageCode language, EntitiesOptions options)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.options(options)
.build();
return sendPostRequest(request, urlBase + ENTITIES_SERVICE_PATH, EntitiesResponse.class);
}
/**
* Returns entities extracted from the input file. Builds request object from API fields not from parameters.
* <p>
* The response is a list of extracted entities. Each entity includes chain ID (all instances of the same
* entity share a chain id), mention (entity text in the input), normalized text (the most complete form
* of this entity that appears in the input), count (how many times this entity appears in the input), and the
* confidence associated with the extraction.
*
* @param inputStream Input stream of file.
* @param contentType The content type of the data (e.g. text/html)
* @return EntitiesResponse
* @throws RosetteAPIException
* @throws IOException
*/
public EntitiesResponse getEntities(InputStream inputStream, String contentType)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + ENTITIES_SERVICE_PATH, EntitiesResponse.class);
}
/**
* Returns entities extracted from the URL content.
* <p>
* The response is a list of extracted entities.
* Each entity includes chain ID (all instances of the same entity share a chain id),
* mention (entity text in the input), normalized text (the most complete form of this entity that appears in
* the input), count (how many times this entity appears in the input), and the confidence associated with the
* extraction.
*
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options EntityMention options.
* @return EntitiesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getEntities(URL) getEntities}
*/
@Deprecated
public EntitiesResponse getEntities(URL url, LanguageCode language, EntitiesOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.options(options)
.build();
return sendPostRequest(request, urlBase + ENTITIES_SERVICE_PATH, EntitiesResponse.class);
}
/**
*Returns entities extracted from the URL content. Request object built through API rather than parameters.
* <p>
* The response is a list of extracted entities.
* Each entity includes chain ID (all instances of the same entity share a chain id),
* mention (entity text in the input), normalized text (the most complete form of this entity that appears in
* the input), count (how many times this entity appears in the input), and the confidence associated with the
* extraction.
*
* @param url URL containing the data.
* @return EntitiesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public EntitiesResponse getEntities(URL url)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + ENTITIES_SERVICE_PATH, EntitiesResponse.class);
}
/**
* Returns entities extracted from a string.
* <p>
* The response is a list of extracted entities.
* Each entity includes chain ID (all instances of the same entity share a chain id),
* mention (entity text in the input), normalized text (the most complete form of this entity that appears in
* the input), count (how many times this entity appears in the input), and the confidence associated with the
* extraction.
*
* @param content String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options EntityMention options.
* @return EntitiesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getEntities(String) getEntities}
*/
@Deprecated
public EntitiesResponse getEntities(String content, LanguageCode language, EntitiesOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.options(options)
.build();
return sendPostRequest(request, urlBase + ENTITIES_SERVICE_PATH, EntitiesResponse.class);
}
/**
*Returns entities extracted from a string. Request object built from API rather than from parameters.
* <p>
* The response is a list of extracted entities.
* Each entity includes chain ID (all instances of the same entity share a chain id),
* mention (entity text in the input), normalized text (the most complete form of this entity that appears in
* the input), count (how many times this entity appears in the input), and the confidence associated with the
* extraction.
*
* @param content String containing the data.
* @return EntitiesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public EntitiesResponse getEntities(String content)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + ENTITIES_SERVICE_PATH, EntitiesResponse.class);
}
/**
* Links entities in the input file to entities in the knowledge base (Wikidata).
* The response identifies the entities in the input that have been linked to entities in the knowledge base.
* Each entity includes an entity id (from the knowledge base), a chain id (all instances of the same entity
* share a chain id), the mention (entity text from the input), and confidence associated with the linking.
*
* @param inputStream Input stream of file.
* @param contentType the content type for the file (e.g. text/html).
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return LinkedEntityResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated Merged into {@link #getEntities(String, LanguageCode, EntitiesOptions)}.
*/
@Deprecated
public LinkedEntitiesResponse getLinkedEntities(InputStream inputStream,
String contentType,
LanguageCode language)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.build();
return sendPostRequest(request, urlBase + ENTITIES_LINKED_SERVICE_PATH, LinkedEntitiesResponse.class);
}
/**
* Links entities in the URL content to entities in the knowledge base (Wikidata).
* The response identifies the entities in the input that have been linked to entities in the knowledge base.
* Each entity includes an entity id (from the knowledge base), a chain id (all instances of the same entity
* share a chain id), the mention (entity text from the input), and confidence associated with the linking.
*
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return LinkedEntityResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated Merged into {@link #getEntities(InputStream, String, LanguageCode, EntitiesOptions)}
*/
@Deprecated
public LinkedEntitiesResponse getLinkedEntities(URL url, LanguageCode language)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.build();
return sendPostRequest(request, urlBase + ENTITIES_LINKED_SERVICE_PATH, LinkedEntitiesResponse.class);
}
/**
* Links entities in a string to entities in the knowledge base (Wikidata).
* The response identifies the entities in the input that have been linked to entities in the knowledge base.
* Each entity includes an entity id (from the knowledge base), a chain id (all instances of the same entity
* share a chain id), the mention (entity text from the input), and confidence associated with the linking.
*
* @param content String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return LinkedEntityResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
@SuppressWarnings("deprecation")
public LinkedEntitiesResponse getLinkedEntities(String content, LanguageCode language)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.build();
return sendPostRequest(request, urlBase + ENTITIES_LINKED_SERVICE_PATH, LinkedEntitiesResponse.class);
}
/**
* Returns an ordered list of categories identified in the input file. The categories are Tier 1 contextual
* categories defined in the <a href="http://www.iab.net/QAGInitiative/overview/taxonomy">QAG Taxonomy</a>.
* <p>
* The response is the contextual categories identified in the input.
*
* @param inputStream Input stream of file.
* @param contentType the contentType of the file (e.g. text/html).
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options CategoriesOptions.
* @return CategoriesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getCategories(InputStream, String) getCategories}
*/
@Deprecated
public CategoriesResponse getCategories(InputStream inputStream,
String contentType,
LanguageCode language, CategoriesOptions options)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.options(options)
.build();
return sendPostRequest(request, urlBase + CATEGORIES_SERVICE_PATH, CategoriesResponse.class);
}
/**
* Returns an ordered list of categories identified in the input file. The categories are Tier 1 contextual
* categories defined in the <a href="http://www.iab.net/QAGInitiative/overview/taxonomy">QAG Taxonomy</a>.
* The request object is built from the API object rather than from the parameters.
* <p>
* The response is the contextual categories identified in the input.
* @param inputStream Input stream of file.
* @param contentType The contentType of the file (e.g. text/html)
* @return CategoriesResponse
* @throws RosetteAPIException
* @throws IOException
*/
public CategoriesResponse getCategories(InputStream inputStream,
String contentType)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + CATEGORIES_SERVICE_PATH, CategoriesResponse.class);
}
/**
* Returns an ordered list of categories identified in the URL content. The categories are Tier 1 contextual
* categories defined in the <a href="http://www.iab.net/QAGInitiative/overview/taxonomy">QAG Taxonomy</a>.
* <p>
* The response is the contextual categories identified in the input.
*
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options CategoriesOptions.
* @return CategoriesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated Replaced by {@link #getCategories(URL) getCategories}
*/
@Deprecated
public CategoriesResponse getCategories(URL url, LanguageCode language, CategoriesOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.options(options)
.build();
return sendPostRequest(request, urlBase + CATEGORIES_SERVICE_PATH, CategoriesResponse.class);
}
/**
* Returns an ordered list of categories identified in the input file. The categories are Tier 1 contextual
* categories defined in the <a href="http://www.iab.net/QAGInitiative/overview/taxonomy">QAG Taxonomy</a>.
* The request object is built from the API object rather than from the parameters.
* <p>
* The response is the contextual categories identified in the input.
*
* @param url URL containing the data.
* @return CategoriesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public CategoriesResponse getCategories(URL url)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + CATEGORIES_SERVICE_PATH, CategoriesResponse.class);
}
/**
* Returns an ordered list of categories identified in a string. The categories are Tier 1 contextual
* categories defined in the <a href="http://www.iab.net/QAGInitiative/overview/taxonomy">QAG Taxonomy</a>.
* <p>
* The response is the contextual categories identified in the input.
*
* @param content String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options CategoriesOptions.
* @return CategoriesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getCategories(String) getCategories}
*/
@Deprecated
public CategoriesResponse getCategories(String content, LanguageCode language, CategoriesOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.options(options)
.build();
return sendPostRequest(request, urlBase + CATEGORIES_SERVICE_PATH, CategoriesResponse.class);
}
/**
* Returns an ordered list of categories identified in the input file. The categories are Tier 1 contextual
* categories defined in the <a href="http://www.iab.net/QAGInitiative/overview/taxonomy">QAG Taxonomy</a>.
* The request object is built from the API object rather than from the parameters.
* <p>
* The response is the contextual categories identified in the input.
*
* @param content String containing the data.
* @return CategoriesResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a problem with communication or JSON serialization/deserialization.
*/
public CategoriesResponse getCategories(String content)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + CATEGORIES_SERVICE_PATH, CategoriesResponse.class);
}
/**
* Returns each relationship extracted from the input.
* <p>
* The response is a list of extracted relationships. A relationship contains
* <p>
* predicate - usually the main verb, property or action that is expressed by the text
* arg1 - usually the subject, agent or main actor of the relationship
* arg2 [optional] - complements the predicate and is usually the object, theme or patient of the relationship
* arg3 [optional] - usually an additional object in ditransitive verbs
* adjuncts [optional] - contain all optional parts of a relationship which are not temporal or locative expressions
* locatives [optional] - usually express the locations the action expressed by the relationship took place
* temporals [ optional] - usually express the time in which the action expressed by the relationship took place
* confidence - a measure of quality of relationship extraction, between 0 - 1
*
* @param content, String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options RelationshipOptions
* @return RelationshipsResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getRelationships(String) getRelationships}
*/
@Deprecated
public RelationshipsResponse getRelationships(String content, LanguageCode language, RelationshipsOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.options(options)
.build();
return sendPostRequest(request, urlBase + RELATIONSHIPS_SERVICE_PATH, RelationshipsResponse.class);
}
/**
* Returns each relationship extracted from the input. Request object uses API attributes rather than parameters.
* <p>
* The response is a list of extracted relationships. A relationship contains
* <p>
* predicate - usually the main verb, property or action that is expressed by the text
* arg1 - usually the subject, agent or main actor of the relationship
* arg2 [optional] - complements the predicate and is usually the object, theme or patient of the relationship
* arg3 [optional] - usually an additional object in ditransitive verbs
* adjuncts [optional] - contain all optional parts of a relationship which are not temporal or locative expressions
* locatives [optional] - usually express the locations the action expressed by the relationship took place
* temporals [ optional] - usually express the time in which the action expressed by the relationship took place
* confidence - a measure of quality of relationship extraction, between 0 - 1
* @param content String containing the data.
* @return RelationshipsResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public RelationshipsResponse getRelationships(String content)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + RELATIONSHIPS_SERVICE_PATH, RelationshipsResponse.class);
}
/**
* Returns each relationship extracted from the input.
* <p>
* The response is a list of extracted relationships. A relationship contains
* <p>
* predicate - usually the main verb, property or action that is expressed by the text
* arg1 - usually the subject, agent or main actor of the relationship
* arg2 [optional] - complements the predicate and is usually the object, theme or patient of the relationship
* arg3 [optional] - usually an additional object in ditransitive verbs
* adjuncts [optional] - contain all optional parts of a relationship which are not temporal or locative expressions
* locatives [optional] - usually express the locations the action expressed by the relationship took place
* temporals [ optional] - usually express the time in which the action expressed by the relationship took place
* confidence - a measure of quality of relationship extraction, between 0 - 1
*
* @param inputStream Input stream of file.
* @param contentType the content type of the file.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options RelationshipOptions
* @return RelationshipsResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request
* @throws IOException - If there is a communication or JSON serialization/deserialization error
*
* @deprecated Replaced by {@link #getRelationships(InputStream, String) getRelationships}
*/
@Deprecated
public RelationshipsResponse getRelationships(InputStream inputStream,
String contentType,
LanguageCode language, RelationshipsOptions options)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.options(options)
.build();
return sendPostRequest(request, urlBase + RELATIONSHIPS_SERVICE_PATH, RelationshipsResponse.class);
}
/**
* Returns each relationship extracted from the input. Request object uses API attributes rather than parameters.
* <p>
* The response is a list of extracted relationships. A relationship contains
* <p>
* predicate - usually the main verb, property or action that is expressed by the text
* arg1 - usually the subject, agent or main actor of the relationship
* arg2 [optional] - complements the predicate and is usually the object, theme or patient of the relationship
* arg3 [optional] - usually an additional object in ditransitive verbs
* adjuncts [optional] - contain all optional parts of a relationship which are not temporal or locative expressions
* locatives [optional] - usually express the locations the action expressed by the relationship took place
* temporals [ optional] - usually express the time in which the action expressed by the relationship took place
* confidence - a measure of quality of relationship extraction, between 0 - 1
* @param inputStream Input stream of file.
* @param contentType The content type of the file.
* @return RelationshipsResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public RelationshipsResponse getRelationships(InputStream inputStream,
String contentType)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + RELATIONSHIPS_SERVICE_PATH, RelationshipsResponse.class);
}
/**
* Returns each relationship extracted from the input.
* <p>
* The response is a list of extracted relationships. A relationship contains
* <p>
* predicate - usually the main verb, property or action that is expressed by the text
* arg1 - usually the subject, agent or main actor of the relationship
* arg2 [optional] - complements the predicate and is usually the object, theme or patient of the relationship
* arg3 [optional] - usually an additional object in ditransitive verbs
* adjuncts [optional] - contain all optional parts of a relationship which are not temporal or locative expressions
* locatives [optional] - usually express the locations the action expressed by the relationship took place
* temporals [ optional] - usually express the time in which the action expressed by the relationship took place
* confidence - a measure of quality of relationship extraction, between 0 - 1
*
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options RelationshipOptions
* @return RelationshipsResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request
* @throws IOException - If there is a communication or JSON serialization/deserialization error
*
* @deprecated replaced {@link #getRelationships(URL) getRelationships}
*/
@Deprecated
public RelationshipsResponse getRelationships(URL url, LanguageCode language, RelationshipsOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.options(options)
.build();
return sendPostRequest(request, urlBase + RELATIONSHIPS_SERVICE_PATH, RelationshipsResponse.class);
}
/**
* Returns each relationship extracted from the input.
* <p>
* The response is a list of extracted relationships. A relationship contains
* <p>
* predicate - usually the main verb, property or action that is expressed by the text
* arg1 - usually the subject, agent or main actor of the relationship
* arg2 [optional] - complements the predicate and is usually the object, theme or patient of the relationship
* arg3 [optional] - usually an additional object in ditransitive verbs
* adjuncts [optional] - contain all optional parts of a relationship which are not temporal or locative expressions
* locatives [optional] - usually express the locations the action expressed by the relationship took place
* temporals [ optional] - usually express the time in which the action expressed by the relationship took place
* confidence - a measure of quality of relationship extraction, between 0 - 1
*
* @param url URL containing the data.
* @return RelationshipOptions
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a problem with communication or JSON serialization/deserialization.
*/
public RelationshipsResponse getRelationships(URL url)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + RELATIONSHIPS_SERVICE_PATH, RelationshipsResponse.class);
}
/**
* Analyzes the positive and negative sentiment expressed by the input.
* <p>
* The response contains sentiment analysis results.
*
* @param inputStream Input stream of file.
* @param contentType the content type of the file (e.g. text/html)
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options SentimentOptions.
* @return SentimentResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getSentiment(InputStream, String) getSentiment}
*/
@Deprecated
public SentimentResponse getSentiment(InputStream inputStream,
String contentType,
LanguageCode language, SentimentOptions options)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.options(options)
.build();
return sendPostRequest(request, urlBase + SENTIMENT_SERVICE_PATH, SentimentResponse.class);
}
/**
* Analyzes the positive and negative sentiment expressed by the input. Request object built from API rather than
* from individual request.
* <p>
* The response contains sentiment analysis results.
*
* @param inputStream Input stream of file.
* @param contentType The content type of the file (e.g. text/html)
* @return SentimentResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public SentimentResponse getSentiment(InputStream inputStream,
String contentType)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + SENTIMENT_SERVICE_PATH, SentimentResponse.class);
}
/**
* Analyzes the positive and negative sentiment expressed by the input.
* <p>
* The response contains sentiment analysis results.
*
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options SentimentOptions.
* @return SentimentResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getSentiment(URL) getSentiment}
*/
@Deprecated
public SentimentResponse getSentiment(URL url, LanguageCode language, SentimentOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.options(options)
.build();
return sendPostRequest(request, urlBase + SENTIMENT_SERVICE_PATH, SentimentResponse.class);
}
/**
* Analyzes the positive and negative sentiment expressed by the input. Request object built from API rather than
* from individual request.
* <p>
* The response contains sentiment analysis results.
*
* @param url URL containing the data.
* @return SentimentOptions
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public SentimentResponse getSentiment(URL url)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + SENTIMENT_SERVICE_PATH, SentimentResponse.class);
}
/**
* Analyzes the positive and negative sentiment expressed by the input.
* <p>
* The response contains sentiment analysis results.
*
* @param content String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @param options SentimentOptions.
* @return SentimentResponse
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getSentiment(String) getSentiment}
*/
@Deprecated
public SentimentResponse getSentiment(String content, LanguageCode language, SentimentOptions options)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.options(options)
.build();
return sendPostRequest(request, urlBase + SENTIMENT_SERVICE_PATH, SentimentResponse.class);
}
/**
* Analyzes the positive and negative sentiment expressed by the input. Request object uses API object rather than
* parameters.
* <p>
* The response contains sentiment analysis results.
*
* @param content String containing the data.
* @return SentimentOptions
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public SentimentResponse getSentiment(String content)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + SENTIMENT_SERVICE_PATH, SentimentResponse.class);
}
/**
* Divides the input into tokens.
*
* @param inputStream Input stream of file.
* @param contentType the content type of the file (e.g. text/html)
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return The response contains a list of tokens.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getTokens(InputStream, String) getTokens}
*/
@Deprecated
public TokensResponse getTokens(InputStream inputStream, String contentType, LanguageCode language)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.build();
return sendPostRequest(request, urlBase + TOKENS_SERVICE_PATH, TokensResponse.class);
}
/**
* Divides the input into tokens. Request object built through API calls rather than from parameters.
*
* @param inputStream Input stream of file.
* @param contentType The content type of the file (e.g. text/html)
*
* @return The response contains a list of tokens.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a problem with communication or JSON serialization/deserialization
*/
public TokensResponse getTokens(InputStream inputStream, String contentType)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + TOKENS_SERVICE_PATH, TokensResponse.class);
}
/**
* Divides the input into tokens.
*
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return The response contains a list of tokens.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getTokens(URL) getTokens}
*/
@Deprecated
public TokensResponse getTokens(URL url, LanguageCode language) throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.build();
return sendPostRequest(request, urlBase + TOKENS_SERVICE_PATH, TokensResponse.class);
}
/**
* Divides the input into tokens. Request object uses API fields rather than call parameters.
*
* @param url URL containing the data.
* @return The response contains a list of tokens.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public TokensResponse getTokens(URL url) throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + TOKENS_SERVICE_PATH, TokensResponse.class);
}
/**
* Divides the input into tokens.
*
* @param content String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return The response contains a list of tokens.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getTokens(String) getTokens}
*/
@Deprecated
public TokensResponse getTokens(String content, LanguageCode language) throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.build();
return sendPostRequest(request, urlBase + TOKENS_SERVICE_PATH, TokensResponse.class);
}
/**
* Divides the input into tokens. Request object is built from the API object rather than from parameters.
*
* @param content String containing the data.
* @return The response contains a list of tokens.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public TokensResponse getTokens(String content) throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + TOKENS_SERVICE_PATH, TokensResponse.class);
}
/**
* Divides the input into sentences.
*
* @param inputStream Input stream of file.
* @param contentType the content type of the file (e.g. text/html).
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return The response contains a list of sentences.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getSentences(InputStream, String) getSentences}
*/
@Deprecated
public SentencesResponse getSentences(InputStream inputStream,
String contentType,
LanguageCode language)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
Request request = new DocumentRequest.Builder()
.language(language)
.contentBytes(bytes, contentType)
.build();
return sendPostRequest(request, urlBase + SENTENCES_SERVICE_PATH, SentencesResponse.class);
}
/**
* Divides the input into sentences. Request object is built from the API object rather than from parameters.
*
* @param inputStream Input stream of file.
* @param contentType The content type of the file (e.g. text/html).
* @return The response contains a list of sentences.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a problem with communication or JSON serialization/deserialization.
*/
public SentencesResponse getSentences(InputStream inputStream,
String contentType)
throws RosetteAPIException, IOException {
byte[] bytes = getBytes(inputStream);
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentBytes(bytes, contentType).build(), urlBase + SENTENCES_SERVICE_PATH, SentencesResponse.class);
}
/**
* Divides the input into sentences.
*
* @param url URL containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return The response contains a list of sentences.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getSentences(URL) getSentences}
*/
@Deprecated
public SentencesResponse getSentences(URL url, LanguageCode language) throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.contentUri(url.toString())
.build();
return sendPostRequest(request, urlBase + SENTENCES_SERVICE_PATH, SentencesResponse.class);
}
/**
* Divides the input into sentences. Request object is built from the API object rather than from parameters.
*
* @param url URL containing the data.
* @return The response contains a list of sentences.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication of JSON serialization/deserialization error.
*/
public SentencesResponse getSentences(URL url) throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.contentUri(url.toString()).build(), urlBase + SENTENCES_SERVICE_PATH, SentencesResponse.class);
}
/**
* Divides the input into sentences.
*
* @param content String containing the data.
* @param language Language of input if known (see {@link LanguageCode}), or null.
* @return The response contains a list of sentences.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*
* @deprecated replaced by {@link #getSentences(String) getSentences}
*/
@Deprecated
public SentencesResponse getSentences(String content, LanguageCode language)
throws RosetteAPIException, IOException {
Request request = new DocumentRequest.Builder()
.language(language)
.content(content)
.build();
return sendPostRequest(request, urlBase + SENTENCES_SERVICE_PATH, SentencesResponse.class);
}
/**
* Divides the input into sentences. Request object is built from the API object rather than from parameters.
*
* @param content String containing the data.
* @return The response contains a list of sentences.
* @throws RosetteAPIException - If there is a problem with the Rosette API request.
* @throws IOException - If there is a communication or JSON serialization/deserialization error.
*/
public SentencesResponse getSentences(String content)
throws RosetteAPIException, IOException {
DocumentRequest.BaseBuilder documentRequestBuilder = getDocumentRequestBuilder();
return sendPostRequest(documentRequestBuilder.content(content).build(), urlBase + SENTENCES_SERVICE_PATH, SentencesResponse.class);
}
/**
* Provides information on Rosette API
*
* @return {@link com.basistech.rosette.apimodel.InfoResponse InfoResponse}
* @throws RosetteAPIException Rosette specific exception
* @throws IOException General IO exception
*/
public InfoResponse getInfo() throws RosetteAPIException, IOException {
return sendGetRequest(urlBase + INFO_SERVICE_PATH, InfoResponse.class);
}
/**
* Send a request to the API, return a response (or throw an exception).
* Use this method for request parameter combinations that are not covered
* by the specific endpoint methods.
* @param endpoint The endpoint, for example, '/entities'.
* @param request The request object.
* @param responseClass The class of the response object corresponding to the request object.
* @param <Req> the request type.
* @param <Res> the response type.
* @return the response.
* @throws IOException for errors in communications.
* @throws RosetteAPIException for errors returned by the API.
*/
public <Req extends Request, Res extends Response> Res doRequest(String endpoint, Req request, Class<Res> responseClass)
throws IOException, RosetteAPIException {
return sendPostRequest(request, urlBase + endpoint, responseClass);
}
/**
* Sends a GET request to Rosette API.
* <p>
* Returns a Response.
*
* @param urlStr Rosette API end point.
* @param clazz Response class
* @return Response
* @throws IOException
* @throws RosetteAPIException
*/
private <T extends Response> T sendGetRequest(String urlStr, Class<T> clazz) throws IOException, RosetteAPIException {
HttpGet get = new HttpGet(urlStr);
HttpResponse httpResponse = httpClient.execute(get);
T resp = getResponse(httpResponse, clazz);
responseHeadersToExtendedInformation(resp, httpResponse);
return resp;
}
/**
* Sends a POST request to Rosette API.
* <p>
* Returns a Response.
*
* @param urlStr Rosette API end point.
* @param clazz Response class
* @return Response
* @throws RosetteAPIException
* @throws IOException
*/
private <T extends Response> T sendPostRequest(Object request, String urlStr, Class<T> clazz)
throws RosetteAPIException, IOException {
ObjectWriter writer = mapper.writer().without(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
boolean notPlainText = false;
if (request instanceof DocumentRequest) {
Object rawContent = ((DocumentRequest) request).getRawContent();
if (rawContent instanceof String) {
writer = writer.withView(DocumentRequestMixin.Views.Content.class);
} else if (rawContent != null) {
notPlainText = true;
}
}
final ObjectWriter finalWriter = writer;
HttpPost post = new HttpPost(urlStr);
//TODO: add compression!
if (notPlainText) {
setupMultipartRequest((DocumentRequest) request, finalWriter, post);
} else {
setupPlainRequest(request, finalWriter, post);
}
RosetteAPIException lastException = null;
int numRetries = this.failureRetries;
while (numRetries-- > 0) {
HttpResponse response = null;
try {
response = httpClient.execute(post);
T resp = getResponse(response, clazz);
Header ridHeader = response.getFirstHeader("X-RosetteAPI-DocumentRequest-Id");
if (ridHeader != null && ridHeader.getValue() != null) {
LOG.debug("DocumentRequest ID " + ridHeader.getValue());
}
responseHeadersToExtendedInformation(resp, response);
return resp;
} catch (RosetteAPIException e) {
// only 5xx errors are worthy retrying, others throw right away
if (e.getHttpStatusCode() < 500) {
throw e;
} else {
lastException = e;
}
} finally {
if (response != null) {
if (response instanceof CloseableHttpResponse) {
((CloseableHttpResponse)response).close();
}
}
}
}
throw lastException;
}
@SuppressWarnings("unchecked")
private <T extends Response> void responseHeadersToExtendedInformation(T resp, HttpResponse response) {
for (Header header : response.getAllHeaders()) {
if (resp.getExtendedInformation() != null
&& resp.getExtendedInformation().containsKey(header.getName())) {
Set<Object> currentSetValue;
if (resp.getExtendedInformation().get(header.getName()) instanceof Set) {
currentSetValue = (Set<Object>) resp.getExtendedInformation().get(header.getName());
} else {
currentSetValue = new HashSet<>(Collections.singletonList(resp.getExtendedInformation().get(header.getName())));
}
currentSetValue.add(header.getValue());
resp.setExtendedInformation(header.getName(), currentSetValue);
} else {
resp.setExtendedInformation(header.getName(), header.getValue());
}
}
}
private void setupPlainRequest(final Object request, final ObjectWriter finalWriter, HttpPost post) {
// just posting json.
post.addHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
post.setEntity(new AbstractHttpEntity() {
@Override
public boolean isRepeatable() {
return false;
}
@Override
public long getContentLength() {
return -1;
}
@Override
public InputStream getContent() throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public void writeTo(OutputStream outstream) throws IOException {
finalWriter.writeValue(outstream, request);
}
@Override
public boolean isStreaming() {
return false;
}
});
}
private void setupMultipartRequest(final DocumentRequest request, final ObjectWriter finalWriter, HttpPost post) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMimeSubtype("mixed");
builder.setMode(HttpMultipartMode.STRICT);
FormBodyPartBuilder partBuilder = FormBodyPartBuilder.create("request",
// Make sure we're not mislead by someone who puts a charset into the mime type.
new AbstractContentBody(ContentType.parse(ContentType.APPLICATION_JSON.getMimeType())) {
@Override
public String getFilename() {
return null;
}
@Override
public void writeTo(OutputStream out) throws IOException {
finalWriter.writeValue(out, request);
}
@Override
public String getTransferEncoding() {
return MIME.ENC_BINARY;
}
@Override
public long getContentLength() {
return -1;
}
});
// Either one of 'name=' or 'Content-ID' would be enough.
partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"request\"");
partBuilder.setField("Content-ID", "request");
builder.addPart(partBuilder.build());
partBuilder = FormBodyPartBuilder.create("content", new InputStreamBody(request.getContentBytes(), ContentType.parse(request.getContentType())));
partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"content\"");
partBuilder.setField("Content-ID", "content");
builder.addPart(partBuilder.build());
builder.setCharset(StandardCharsets.UTF_8);
HttpEntity entity = builder.build();
post.setEntity(entity);
}
private String headerValueOrNull(Header header) {
if (header == null) {
return null;
} else {
return header.getValue();
}
}
/**
* Gets response from HTTP connection, according to the specified response class;
* throws for an error response.
*
* @param httpResponse the response object
* @param clazz Response class
* @return Response
* @throws IOException
* @throws RosetteAPIException if the status is not 200.
*/
private <T extends Response> T getResponse(HttpResponse httpResponse, Class<T> clazz)
throws IOException, RosetteAPIException {
int status = httpResponse.getStatusLine().getStatusCode();
String encoding = headerValueOrNull(httpResponse.getFirstHeader(HttpHeaders.CONTENT_ENCODING));
String connectionConcurrency = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteApi-Concurrency"));
if (connectionConcurrency != null) {
try {
int concurrencyHeader = Integer.parseInt(connectionConcurrency);
if (allowSocketChange && concurrencyHeader != maxSockets) {
maxSockets = concurrencyHeader;
initHttpClient();
}
} catch (NumberFormatException e) {
throw new RuntimeException(
String.format("Error converting X-RosetteApi-Concurrency (%s) to a number", connectionConcurrency),
e.getCause());
}
}
try (
InputStream stream = httpResponse.getEntity().getContent();
InputStream inputStream = "gzip".equalsIgnoreCase(encoding) ? new GZIPInputStream(stream) : stream) {
String ridHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-DocumentRequest-Id"));
if (HTTP_OK != status) {
String ecHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-Status-Code"));
String emHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-Status-Message"));
String responseContentType = headerValueOrNull(httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE));
if ("application/json".equals(responseContentType)) {
ErrorResponse errorResponse = mapper.readValue(inputStream, ErrorResponse.class);
if (ridHeader != null) {
LOG.debug("DocumentRequest ID " + ridHeader);
}
if (ecHeader != null) {
errorResponse.setCode(ecHeader);
}
if (emHeader != null) {
errorResponse.setMessage(emHeader);
}
throw new RosetteAPIException(status, errorResponse);
} else {
String errorContent;
if (inputStream != null) {
byte[] content = getBytes(inputStream);
errorContent = new String(content, "utf-8");
} else {
errorContent = "(no body)";
}
// something not from us at al
throw new RosetteAPIException(status, new ErrorResponse("invalidErrorResponse", errorContent));
}
} else {
return mapper.readValue(inputStream, clazz);
}
}
}
/**
* Returns a byte array from InputStream.
*
* @param is InputStream
* @return byte array
* @throws IOException
*/
private static byte[] getBytes(InputStream is) throws IOException {
return ByteStreams.toByteArray(is);
}
@Override
public void close() throws IOException {
if (httpClient instanceof CloseableHttpClient) {
((CloseableHttpClient)httpClient).close();
}
}
private DocumentRequest.BaseBuilder getDocumentRequestBuilder() throws IOException {
return new DocumentRequest.Builder()
.language(language)
.genre(genre)
.options(options);
}
/**
* Builder class for the RosetteAPI object.
*/
public static class Builder {
protected LanguageCode language;
protected String genre;
protected Options options;
protected String key;
protected String urlBase = DEFAULT_URL_BASE;
protected int failureRetries = 1;
protected HttpClient httpClient;
protected Builder getThis() {
return this;
}
/**
* Set the language of the input.
* @param language the language.
* @return this
*/
public Builder language(LanguageCode language) {
this.language = language;
return getThis();
}
/**
* Set the options for this request.
* @param options the options.
* @return this
*/
public Builder options(Options options) {
this.options = options;
return getThis();
}
/**
* Set the genre of the request.
* @param genre genre (ex: social-media)
* @return this
*/
public Builder genre(String genre) {
this.genre = genre;
return getThis();
}
/**
* Set the apiKey for the requests
* @param key apiKey
* @return this
*/
public Builder apiKey(String key) {
this.key = key;
return getThis();
}
/**
* Sets an alternative url for testing purposes
* @param url alternative url
* @return this
*/
public Builder alternateUrl(String url) {
if (url != null) {
this.urlBase = url;
}
return getThis();
}
/**
* Set failure retries, default 1
* @param retries number of retries
* @return this
*/
public Builder failureRetries(int retries) {
this.failureRetries = retries;
return getThis();
}
/**
* User can provide their own http client
* @param client CloseableHttpClient
* @return this
*/
public Builder httpClient(HttpClient client) {
this.httpClient = client;
return getThis();
}
/**
* Construct the api object.
* @return the api object.
*/
public RosetteAPI build() throws IOException, RosetteAPIException {
return new RosetteAPI(key, urlBase, failureRetries, language, genre, options, httpClient);
}
}
}
|
RCB-454: Catch and handle NumberFormatException, validate concurrency returned values
|
api/src/main/java/com/basistech/rosette/api/RosetteAPI.java
|
RCB-454: Catch and handle NumberFormatException, validate concurrency returned values
|
|
Java
|
apache-2.0
|
f97dd575024338c4cf72724d7e40675b4ca61402
| 0
|
jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim
|
/*
* JaamSim Discrete Event Simulation
* Copyright (C) 2013 Ausenco Engineering Canada Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.jaamsim.FluidObjects;
import java.util.ArrayList;
import com.jaamsim.input.InputErrorException;
import com.jaamsim.input.Output;
/**
* FluidFlow tracks the flow rate between a source and a destination.
* @author Harry King
*
*/
public class FluidFlow extends FluidFlowCalculation {
private double flowAcceleration; // The rate of change of the volumetric flow rate with respect to time (m3/s2).
private ArrayList<FluidComponent> routeList; // A list of the hydraulic components in the flow, from source to destination.
private double totalFlowInertia; // The sum of Density x Length / FlowArea for the hydraulic components in the route.
private double destinationBaseInletPressure; // The base pressure at the destination's inlet.
private double destinationTargetInletPressure; // The desired inlet pressure at the destination's inlet.
{
sourceInput.setRequired(true);
destinationInput.setRequired(true);
}
public FluidFlow() {
routeList = new ArrayList<>();
}
@Override
public void earlyInit() {
super.earlyInit();
flowAcceleration = 0.0;
// Construct the list of hydraulic components in the flow path
routeList.clear();
routeList.add( this.getDestination() );
FluidComponent prev = routeList.get(0).getPrevious();
while( prev != null ) {
routeList.add(0, prev);
prev = prev.getPrevious();
}
// Confirm that the first component is the source
if( routeList.get(0) != this.getSource() ) {
throw new InputErrorException( "The source of the route is not connected to the destination by the 'Previous' keyword inputs for the individual components." );
}
// Set the Flow object for each component in the route
for( FluidComponent each : routeList ) {
each.setFluidFlow( this );
}
// Calculate the total flow inertia of the flow path
totalFlowInertia = 0.0;
for( FluidComponent each : routeList ) {
each.earlyInit(); // Needs to be called to set flowArea
totalFlowInertia += each.getLength() / each.getFlowArea();
}
totalFlowInertia *= this.getFluid().getDensity();
}
@Override
protected void calcFlowRate( FluidComponent source, FluidComponent destination, double dt ) {
// Update the flow rate
this.setFlowRate( this.getFlowRate() + flowAcceleration * dt );
// Update the flow velocity and base pressures in each component of the flow route
// (base pressure ignores the affect of acceleration)
for( FluidComponent each : routeList ) {
each.updateVelocity();
each.updateBaseInletPressure();
each.updateBaseOutletPressure();
}
// Update the flow acceleration
destinationBaseInletPressure = destination.getBaseInletPressure();
destinationTargetInletPressure = destination.getTargetInletPressure();
flowAcceleration = ( destinationBaseInletPressure
- destinationTargetInletPressure ) / totalFlowInertia;
// Update the pressure in each component of the flow route after allowing for acceleration
for( FluidComponent each : routeList ) {
each.updateInletPressure();
each.updateOutletPressure( flowAcceleration );
}
// Confirm that the pressure is now balanced
double diff = destination.getInletPressure() /
destination.getTargetInletPressure() - 1.0;
if( Math.abs( diff ) > 1.0e-4 ) {
error("Pressure did not balance correctly. Difference = %f", diff);
}
}
@Output(name = "FlowAcceleration",
description = "The time derivative of the volumetric flow rate.")
public double getFlowAcceleration( double simTime ) {
return flowAcceleration;
}
@Output(name = "FlowInertia",
description = "The sum of (density)(length)/(flow area) for the hydraulic components in the route.")
public double getFlowInertia( double simTime ) {
return totalFlowInertia;
}
}
|
src/main/java/com/jaamsim/FluidObjects/FluidFlow.java
|
/*
* JaamSim Discrete Event Simulation
* Copyright (C) 2013 Ausenco Engineering Canada Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.jaamsim.FluidObjects;
import java.util.ArrayList;
import com.jaamsim.input.InputErrorException;
import com.jaamsim.input.Output;
/**
* FluidFlow tracks the flow rate between a source and a destination.
* @author Harry King
*
*/
public class FluidFlow extends FluidFlowCalculation {
private double flowAcceleration; // The rate of change of the volumetric flow rate with respect to time (m3/s2).
private ArrayList<FluidComponent> routeList; // A list of the hydraulic components in the flow, from source to destination.
private double totalFlowInertia; // The sum of Density x Length / FlowArea for the hydraulic components in the route.
private double destinationBaseInletPressure; // The base pressure at the destination's inlet.
private double destinationTargetInletPressure; // The desired inlet pressure at the destination's inlet.
public FluidFlow() {
routeList = new ArrayList<>();
}
@Override
public void validate() {
super.validate();
// Confirm that the source has been specified
if( this.getSource() == null ) {
throw new InputErrorException( "The keyword Source must be set." );
}
// Confirm that the destination has been specified
if( this.getDestination() == null ) {
throw new InputErrorException( "The keyword Destination must be set." );
}
}
@Override
public void earlyInit() {
super.earlyInit();
flowAcceleration = 0.0;
// Construct the list of hydraulic components in the flow path
routeList.clear();
routeList.add( this.getDestination() );
FluidComponent prev = routeList.get(0).getPrevious();
while( prev != null ) {
routeList.add(0, prev);
prev = prev.getPrevious();
}
// Confirm that the first component is the source
if( routeList.get(0) != this.getSource() ) {
throw new InputErrorException( "The source of the route is not connected to the destination by the 'Previous' keyword inputs for the individual components." );
}
// Set the Flow object for each component in the route
for( FluidComponent each : routeList ) {
each.setFluidFlow( this );
}
// Calculate the total flow inertia of the flow path
totalFlowInertia = 0.0;
for( FluidComponent each : routeList ) {
each.earlyInit(); // Needs to be called to set flowArea
totalFlowInertia += each.getLength() / each.getFlowArea();
}
totalFlowInertia *= this.getFluid().getDensity();
}
@Override
protected void calcFlowRate( FluidComponent source, FluidComponent destination, double dt ) {
// Update the flow rate
this.setFlowRate( this.getFlowRate() + flowAcceleration * dt );
// Update the flow velocity and base pressures in each component of the flow route
// (base pressure ignores the affect of acceleration)
for( FluidComponent each : routeList ) {
each.updateVelocity();
each.updateBaseInletPressure();
each.updateBaseOutletPressure();
}
// Update the flow acceleration
destinationBaseInletPressure = destination.getBaseInletPressure();
destinationTargetInletPressure = destination.getTargetInletPressure();
flowAcceleration = ( destinationBaseInletPressure
- destinationTargetInletPressure ) / totalFlowInertia;
// Update the pressure in each component of the flow route after allowing for acceleration
for( FluidComponent each : routeList ) {
each.updateInletPressure();
each.updateOutletPressure( flowAcceleration );
}
// Confirm that the pressure is now balanced
double diff = destination.getInletPressure() /
destination.getTargetInletPressure() - 1.0;
if( Math.abs( diff ) > 1.0e-4 ) {
error("Pressure did not balance correctly. Difference = %f", diff);
}
}
@Output(name = "FlowAcceleration",
description = "The time derivative of the volumetric flow rate.")
public double getFlowAcceleration( double simTime ) {
return flowAcceleration;
}
@Output(name = "FlowInertia",
description = "The sum of (density)(length)/(flow area) for the hydraulic components in the route.")
public double getFlowInertia( double simTime ) {
return totalFlowInertia;
}
}
|
JS: Set Required on FluidFlow keywords and removed validate
Signed-off-by: Eric Finlay <0515159691d711daa95426d2e7114f1a85afa555@ausenco.com>
Signed-off-by: Stephen Wong <6f34db11dd2258ec4ffa799eb0d7827f906cb1c6@ausenco.com>
|
src/main/java/com/jaamsim/FluidObjects/FluidFlow.java
|
JS: Set Required on FluidFlow keywords and removed validate
|
|
Java
|
apache-2.0
|
4d41a4998bd394716be615ba9a6d604749bf71a4
| 0
|
apache/velocity-tools,apache/velocity-tools
|
package org.apache.velocity.tools.struts;
/*
* 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.
*/
import java.util.Iterator;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.SecurePlugInInterface;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.config.SecureActionConfig;
import org.apache.velocity.tools.view.tools.LinkTool;
/**
* Tool to be able to use Struts SSL Extensions with Velocity.
* <p>It has the same interface as StrutsLinkTool and can function as a
* substitute if Struts 1.x and SSL Ext are installed. </p>
* <p>Usage:
* <pre>
* Template example:
* <!-- Use just like a regular StrutsLinkTool -->
* $link.action.nameOfAction
* $link.action.nameOfForward
*
* If the action or forward is marked as secure, or not,
* in your struts-config then the link will be rendered
* with https or http accordingly.
*
* Toolbox configuration:
* <tool>
* <key>link</key>
* <scope>request</scope>
* <class>org.apache.velocity.tools.struts.SecureLinkTool</class>
* </tool>
* </pre>
* </p>
* @since VelocityTools 1.1
* @author <a href="mailto:marinoj@centrum.is">Marino A. Jonsson</a>
* @version $Revision$ $Date$
*/
public class SecureLinkTool extends LinkTool
{
private static final String HTTP = "http";
private static final String HTTPS = "https";
private static final String STD_HTTP_PORT = "80";
private static final String STD_HTTPS_PORT = "443";
/**
* <p>Returns a copy of the link with the given action name
* converted into a server-relative URI reference. This method
* does not check if the specified action really is defined.
* This method will overwrite any previous URI reference settings
* but will copy the query string.</p>
*
* @param action an action path as defined in struts-config.xml
*
* @return a new instance of StrutsLinkTool
*/
public SecureLinkTool setAction(String action)
{
String link = StrutsUtils.getActionMappingURL(application, request, action);
return (SecureLinkTool)copyWith(computeURL(request, application, link));
}
/**
* <p>Returns a copy of the link with the given global forward name
* converted into a server-relative URI reference. If the parameter
* does not map to an existing global forward name, <code>null</code>
* is returned. This method will overwrite any previous URI reference
* settings but will copy the query string.</p>
*
* @param forward a global forward name as defined in struts-config.xml
*
* @return a new instance of StrutsLinkTool
*/
public SecureLinkTool setForward(String forward)
{
String url = StrutsUtils.getForwardURL(request, application, forward);
if (url == null)
{
return null;
}
return (SecureLinkTool)copyWith(url);
}
/**
* Compute a hyperlink URL based on the specified action link.
* The returned URL will have already been passed to
* <code>response.encodeURL()</code> for adding a session identifier.
*
* @param request the current request.
* @param app the current ServletContext.
* @param link the action that is to be converted to a hyperlink URL
* @return the computed hyperlink URL
*/
public String computeURL(HttpServletRequest request,
ServletContext app, String link)
{
StringBuffer url = new StringBuffer(link);
String contextPath = request.getContextPath();
SecurePlugInInterface securePlugin = (SecurePlugInInterface)app.getAttribute(SecurePlugInInterface.SECURE_PLUGIN);
if (securePlugin.getSslExtEnable() &&
url.toString().startsWith(contextPath))
{
// Initialize the scheme and ports we are using
String usingScheme = request.getScheme();
String usingPort = String.valueOf(request.getServerPort());
// Get the servlet context relative link URL
String linkString = url.toString().substring(contextPath.length());
// See if link references an action somewhere in our app
SecureActionConfig secureConfig = getActionConfig(request, app, linkString);
// If link is an action, find the desired port and scheme
if (secureConfig != null &&
!SecureActionConfig.ANY.equalsIgnoreCase(secureConfig.getSecure()))
{
String desiredScheme = Boolean.valueOf(secureConfig.getSecure()).booleanValue() ?
HTTPS : HTTP;
String desiredPort = Boolean.valueOf(secureConfig.getSecure()).booleanValue() ?
securePlugin.getHttpsPort() : securePlugin.getHttpPort();
// If scheme and port we are using do not match the ones we want
if (!desiredScheme.equals(usingScheme) ||
!desiredPort.equals(usingPort))
{
url.insert(0, startNewUrlString(request, desiredScheme, desiredPort));
// This is a hack to help us overcome the problem that some
// older browsers do not share sessions between http & https
// If this feature is diabled, session ID could still be added
// the previous call to the RequestUtils.computeURL() method,
// but only if needed due to cookies disabled, etc.
if (securePlugin.getSslExtAddSession() && url.toString().indexOf(";jsessionid=") < 0)
{
// Add the session identifier
url = new StringBuffer(toEncoded(url.toString(),
request.getSession().getId()));
}
}
}
}
return url.toString();
}
/**
* Finds the configuration definition for the specified action link
*
* @param request the current request.
* @param app the current ServletContext.
* @param linkString The action we are searching for, specified as a
* link. (i.e. may include "..")
* @return The SecureActionConfig object entry for this action,
* or null if not found
*/
private static SecureActionConfig getActionConfig(HttpServletRequest
request,
ServletContext app,
String linkString)
{
ModuleConfig moduleConfig = StrutsUtils.selectModule(linkString, app);
// Strip off the module path, if any
linkString = linkString.substring(moduleConfig.getPrefix().length());
// Use our servlet mapping, if one is specified
//String servletMapping = (String)app.getAttribute(Globals.SERVLET_KEY);
SecurePlugInInterface spi = (SecurePlugInInterface)app.getAttribute(
SecurePlugInInterface.SECURE_PLUGIN);
Iterator mappingItr = spi.getServletMappings().iterator();
while (mappingItr.hasNext())
{
String servletMapping = (String)mappingItr.next();
int starIndex = servletMapping != null ? servletMapping.indexOf('*')
: -1;
if (starIndex == -1)
{
continue;
} // No servlet mapping or no usable pattern defined, short circuit
String prefix = servletMapping.substring(0, starIndex);
String suffix = servletMapping.substring(starIndex + 1);
// Strip off the jsessionid, if any
int jsession = linkString.indexOf(";jsessionid=");
if (jsession >= 0)
{
linkString = linkString.substring(0, jsession);
}
// Strip off the query string, if any
// (differs from the SSL Ext. version - query string before anchor)
int question = linkString.indexOf("?");
if (question >= 0)
{
linkString = linkString.substring(0, question);
}
// Strip off the anchor, if any
int anchor = linkString.indexOf("#");
if (anchor >= 0)
{
linkString = linkString.substring(0, anchor);
}
// Unable to establish this link as an action, short circuit
if (!(linkString.startsWith(prefix) && linkString.endsWith(suffix)))
{
continue;
}
// Chop off prefix and suffix
linkString = linkString.substring(prefix.length());
linkString = linkString.substring(0,
linkString.length()
- suffix.length());
if (!linkString.startsWith("/"))
{
linkString = "/" + linkString;
}
SecureActionConfig secureConfig = (SecureActionConfig)moduleConfig.
findActionConfig(linkString);
return secureConfig;
}
return null;
}
/**
* Builds the protocol, server name, and port portion of the new URL
* @param request The current request
* @param desiredScheme The scheme (http or https) to be used in the new URL
* @param desiredPort The port number to be used in th enew URL
* @return The new URL as a StringBuffer
*/
private static StringBuffer startNewUrlString(HttpServletRequest request,
String desiredScheme,
String desiredPort)
{
StringBuffer url = new StringBuffer();
String serverName = request.getServerName();
url.append(desiredScheme).append("://").append(serverName);
if ((HTTP.equals(desiredScheme) && !STD_HTTP_PORT.equals(desiredPort)) ||
(HTTPS.equals(desiredScheme) && !STD_HTTPS_PORT.equals(desiredPort)))
{
url.append(":").append(desiredPort);
}
return url;
}
/**
* Return the specified URL with the specified session identifier
* suitably encoded.
*
* @param url URL to be encoded with the session id
* @param sessionId Session id to be included in the encoded URL
* @return the specified URL with the specified session identifier suitably encoded
*/
public String toEncoded(String url, String sessionId)
{
if (url == null || sessionId == null)
{
return (url);
}
String path = url;
String query = "";
String anchor = "";
// (differs from the SSL Ext. version - anchor before query string)
int pound = url.indexOf('#');
if (pound >= 0)
{
path = url.substring(0, pound);
anchor = url.substring(pound);
}
int question = path.indexOf('?');
if (question >= 0)
{
query = path.substring(question);
path = path.substring(0, question);
}
StringBuffer sb = new StringBuffer(path);
// jsessionid can't be first.
if (sb.length() > 0)
{
sb.append(";jsessionid=");
sb.append(sessionId);
}
sb.append(query);
sb.append(anchor);
return sb.toString();
}
}
|
src/java/org/apache/velocity/tools/struts/SecureLinkTool.java
|
package org.apache.velocity.tools.struts;
/*
* 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.
*/
import java.util.Iterator;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.SecurePlugInInterface;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.config.SecureActionConfig;
import org.apache.velocity.tools.view.tools.LinkTool;
/**
* Tool to be able to use Struts SSL Extensions with Velocity.
* <p>It has the same interface as StrutsLinkTool and can function as a
* substitute if Struts 1.1 and SSL Ext are installed. </p>
* <p>Usage:
* <pre>
* Template example:
* <!-- Use just like a regular StrutsLinkTool -->
* $link.action.nameOfAction
* $link.action.nameOfForward
*
* If the action or forward is marked as secure, or not,
* in your struts-config then the link will be rendered
* with https or http accordingly.
*
* Toolbox configuration:
* <tool>
* <key>link</key>
* <scope>request</scope>
* <class>org.apache.velocity.tools.struts.SecureLinkTool</class>
* </tool>
* </pre>
* </p>
* @since VelocityTools 1.1
* @author <a href="mailto:marinoj@centrum.is">Marino A. Jonsson</a>
* @version $Revision$ $Date$
*/
public class SecureLinkTool extends LinkTool
{
private static final String HTTP = "http";
private static final String HTTPS = "https";
private static final String STD_HTTP_PORT = "80";
private static final String STD_HTTPS_PORT = "443";
/**
* <p>Returns a copy of the link with the given action name
* converted into a server-relative URI reference. This method
* does not check if the specified action really is defined.
* This method will overwrite any previous URI reference settings
* but will copy the query string.</p>
*
* @param action an action path as defined in struts-config.xml
*
* @return a new instance of StrutsLinkTool
*/
public SecureLinkTool setAction(String action)
{
String link = StrutsUtils.getActionMappingURL(application, request, action);
return (SecureLinkTool)copyWith(computeURL(request, application, link));
}
/**
* <p>Returns a copy of the link with the given global forward name
* converted into a server-relative URI reference. If the parameter
* does not map to an existing global forward name, <code>null</code>
* is returned. This method will overwrite any previous URI reference
* settings but will copy the query string.</p>
*
* @param forward a global forward name as defined in struts-config.xml
*
* @return a new instance of StrutsLinkTool
*/
public SecureLinkTool setForward(String forward)
{
String url = StrutsUtils.getForwardURL(request, application, forward);
if (url == null)
{
return null;
}
return (SecureLinkTool)copyWith(url);
}
/**
* Compute a hyperlink URL based on the specified action link.
* The returned URL will have already been passed to
* <code>response.encodeURL()</code> for adding a session identifier.
*
* @param request the current request.
* @param app the current ServletContext.
* @param link the action that is to be converted to a hyperlink URL
* @return the computed hyperlink URL
*/
public String computeURL(HttpServletRequest request,
ServletContext app, String link)
{
StringBuffer url = new StringBuffer(link);
String contextPath = request.getContextPath();
SecurePlugInInterface securePlugin = (SecurePlugInInterface)app.getAttribute(SecurePlugInInterface.SECURE_PLUGIN);
if (securePlugin.getSslExtEnable() &&
url.toString().startsWith(contextPath))
{
// Initialize the scheme and ports we are using
String usingScheme = request.getScheme();
String usingPort = String.valueOf(request.getServerPort());
// Get the servlet context relative link URL
String linkString = url.toString().substring(contextPath.length());
// See if link references an action somewhere in our app
SecureActionConfig secureConfig = getActionConfig(request, app, linkString);
// If link is an action, find the desired port and scheme
if (secureConfig != null &&
!SecureActionConfig.ANY.equalsIgnoreCase(secureConfig.getSecure()))
{
String desiredScheme = Boolean.valueOf(secureConfig.getSecure()).booleanValue() ?
HTTPS : HTTP;
String desiredPort = Boolean.valueOf(secureConfig.getSecure()).booleanValue() ?
securePlugin.getHttpsPort() : securePlugin.getHttpPort();
// If scheme and port we are using do not match the ones we want
if (!desiredScheme.equals(usingScheme) ||
!desiredPort.equals(usingPort))
{
url.insert(0, startNewUrlString(request, desiredScheme, desiredPort));
// This is a hack to help us overcome the problem that some
// older browsers do not share sessions between http & https
// If this feature is diabled, session ID could still be added
// the previous call to the RequestUtils.computeURL() method,
// but only if needed due to cookies disabled, etc.
if (securePlugin.getSslExtAddSession() && url.toString().indexOf(";jsessionid=") < 0)
{
// Add the session identifier
url = new StringBuffer(toEncoded(url.toString(),
request.getSession().getId()));
}
}
}
}
return url.toString();
}
/**
* Finds the configuration definition for the specified action link
*
* @param request the current request.
* @param app the current ServletContext.
* @param linkString The action we are searching for, specified as a
* link. (i.e. may include "..")
* @return The SecureActionConfig object entry for this action,
* or null if not found
*/
private static SecureActionConfig getActionConfig(HttpServletRequest
request,
ServletContext app,
String linkString)
{
ModuleConfig moduleConfig = StrutsUtils.selectModule(linkString, app);
// Strip off the module path, if any
linkString = linkString.substring(moduleConfig.getPrefix().length());
// Use our servlet mapping, if one is specified
//String servletMapping = (String)app.getAttribute(Globals.SERVLET_KEY);
SecurePlugInInterface spi = (SecurePlugInInterface)app.getAttribute(
SecurePlugInInterface.SECURE_PLUGIN);
Iterator mappingItr = spi.getServletMappings().iterator();
while (mappingItr.hasNext())
{
String servletMapping = (String)mappingItr.next();
int starIndex = servletMapping != null ? servletMapping.indexOf('*')
: -1;
if (starIndex == -1)
{
continue;
} // No servlet mapping or no usable pattern defined, short circuit
String prefix = servletMapping.substring(0, starIndex);
String suffix = servletMapping.substring(starIndex + 1);
// Strip off the jsessionid, if any
int jsession = linkString.indexOf(";jsessionid=");
if (jsession >= 0)
{
linkString = linkString.substring(0, jsession);
}
// Strip off the query string, if any
// (differs from the SSL Ext. version - query string before anchor)
int question = linkString.indexOf("?");
if (question >= 0)
{
linkString = linkString.substring(0, question);
}
// Strip off the anchor, if any
int anchor = linkString.indexOf("#");
if (anchor >= 0)
{
linkString = linkString.substring(0, anchor);
}
// Unable to establish this link as an action, short circuit
if (!(linkString.startsWith(prefix) && linkString.endsWith(suffix)))
{
continue;
}
// Chop off prefix and suffix
linkString = linkString.substring(prefix.length());
linkString = linkString.substring(0,
linkString.length()
- suffix.length());
if (!linkString.startsWith("/"))
{
linkString = "/" + linkString;
}
SecureActionConfig secureConfig = (SecureActionConfig)moduleConfig.
findActionConfig(linkString);
return secureConfig;
}
return null;
}
/**
* Builds the protocol, server name, and port portion of the new URL
* @param request The current request
* @param desiredScheme The scheme (http or https) to be used in the new URL
* @param desiredPort The port number to be used in th enew URL
* @return The new URL as a StringBuffer
*/
private static StringBuffer startNewUrlString(HttpServletRequest request,
String desiredScheme,
String desiredPort)
{
StringBuffer url = new StringBuffer();
String serverName = request.getServerName();
url.append(desiredScheme).append("://").append(serverName);
if ((HTTP.equals(desiredScheme) && !STD_HTTP_PORT.equals(desiredPort)) ||
(HTTPS.equals(desiredScheme) && !STD_HTTPS_PORT.equals(desiredPort)))
{
url.append(":").append(desiredPort);
}
return url;
}
/**
* Return the specified URL with the specified session identifier
* suitably encoded.
*
* @param url URL to be encoded with the session id
* @param sessionId Session id to be included in the encoded URL
* @return the specified URL with the specified session identifier suitably encoded
*/
public String toEncoded(String url, String sessionId)
{
if (url == null || sessionId == null)
{
return (url);
}
String path = url;
String query = "";
String anchor = "";
// (differs from the SSL Ext. version - anchor before query string)
int pound = url.indexOf('#');
if (pound >= 0)
{
path = url.substring(0, pound);
anchor = url.substring(pound);
}
int question = path.indexOf('?');
if (question >= 0)
{
query = path.substring(question);
path = path.substring(0, question);
}
StringBuffer sb = new StringBuffer(path);
// jsessionid can't be first.
if (sb.length() > 0)
{
sb.append(";jsessionid=");
sb.append(sessionId);
}
sb.append(query);
sb.append(anchor);
return sb.toString();
}
}
|
s/1.1/1.x in javadoc
git-svn-id: 08feff1e20460d5e8b75c2f5109ada1fb2e66d41@487322 13f79535-47bb-0310-9956-ffa450edef68
|
src/java/org/apache/velocity/tools/struts/SecureLinkTool.java
|
s/1.1/1.x in javadoc
|
|
Java
|
apache-2.0
|
a849f86e4ca68a0031b470bfc343b6f5551f6ebd
| 0
|
dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android
|
package org.commcare.dalvik.activities;
import org.commcare.android.adapters.AppManagerAdapter;
import org.commcare.android.util.SessionUnavailableException;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.dalvik.services.CommCareSessionService;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
/**
* The activity that starts up when a user launches into the app manager.
* Displays a list of all installed apps, each of which can be clicked to launch
* the SingleAppManagerActivity for that app. Also includes a button for
* installing new apps.
*
* @author amstone326
*/
public class AppManagerActivity extends Activity implements OnItemClickListener {
public static final String KEY_LAUNCH_FROM_MANAGER = "from_manager";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app_manager);
((ListView)this.findViewById(R.id.apps_list_view)).setOnItemClickListener(this);
}
@Override
public void onResume() {
super.onResume();
refreshView();
}
/**
* Refresh the list of installed apps
*/
private void refreshView() {
ListView lv = (ListView)findViewById(R.id.apps_list_view);
lv.setAdapter(new AppManagerAdapter(this, android.R.layout.simple_list_item_1,
CommCareApplication._().appRecordArray()));
}
/**
* onClick method for the Install An App button
*
* @param v unused argument necessary for the method's use as an onClick handler.
*/
public void installAppClicked(View v) {
try {
CommCareSessionService s = CommCareApplication._().getSession();
if (s.isActive()) {
triggerLogoutWarning();
} else {
installApp();
}
} catch (SessionUnavailableException e) {
installApp();
}
}
/**
* Logs the user out and takes them to the app installation activitiy.
*/
private void installApp() {
try {
CommCareApplication._().getSession().closeSession(false);
} catch (SessionUnavailableException e) {
// If the session isn't available, we don't need to logout
}
Intent i = new Intent(getApplicationContext(), CommCareSetupActivity.class);
i.putExtra(KEY_LAUNCH_FROM_MANAGER, true);
this.startActivityForResult(i, CommCareHomeActivity.INIT_APP);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case CommCareHomeActivity.INIT_APP:
boolean installFailed = intent != null && intent.getBooleanExtra(
CommCareSetupActivity.KEY_INSTALL_FAILED, false);
if (resultCode == RESULT_OK && !installFailed) {
if (!CommCareApplication._().getCurrentApp().areResourcesValidated()) {
Intent i = new Intent(this, CommCareVerificationActivity.class);
i.putExtra(KEY_LAUNCH_FROM_MANAGER, true);
this.startActivityForResult(i, CommCareHomeActivity.MISSING_MEDIA_ACTIVITY);
} else {
Toast.makeText(this, "New app installed successfully", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "No app was installed!", Toast.LENGTH_LONG).show();
}
break;
case CommCareHomeActivity.MISSING_MEDIA_ACTIVITY:
if (resultCode == RESULT_CANCELED) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Media Not Verified");
builder.setMessage(R.string.skipped_verification_warning)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else if (resultCode == RESULT_OK) {
Toast.makeText(this, "Media Validated!", Toast.LENGTH_LONG).show();
}
break;
}
}
/**
* Redirects user to SingleAppManager when they select a particular app.
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent i = new Intent(getApplicationContext(),
SingleAppManagerActivity.class);
// Pass to SingleAppManager the index of the app that was selected, so it knows which
// app to display information for
i.putExtra("position", position);
startActivity(i);
}
/**
* Warns user that the action they are trying to conduct will result in the current
* session being logged out
*/
private void triggerLogoutWarning() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Logging out your app");
builder.setMessage(R.string.logout_warning)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
installApp();
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
|
app/src/org/commcare/dalvik/activities/AppManagerActivity.java
|
package org.commcare.dalvik.activities;
import org.commcare.android.adapters.AppManagerAdapter;
import org.commcare.android.util.SessionUnavailableException;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.dalvik.services.CommCareSessionService;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
/**
* The activity that starts up when a user launches into the app manager.
* Displays a list of all installed apps, each of which can be clicked to launch
* the SingleAppManagerActivity for that app. Also includes a button for
* installing new apps.
*
* @author amstone326
*/
public class AppManagerActivity extends Activity implements OnItemClickListener {
public static final String KEY_LAUNCH_FROM_MANAGER = "from_manager";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app_manager);
((ListView)this.findViewById(R.id.apps_list_view)).setOnItemClickListener(this);
}
public void onResume() {
super.onResume();
refreshView();
}
/**
* Refresh the list of installed apps
*/
private void refreshView() {
ListView lv = (ListView)findViewById(R.id.apps_list_view);
lv.setAdapter(new AppManagerAdapter(this, android.R.layout.simple_list_item_1,
CommCareApplication._().appRecordArray()));
}
/**
* onClick method for the Install An App button
*
* @param v unused argument necessary for the method's use as an onClick handler.
*/
public void installAppClicked(View v) {
try {
CommCareSessionService s = CommCareApplication._().getSession();
if (s.isActive()) {
triggerLogoutWarning();
} else {
installApp();
}
} catch (SessionUnavailableException e) {
installApp();
}
}
/**
* Logs the user out and takes them to the app installation activitiy.
*/
private void installApp() {
try {
CommCareApplication._().getSession().closeSession(false);
} catch (SessionUnavailableException e) {
// If the session isn't available, we don't need to logout
}
Intent i = new Intent(getApplicationContext(), CommCareSetupActivity.class);
i.putExtra(KEY_LAUNCH_FROM_MANAGER, true);
this.startActivityForResult(i, CommCareHomeActivity.INIT_APP);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case CommCareHomeActivity.INIT_APP:
boolean installFailed = intent != null && intent.getBooleanExtra(
CommCareSetupActivity.KEY_INSTALL_FAILED, false);
if (resultCode == RESULT_OK && !installFailed) {
if (!CommCareApplication._().getCurrentApp().areResourcesValidated()) {
Intent i = new Intent(this, CommCareVerificationActivity.class);
i.putExtra(KEY_LAUNCH_FROM_MANAGER, true);
this.startActivityForResult(i, CommCareHomeActivity.MISSING_MEDIA_ACTIVITY);
} else {
Toast.makeText(this, "New app installed successfully", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "No app was installed!", Toast.LENGTH_LONG).show();
}
break;
case CommCareHomeActivity.MISSING_MEDIA_ACTIVITY:
if (resultCode == RESULT_CANCELED) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Media Not Verified");
builder.setMessage(R.string.skipped_verification_warning)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else if (resultCode == RESULT_OK) {
Toast.makeText(this, "Media Validated!", Toast.LENGTH_LONG).show();
}
break;
}
}
/**
* Redirects user to SingleAppManager when they select a particular app.
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent i = new Intent(getApplicationContext(),
SingleAppManagerActivity.class);
// Pass to SingleAppManager the index of the app that was selected, so it knows which
// app to display information for
i.putExtra("position", position);
startActivity(i);
}
/**
* Warns user that the action they are trying to conduct will result in the current
* session being logged out
*/
private void triggerLogoutWarning() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Logging out your app");
builder.setMessage(R.string.logout_warning)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
installApp();
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
|
Added missing override
|
app/src/org/commcare/dalvik/activities/AppManagerActivity.java
|
Added missing override
|
|
Java
|
apache-2.0
|
887b68c813c6175c8e5fe0e64d32cfb4de0bd6ab
| 0
|
datazuul/com.datazuul.apps--datazuul-radio,datazuul/com.datazuul.apps--datazuul-radio
|
package com.datazuul.apps.jradio;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.dyno.visual.swing.layouts.Constraints;
import org.dyno.visual.swing.layouts.GroupLayout;
import org.dyno.visual.swing.layouts.Leading;
import org.dyno.visual.swing.layouts.Trailing;
//VS4E -- DO NOT REMOVE THIS LINE!
public class RadioGUI extends JFrame {
private RadioPlayerThread radioPlayerThread = null;
private Preferences prefs = null;
private static final long serialVersionUID = 1L;
private JList stationList;
private JScrollPane stationListScrollPane;
private JLabel speakerLabel;
private JButton addButton;
private JMenuItem menuFileQuit;
private JMenu menuFile;
private JMenuBar menuBar;
private JMenuItem menuHelpAbout;
private JMenu menuHelp;
private JButton delButton;
private static final String PREFERRED_LOOK_AND_FEEL = "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel";
public RadioGUI() {
initPrefs();
initComponents();
}
private void initPrefs() {
// This will define a node in which the preferences can be stored
// System.out.println("node=" + this.getClass().getCanonicalName());
prefs = Preferences.userRoot().node("net/jubuntu/jradio");
String[] keys = null;
try {
keys = prefs.keys();
} catch (BackingStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (keys.length == 0) {
prefs.put("Bayern 1 (Niederbayern / Oberpfalz)",
"https://dispatcher.rndfnk.com/br/br1/nbopf/mp3/mid");
prefs.put("Bayern 2 (Süd)",
"https://dispatcher.rndfnk.com/br/br2/sued/mp3/mid");
prefs.put("Bayern 3",
"https://dispatcher.rndfnk.com/br/br3/live/mp3/mid");
prefs.put("Hardradio.com", "http://144.217.29.205:80/");
prefs.put("Schattenreich",
"http://stream.laut.fm/schattenreich");
try {
prefs.flush();
} catch (BackingStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void initComponents() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new GroupLayout());
add(getStationListScrollPane(), new Constraints(new Leading(200, 300,
10, 10), new Leading(12, 192, 10, 10)));
add(getSpeakerLabel(), new Constraints(new Leading(12, 176, 10, 10),
new Leading(11, 193, 12, 12)));
add(getAddButton(), new Constraints(new Leading(356, 59, 12, 12),
new Trailing(12, 46, 216)));
add(getDelButton(), new Constraints(new Leading(284, 60, 12, 12),
new Trailing(12, 46, 216)));
setJMenuBar(getJMenuBar0());
setSize(510, 265);
}
private JButton getDelButton() {
if (delButton == null) {
delButton = new JButton();
delButton.setText("-");
delButton.setToolTipText("Delete selected radio station");
delButton.setMnemonic('D');
delButton.setPreferredSize(new Dimension(45, 25));
delButton.setMaximumSize(new Dimension(45, 25));
delButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
delButtonActionActionPerformed(event);
}
});
}
return delButton;
}
private JMenu getMenuHelp() {
if (menuHelp == null) {
menuHelp = new JMenu();
menuHelp.setText("Help");
menuHelp.setOpaque(false);
menuHelp.add(getMenuHelpAbout());
}
return menuHelp;
}
private JMenuItem getMenuHelpAbout() {
if (menuHelpAbout == null) {
menuHelpAbout = new JMenuItem();
menuHelpAbout.setText("About");
menuHelpAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
menuHelpAboutActionActionPerformed(event);
}
});
}
return menuHelpAbout;
}
private JMenuBar getJMenuBar0() {
if (menuBar == null) {
menuBar = new JMenuBar();
menuBar.add(getMenuFile());
menuBar.add(getMenuHelp());
}
return menuBar;
}
private JMenu getMenuFile() {
if (menuFile == null) {
menuFile = new JMenu();
menuFile.setText("File");
menuFile.setOpaque(false);
menuFile.add(getMenuFileQuit());
}
return menuFile;
}
private JMenuItem getMenuFileQuit() {
if (menuFileQuit == null) {
menuFileQuit = new JMenuItem();
menuFileQuit.setText("Quit");
menuFileQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
menuFileQuitActionActionPerformed(event);
}
});
}
return menuFileQuit;
}
public void actionPerformed(ActionEvent e) {
if ("addStation".equals(e.getActionCommand())) {
System.out.println("klick");
} else {
System.out.println("uups");
}
}
private JButton getAddButton() {
if (addButton == null) {
addButton = new JButton();
addButton.setText("+");
addButton.setToolTipText("Add a radio station");
addButton.setPreferredSize(new Dimension(60, 25));
addButton.setMaximumSize(new Dimension(60, 25));
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
addButtonActionActionPerformed(event);
}
});
}
return addButton;
}
private JLabel getSpeakerLabel() {
if (speakerLabel == null) {
speakerLabel = new JLabel();
URL imageURL = this.getClass().getResource("images/speaker-02.png");
ImageIcon ii = new ImageIcon(imageURL);
// Image img = ii.getImage();
// Image newimg =
// img.getScaledInstance(speakerLabel.getSize().width,
// speakerLabel.getSize().height, Image.SCALE_SMOOTH);
// ii = new ImageIcon(newimg);
speakerLabel.setIcon(ii);
}
return speakerLabel;
}
private JScrollPane getStationListScrollPane() {
if (stationListScrollPane == null) {
stationListScrollPane = new JScrollPane();
stationListScrollPane.setViewportView(getStationList());
}
return stationListScrollPane;
}
private JList getStationList() {
if (stationList == null) {
stationList = new JList();
stationList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
stationList.setLayoutOrientation(JList.VERTICAL);
DefaultListModel listModel = new DefaultListModel();
String[] keys = null;
try {
keys = prefs.keys();
} catch (BackingStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (keys != null) {
for (int i = 0; i < keys.length; i++) {
String key = keys[i];
listModel.addElement(new RadioStation(key, prefs.get(key,
"")));
}
}
stationList.setModel(listModel);
// stationList.setSelectedIndex(-1);
stationList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
ensureEventThread();
if (event.getValueIsAdjusting() == false) {
stationListSelectionValueChanged(event);
}
}
});
}
return stationList;
}
private void ensureEventThread() {
if (SwingUtilities.isEventDispatchThread()) {
return;
}
throw new RuntimeException("no event thread");
}
private static void installLnF() {
try {
String lnfClassname = PREFERRED_LOOK_AND_FEEL;
if (lnfClassname == null)
lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(lnfClassname);
} catch (Exception e) {
System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
+ " on this platform:" + e.getMessage());
}
}
/**
* Main entry of the class. Note: This class is only created so that you can
* easily preview the result at runtime. It is not expected to be managed by
* the designer. You can modify it as you like.
*/
public static void main(String[] args) {
installLnF();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
RadioGUI frame = new RadioGUI();
frame.setDefaultCloseOperation(RadioGUI.EXIT_ON_CLOSE);
frame.setTitle("JRadio");
frame.getContentPane().setPreferredSize(frame.getSize());
// frame.getContentPane().setBackground(new Color(205, 235,
// 139));
URL imageURL = this.getClass().getResource(
"images/radio-icon-36x36.png");
ImageIcon ii = new ImageIcon(imageURL);
frame.setIconImage(ii.getImage());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private void stationListSelectionValueChanged(ListSelectionEvent event) {
if (radioPlayerThread != null) {
radioPlayerThread.stopIt();
}
RadioStation station = (RadioStation) stationList.getSelectedValue();
// stationList.setSelectedIndex(stationList.getSelectedIndex());
if (station != null) {
final String url = station.getUrl();
radioPlayerThread = new RadioPlayerThread(url);
radioPlayerThread.start();
}
}
private void addButtonActionActionPerformed(ActionEvent event) {
System.out.println("klick");
AddRadioStationDialog dlg = new AddRadioStationDialog(this,
"Add a new radio station", true);
dlg.pack();
dlg.setLocationRelativeTo(getParent());
dlg.setVisible(true);
String radioStationName = dlg.getRadioStationName();
String streamUrl = dlg.getStreamUrl();
if (radioStationName != null && streamUrl != null) {
if (streamUrl.toLowerCase().endsWith(".m3u")
|| streamUrl.toLowerCase().endsWith(".pls")) {
URL playlistUrl = null;
try {
playlistUrl = new URL(streamUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
URL[] urls = PlaylistParser.parse(playlistUrl);
streamUrl = urls[0].toString();
}
System.out.println("name=" + radioStationName + ", url="
+ streamUrl);
prefs.put(radioStationName, streamUrl);
try {
prefs.flush();
} catch (BackingStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DefaultListModel model = (DefaultListModel) getStationList()
.getModel();
model.addElement(new RadioStation(radioStationName, streamUrl));
getStationList().setSelectedIndex(-1);
}
}
private void delButtonActionActionPerformed(ActionEvent event) {
RadioStation station = (RadioStation) stationList.getSelectedValue();
if (station != null) {
int n = JOptionPane.showConfirmDialog(this,
"Do you really want to remove the radio station \""
+ station.getLabel() + "\"?", "Confirm Deletion",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
prefs.remove(station.getLabel());
try {
prefs.flush();
} catch (BackingStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DefaultListModel model = (DefaultListModel) getStationList()
.getModel();
model.removeElement(station);
getStationList().clearSelection();
} else if (n == JOptionPane.NO_OPTION) {
} else {
}
}
}
private void menuFileQuitActionActionPerformed(ActionEvent event) {
System.exit(0);
}
private void menuHelpAboutActionActionPerformed(ActionEvent event) {
DialogAbout dlg = new DialogAbout();
dlg.setModal(true);
// dlg.pack();
dlg.setLocationRelativeTo(getParent());
dlg.setVisible(true);
}
}
|
src/main/java/com/datazuul/apps/jradio/RadioGUI.java
|
package com.datazuul.apps.jradio;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.dyno.visual.swing.layouts.Constraints;
import org.dyno.visual.swing.layouts.GroupLayout;
import org.dyno.visual.swing.layouts.Leading;
import org.dyno.visual.swing.layouts.Trailing;
//VS4E -- DO NOT REMOVE THIS LINE!
public class RadioGUI extends JFrame {
private RadioPlayerThread radioPlayerThread = null;
private Preferences prefs = null;
private static final long serialVersionUID = 1L;
private JList stationList;
private JScrollPane stationListScrollPane;
private JLabel speakerLabel;
private JButton addButton;
private JMenuItem menuFileQuit;
private JMenu menuFile;
private JMenuBar menuBar;
private JMenuItem menuHelpAbout;
private JMenu menuHelp;
private JButton delButton;
private static final String PREFERRED_LOOK_AND_FEEL = "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel";
public RadioGUI() {
initPrefs();
initComponents();
}
private void initPrefs() {
// This will define a node in which the preferences can be stored
// System.out.println("node=" + this.getClass().getCanonicalName());
prefs = Preferences.userRoot().node("net/jubuntu/jradio");
String[] keys = null;
try {
keys = prefs.keys();
} catch (BackingStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (keys.length == 0) {
prefs.put("Bayern 1",
"http://gffstream.ic.llnwd.net/stream/gffstream_w10b");
prefs.put("Bayern 2",
"http://gffstream.ic.llnwd.net/stream/gffstream_w11b");
prefs.put("Bayern 3",
"http://gffstream.ic.llnwd.net/stream/gffstream_w12b");
prefs.put("Hardradio.com", "http://66.90.91.59:80/hardradio.mp3");
prefs.put("Radio Gothic",
"http://ice-03.lagardere.cz:80/web-gothic-128");
try {
prefs.flush();
} catch (BackingStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void initComponents() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new GroupLayout());
add(getStationListScrollPane(), new Constraints(new Leading(200, 300,
10, 10), new Leading(12, 192, 10, 10)));
add(getSpeakerLabel(), new Constraints(new Leading(12, 176, 10, 10),
new Leading(11, 193, 12, 12)));
add(getAddButton(), new Constraints(new Leading(356, 59, 12, 12),
new Trailing(12, 46, 216)));
add(getDelButton(), new Constraints(new Leading(284, 60, 12, 12),
new Trailing(12, 46, 216)));
setJMenuBar(getJMenuBar0());
setSize(510, 265);
}
private JButton getDelButton() {
if (delButton == null) {
delButton = new JButton();
delButton.setText("-");
delButton.setToolTipText("Delete selected radio station");
delButton.setMnemonic('D');
delButton.setPreferredSize(new Dimension(45, 25));
delButton.setMaximumSize(new Dimension(45, 25));
delButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
delButtonActionActionPerformed(event);
}
});
}
return delButton;
}
private JMenu getMenuHelp() {
if (menuHelp == null) {
menuHelp = new JMenu();
menuHelp.setText("Help");
menuHelp.setOpaque(false);
menuHelp.add(getMenuHelpAbout());
}
return menuHelp;
}
private JMenuItem getMenuHelpAbout() {
if (menuHelpAbout == null) {
menuHelpAbout = new JMenuItem();
menuHelpAbout.setText("About");
menuHelpAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
menuHelpAboutActionActionPerformed(event);
}
});
}
return menuHelpAbout;
}
private JMenuBar getJMenuBar0() {
if (menuBar == null) {
menuBar = new JMenuBar();
menuBar.add(getMenuFile());
menuBar.add(getMenuHelp());
}
return menuBar;
}
private JMenu getMenuFile() {
if (menuFile == null) {
menuFile = new JMenu();
menuFile.setText("File");
menuFile.setOpaque(false);
menuFile.add(getMenuFileQuit());
}
return menuFile;
}
private JMenuItem getMenuFileQuit() {
if (menuFileQuit == null) {
menuFileQuit = new JMenuItem();
menuFileQuit.setText("Quit");
menuFileQuit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
menuFileQuitActionActionPerformed(event);
}
});
}
return menuFileQuit;
}
public void actionPerformed(ActionEvent e) {
if ("addStation".equals(e.getActionCommand())) {
System.out.println("klick");
} else {
System.out.println("uups");
}
}
private JButton getAddButton() {
if (addButton == null) {
addButton = new JButton();
addButton.setText("+");
addButton.setToolTipText("Add a radio station");
addButton.setPreferredSize(new Dimension(60, 25));
addButton.setMaximumSize(new Dimension(60, 25));
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
addButtonActionActionPerformed(event);
}
});
}
return addButton;
}
private JLabel getSpeakerLabel() {
if (speakerLabel == null) {
speakerLabel = new JLabel();
URL imageURL = this.getClass().getResource("images/speaker-02.png");
ImageIcon ii = new ImageIcon(imageURL);
// Image img = ii.getImage();
// Image newimg =
// img.getScaledInstance(speakerLabel.getSize().width,
// speakerLabel.getSize().height, Image.SCALE_SMOOTH);
// ii = new ImageIcon(newimg);
speakerLabel.setIcon(ii);
}
return speakerLabel;
}
private JScrollPane getStationListScrollPane() {
if (stationListScrollPane == null) {
stationListScrollPane = new JScrollPane();
stationListScrollPane.setViewportView(getStationList());
}
return stationListScrollPane;
}
private JList getStationList() {
if (stationList == null) {
stationList = new JList();
stationList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
stationList.setLayoutOrientation(JList.VERTICAL);
DefaultListModel listModel = new DefaultListModel();
String[] keys = null;
try {
keys = prefs.keys();
} catch (BackingStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (keys != null) {
for (int i = 0; i < keys.length; i++) {
String key = keys[i];
listModel.addElement(new RadioStation(key, prefs.get(key,
"")));
}
}
stationList.setModel(listModel);
// stationList.setSelectedIndex(-1);
stationList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
ensureEventThread();
if (event.getValueIsAdjusting() == false) {
stationListSelectionValueChanged(event);
}
}
});
}
return stationList;
}
private void ensureEventThread() {
if (SwingUtilities.isEventDispatchThread()) {
return;
}
throw new RuntimeException("no event thread");
}
private static void installLnF() {
try {
String lnfClassname = PREFERRED_LOOK_AND_FEEL;
if (lnfClassname == null)
lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(lnfClassname);
} catch (Exception e) {
System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
+ " on this platform:" + e.getMessage());
}
}
/**
* Main entry of the class. Note: This class is only created so that you can
* easily preview the result at runtime. It is not expected to be managed by
* the designer. You can modify it as you like.
*/
public static void main(String[] args) {
installLnF();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
RadioGUI frame = new RadioGUI();
frame.setDefaultCloseOperation(RadioGUI.EXIT_ON_CLOSE);
frame.setTitle("JRadio");
frame.getContentPane().setPreferredSize(frame.getSize());
// frame.getContentPane().setBackground(new Color(205, 235,
// 139));
URL imageURL = this.getClass().getResource(
"images/radio-icon-36x36.png");
ImageIcon ii = new ImageIcon(imageURL);
frame.setIconImage(ii.getImage());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private void stationListSelectionValueChanged(ListSelectionEvent event) {
if (radioPlayerThread != null) {
radioPlayerThread.stopIt();
}
RadioStation station = (RadioStation) stationList.getSelectedValue();
// stationList.setSelectedIndex(stationList.getSelectedIndex());
if (station != null) {
final String url = station.getUrl();
radioPlayerThread = new RadioPlayerThread(url);
radioPlayerThread.start();
}
}
private void addButtonActionActionPerformed(ActionEvent event) {
System.out.println("klick");
AddRadioStationDialog dlg = new AddRadioStationDialog(this,
"Add a new radio station", true);
dlg.pack();
dlg.setLocationRelativeTo(getParent());
dlg.setVisible(true);
String radioStationName = dlg.getRadioStationName();
String streamUrl = dlg.getStreamUrl();
if (radioStationName != null && streamUrl != null) {
if (streamUrl.toLowerCase().endsWith(".m3u")
|| streamUrl.toLowerCase().endsWith(".pls")) {
URL playlistUrl = null;
try {
playlistUrl = new URL(streamUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
URL[] urls = PlaylistParser.parse(playlistUrl);
streamUrl = urls[0].toString();
}
System.out.println("name=" + radioStationName + ", url="
+ streamUrl);
prefs.put(radioStationName, streamUrl);
try {
prefs.flush();
} catch (BackingStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DefaultListModel model = (DefaultListModel) getStationList()
.getModel();
model.addElement(new RadioStation(radioStationName, streamUrl));
getStationList().setSelectedIndex(-1);
}
}
private void delButtonActionActionPerformed(ActionEvent event) {
RadioStation station = (RadioStation) stationList.getSelectedValue();
if (station != null) {
int n = JOptionPane.showConfirmDialog(this,
"Do you really want to remove the radio station \""
+ station.getLabel() + "\"?", "Confirm Deletion",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
prefs.remove(station.getLabel());
try {
prefs.flush();
} catch (BackingStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DefaultListModel model = (DefaultListModel) getStationList()
.getModel();
model.removeElement(station);
getStationList().clearSelection();
} else if (n == JOptionPane.NO_OPTION) {
} else {
}
}
}
private void menuFileQuitActionActionPerformed(ActionEvent event) {
System.exit(0);
}
private void menuHelpAboutActionActionPerformed(ActionEvent event) {
DialogAbout dlg = new DialogAbout();
dlg.setModal(true);
// dlg.pack();
dlg.setLocationRelativeTo(getParent());
dlg.setVisible(true);
}
}
|
Fix channels
|
src/main/java/com/datazuul/apps/jradio/RadioGUI.java
|
Fix channels
|
|
Java
|
apache-2.0
|
f3c10fb350296942e7cd29e472c4346c8b598eae
| 0
|
sowmyav24/twu-biblioteca-SowmyaV
|
package com.twu.biblioteca;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
HashMap<Book, Boolean> book = new HashMap<>();
book.put(new Book("The Monk Who Sold His Ferrari", "Robin Sharma", "2007"), true);
Books books = new Books(book);
BibliotecaAppView bibliotecaAppView = new BibliotecaAppView(scanner);
BooksController booksController = new BooksController(bibliotecaAppView, books);
HashMap<Integer, MenuActionPerformed> menuItems = new HashMap<>();
menuItems.put(1, new ListBooks(booksController));
menuItems.put(2, new InvalidMenuOption(bibliotecaAppView));
Menu menu = new Menu(menuItems);
MenuController menuController = new MenuController(bibliotecaAppView, menu);
BibliotecaApp bibliotecaApp = new BibliotecaApp(bibliotecaAppView, menuController, booksController);
bibliotecaApp.start();
}
}
|
src/com/twu/biblioteca/Main.java
|
package com.twu.biblioteca;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
HashMap<Book, Boolean> book = new HashMap<>();
book.put(new Book("The Monk Who Sold His Ferrari", "Robin Sharma", "2007"), true);
Books books = new Books(book);
BibliotecaAppView bibliotecaAppView = new BibliotecaAppView(scanner);
BooksController booksController = new BooksController(bibliotecaAppView, books);
HashMap<Integer, MenuActionPerformed> menuItems = new HashMap<>();
menuItems.put(1, new ListBooks(booksController));
menuItems.put(2, new InvalidMenuOption(bibliotecaAppView));
Menu menu = new Menu(menuItems);
MenuController menuController = new MenuController(bibliotecaAppView, menu);
}
}
|
Added start function and caled it from main
|
src/com/twu/biblioteca/Main.java
|
Added start function and caled it from main
|
|
Java
|
apache-2.0
|
a4c6f49d47517ef972302f897e740bc884b70db8
| 0
|
99soft/guartz
|
package org.nnsoft.guice.guartz;
/*
* Copyright 2009-2012 The 99 Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import static java.lang.String.format;
import static java.util.TimeZone.getDefault;
import static org.nnsoft.guice.guartz.Scheduled.DEFAULT;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import static org.quartz.utils.Key.DEFAULT_GROUP;
import java.util.TimeZone;
import javax.inject.Inject;
import org.quartz.Job;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import com.google.inject.ProvisionException;
/**
* DSL to produce {@code Job} and add to a {@code Scheduler},
* and associate the related {@code Trigger} with it.
*/
public final class JobSchedulerBuilder {
/**
* The type of the {@code Job} to be executed.
*/
private final Class<? extends Job> jobClass;
/**
* The {@code Job} name, must be unique within the group.
*/
private String jobName = DEFAULT;
/**
* The {@code Job} group name.
*/
private String jobGroup = DEFAULT_GROUP;
/**
* Instructs the {@code Scheduler} whether or not the {@code Job} should
* be re-executed if a {@code recovery} or {@code fail-over} situation is
* encountered.
*/
private boolean requestRecovery = false;
/**
* Whether or not the {@code Job} should remain stored after it is
* orphaned (no {@code Trigger}s point to it).
*/
private boolean storeDurably = false;
/**
* The {@code Trigger} name, must be unique within the group.
*/
private String triggerName = DEFAULT;
/**
* The {@code Trigger} group.
*/
private String triggerGroup = DEFAULT_GROUP;
/**
* The cron expression to base the schedule on.
*/
private String cronExpression;
/**
* The time zone for which the {@code cronExpression}
* of this {@code CronTrigger} will be resolved.
*/
private TimeZone timeZone = getDefault();
/**
* The {@code Trigger}'s priority. When more than one {@code Trigger} have the same
* fire time, the scheduler will fire the one with the highest priority
* first.
*/
private int priority = 0;
/**
* The {@code Trigger} to be used to schedule the {@code Job}
*
* @since 1.2
*/
private Trigger trigger;
/**
* Creates a new {@code JobSchedulerBuilder} instance.
*
* This class can't be instantiated by users.
*
* @param jobClass The type of the {@code Job} to be executed
*/
JobSchedulerBuilder( final Class<? extends Job> jobClass )
{
this.jobClass = jobClass;
}
/**
* Sets the {@code Job} name, must be unique within the group.
*
* @param jobName The {@code Job} name, must be unique within the group
* @return This builder instance
*/
public JobSchedulerBuilder withJobName( String jobName )
{
this.jobName = jobName;
return this;
}
/**
* Sets the {@code Job} group.
*
* @param jobGroup The {@code Job} group
* @return This builder instance
*/
public JobSchedulerBuilder withJobGroup( String jobGroup )
{
this.jobGroup = jobGroup;
return this;
}
/**
* Instructs the {@code Scheduler} whether or not the {@code Job} should
* be re-executed if a {@code recovery} or {@code fail-over} situation is
* encountered.
*
* @param requestRecovery The activation flag
* @return This builder instance
*/
public JobSchedulerBuilder withRequestRecovery( boolean requestRecovery )
{
this.requestRecovery = requestRecovery;
return this;
}
/**
* Whether or not the {@code Job} should remain stored after it is
* orphaned (no {@code Trigger}s point to it).
*
* @param storeDurably The activation flag
* @return This builder instance
*/
public JobSchedulerBuilder withStoreDurably( boolean storeDurably )
{
this.storeDurably = storeDurably;
return this;
}
/**
* Sets the {@code Trigger} name, must be unique within the group.
*
* @param triggerName The {@code Trigger} name, must be unique within the group
* @return This builder instance
*/
public JobSchedulerBuilder withTriggerName( String triggerName )
{
this.triggerName = triggerName;
return this;
}
/**
* Sets the {@code Trigger} group.
*
* @param triggerGroup The {@code Trigger} group
* @return This builder instance
*/
public JobSchedulerBuilder withTriggerGroup( String triggerGroup )
{
this.triggerGroup = triggerGroup;
return this;
}
/**
* Sets the cron expression to base the schedule on.
*
* @param cronExpression The cron expression to base the schedule on
* @return This builder instance
*/
public JobSchedulerBuilder withCronExpression( String cronExpression )
{
this.cronExpression = cronExpression;
return this;
}
/**
* Sets the time zone for which the {@code cronExpression} of this
* {@code CronTrigger} will be resolved.
*
* @param timeZone The time zone for which the {@code cronExpression}
* of this {@code CronTrigger} will be resolved.
* @return This builder instance
*/
public JobSchedulerBuilder withTimeZone( TimeZone timeZone )
{
this.timeZone = timeZone;
return this;
}
/**
* Sets the {@code Trigger}'s priority. When more than one {@code Trigger} have the same
* fire time, the scheduler will fire the one with the highest priority
* first.
*
* @param priority The {@code Trigger}'s priority
* @return This builder instance
*/
public JobSchedulerBuilder withPriority( int priority )
{
this.priority = priority;
return this;
}
/**
* Sets the {@code Trigger} that will be used to schedule
* the {@code Job}.
*
* <p>
* Be aware that using using this method will override any other
* {@code Trigger}-related operation, like {@link #withTriggerGroup(String)}
* or {@link #withTimeZone(TimeZone)}
*
* @param trigger The {@code Trigger} to associate with the {@code Job}
* @return This builder instance
* @since 1.2
*/
public JobSchedulerBuilder withTrigger(Trigger trigger)
{
this.trigger = trigger;
return this;
}
/**
* Add the produced {@code Job} to the given {@code Scheduler},
* and associate the related {@code Trigger} with it.
*
* Users <b>MUST NOT</b> use this method!
*
* @param scheduler The given {@code Scheduler}
* @throws Exception If any error occurs
*/
@Inject
public void schedule( Scheduler scheduler )
throws Exception
{
if ( cronExpression == null && trigger == null )
{
throw new ProvisionException( format( "Impossible to schedule Job '%s' without cron expression",
jobClass.getName() ) );
}
if ( cronExpression != null && trigger != null )
{
throw new ProvisionException( format( "Impossible to schedule Job '%s' with cron expression " +
"and an associated Trigger at the same time", jobClass.getName() ) );
}
scheduler.scheduleJob( newJob( jobClass )
.withIdentity( DEFAULT.equals( jobName ) ? jobClass.getName() : jobName, jobGroup )
.requestRecovery( requestRecovery )
.storeDurably( storeDurably ).build(),
( trigger == null ) ?
newTrigger()
.withIdentity( DEFAULT.equals( triggerName ) ? jobClass.getCanonicalName() : triggerName,
triggerGroup )
.withSchedule( cronSchedule( cronExpression )
.inTimeZone( timeZone ) )
.withPriority( priority )
.build()
: trigger);
}
}
|
src/main/java/org/nnsoft/guice/guartz/JobSchedulerBuilder.java
|
package org.nnsoft.guice.guartz;
/*
* Copyright 2009-2012 The 99 Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import static java.lang.String.format;
import static java.util.TimeZone.getDefault;
import static org.nnsoft.guice.guartz.Scheduled.DEFAULT;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import static org.quartz.utils.Key.DEFAULT_GROUP;
import java.util.TimeZone;
import javax.inject.Inject;
import org.quartz.Job;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import com.google.inject.ProvisionException;
/**
* DSL to produce {@code Job} and add to a {@code Scheduler},
* and associate the related {@code Trigger} with it.
*/
public final class JobSchedulerBuilder {
/**
* The type of the {@code Job} to be executed.
*/
private final Class<? extends Job> jobClass;
/**
* The {@code Job} name, must be unique within the group.
*/
private String jobName = DEFAULT;
/**
* The {@code Job} group name.
*/
private String jobGroup = DEFAULT_GROUP;
/**
* Instructs the {@code Scheduler} whether or not the {@code Job} should
* be re-executed if a {@code recovery} or {@code fail-over} situation is
* encountered.
*/
private boolean requestRecovery = false;
/**
* Whether or not the {@code Job} should remain stored after it is
* orphaned (no {@code Trigger}s point to it).
*/
private boolean storeDurably = false;
/**
* The {@code Trigger} name, must be unique within the group.
*/
private String triggerName = DEFAULT;
/**
* The {@code Trigger} group.
*/
private String triggerGroup = DEFAULT_GROUP;
/**
* The cron expression to base the schedule on.
*/
private String cronExpression;
/**
* The time zone for which the {@code cronExpression}
* of this {@code CronTrigger} will be resolved.
*/
private TimeZone timeZone = getDefault();
/**
* The {@code Trigger}'s priority. When more than one {@code Trigger} have the same
* fire time, the scheduler will fire the one with the highest priority
* first.
*/
private int priority = 0;
/**
* The {@code Trigger} to be used to schedule the {@code Job}
*/
private Trigger trigger;
/**
* Creates a new {@code JobSchedulerBuilder} instance.
*
* This class can't be instantiated by users.
*
* @param jobClass The type of the {@code Job} to be executed
*/
JobSchedulerBuilder( final Class<? extends Job> jobClass )
{
this.jobClass = jobClass;
}
/**
* Sets the {@code Job} name, must be unique within the group.
*
* @param jobName The {@code Job} name, must be unique within the group
* @return This builder instance
*/
public JobSchedulerBuilder withJobName( String jobName )
{
this.jobName = jobName;
return this;
}
/**
* Sets the {@code Job} group.
*
* @param jobGroup The {@code Job} group
* @return This builder instance
*/
public JobSchedulerBuilder withJobGroup( String jobGroup )
{
this.jobGroup = jobGroup;
return this;
}
/**
* Instructs the {@code Scheduler} whether or not the {@code Job} should
* be re-executed if a {@code recovery} or {@code fail-over} situation is
* encountered.
*
* @param requestRecovery The activation flag
* @return This builder instance
*/
public JobSchedulerBuilder withRequestRecovery( boolean requestRecovery )
{
this.requestRecovery = requestRecovery;
return this;
}
/**
* Whether or not the {@code Job} should remain stored after it is
* orphaned (no {@code Trigger}s point to it).
*
* @param storeDurably The activation flag
* @return This builder instance
*/
public JobSchedulerBuilder withStoreDurably( boolean storeDurably )
{
this.storeDurably = storeDurably;
return this;
}
/**
* Sets the {@code Trigger} name, must be unique within the group.
*
* @param triggerName The {@code Trigger} name, must be unique within the group
* @return This builder instance
*/
public JobSchedulerBuilder withTriggerName( String triggerName )
{
this.triggerName = triggerName;
return this;
}
/**
* Sets the {@code Trigger} group.
*
* @param triggerGroup The {@code Trigger} group
* @return This builder instance
*/
public JobSchedulerBuilder withTriggerGroup( String triggerGroup )
{
this.triggerGroup = triggerGroup;
return this;
}
/**
* Sets the cron expression to base the schedule on.
*
* @param cronExpression The cron expression to base the schedule on
* @return This builder instance
*/
public JobSchedulerBuilder withCronExpression( String cronExpression )
{
this.cronExpression = cronExpression;
return this;
}
/**
* Sets the time zone for which the {@code cronExpression} of this
* {@code CronTrigger} will be resolved.
*
* @param timeZone The time zone for which the {@code cronExpression}
* of this {@code CronTrigger} will be resolved.
* @return This builder instance
*/
public JobSchedulerBuilder withTimeZone( TimeZone timeZone )
{
this.timeZone = timeZone;
return this;
}
/**
* Sets the {@code Trigger}'s priority. When more than one {@code Trigger} have the same
* fire time, the scheduler will fire the one with the highest priority
* first.
*
* @param priority The {@code Trigger}'s priority
* @return This builder instance
*/
public JobSchedulerBuilder withPriority( int priority )
{
this.priority = priority;
return this;
}
/**
* Sets the {@code Trigger} that will be used to schedule
* the {@code Job}.
*
* <p>
* Be aware that using using this method will override any other
* {@code Trigger}-related operation, like {@link #withTriggerGroup(String)}
* or {@link #withTimeZone(TimeZone)}
*
* @param trigger The {@code Trigger} to associate with the {@code Job}
* @return This builder instance
*/
public JobSchedulerBuilder withTrigger(Trigger trigger)
{
this.trigger = trigger;
return this;
}
/**
* Add the produced {@code Job} to the given {@code Scheduler},
* and associate the related {@code Trigger} with it.
*
* Users <b>MUST NOT</b> use this method!
*
* @param scheduler The given {@code Scheduler}
* @throws Exception If any error occurs
*/
@Inject
public void schedule( Scheduler scheduler )
throws Exception
{
if ( cronExpression == null && trigger == null )
{
throw new ProvisionException( format( "Impossible to schedule Job '%s' without cron expression",
jobClass.getName() ) );
}
if ( cronExpression != null && trigger != null )
{
throw new ProvisionException( format( "Impossible to schedule Job '%s' with cron expression " +
"and an associated Trigger at the same time", jobClass.getName() ) );
}
scheduler.scheduleJob( newJob( jobClass )
.withIdentity( DEFAULT.equals( jobName ) ? jobClass.getName() : jobName, jobGroup )
.requestRecovery( requestRecovery )
.storeDurably( storeDurably ).build(),
( trigger == null ) ?
newTrigger()
.withIdentity( DEFAULT.equals( triggerName ) ? jobClass.getCanonicalName() : triggerName,
triggerGroup )
.withSchedule( cronSchedule( cronExpression )
.inTimeZone( timeZone ) )
.withPriority( priority )
.build()
: trigger);
}
}
|
added @since tags
|
src/main/java/org/nnsoft/guice/guartz/JobSchedulerBuilder.java
|
added @since tags
|
|
Java
|
apache-2.0
|
58e2642a194733ed0d13fff092f3f577bbf1805f
| 0
|
apache/tapestry3,apache/tapestry3,apache/tapestry3,apache/tapestry3
|
// Copyright 2004 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry.html;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.tapestry.AbstractComponent;
import org.apache.tapestry.ApplicationRuntimeException;
import org.apache.tapestry.IMarkupWriter;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.IResourceLocation;
import org.apache.tapestry.IScriptProcessor;
import org.apache.tapestry.Tapestry;
import org.apache.tapestry.asset.PrivateAsset;
import org.apache.tapestry.resource.ClasspathResourceLocation;
import org.apache.tapestry.util.IdAllocator;
/**
* The body of a Tapestry page. This is used since it allows components on the
* page access to an initialization script (that is written the start, just inside
* the <body> tag). This is currently used by {@link Rollover} and {@link Script}
* components.
*
* [<a href="../../../../../ComponentReference/Body.html">Component Reference</a>]
*
* @author Howard Lewis Ship
* @version $Id$
*
**/
public abstract class Body extends AbstractComponent implements IScriptProcessor
{
// Lines that belong inside the onLoad event handler for the <body> tag.
private StringBuffer _initializationScript;
// The writer initially passed to render() ... wrapped elements render
// into a nested response writer.
private IMarkupWriter _outerWriter;
// Any other scripting desired
private StringBuffer _bodyScript;
// Contains text lines related to image initializations
private StringBuffer _imageInitializations;
/**
* Map of URLs to Strings (preloaded image references).
*
**/
private Map _imageMap;
/**
* List of included scripts. Values are Strings.
*
* @since 1.0.5
*
**/
private List _externalScripts;
private IdAllocator _idAllocator;
private static final String ATTRIBUTE_NAME = "org.apache.tapestry.active.Body";
/**
* Tracks a particular preloaded image.
*
**/
/**
* Adds to the script an initialization for the named variable as
* an Image(), to the given URL.
*
* <p>Returns a reference, a string that can be used to represent
* the preloaded image in a JavaScript function.
*
* @since 1.0.2
**/
public String getPreloadedImageReference(String URL)
{
if (_imageMap == null)
_imageMap = new HashMap();
String reference = (String) _imageMap.get(URL);
if (reference == null)
{
int count = _imageMap.size();
String varName = "tapestry_preload[" + count + "]";
reference = varName + ".src";
if (_imageInitializations == null)
_imageInitializations = new StringBuffer();
_imageInitializations.append(" ");
_imageInitializations.append(varName);
_imageInitializations.append(" = new Image();\n");
_imageInitializations.append(" ");
_imageInitializations.append(reference);
_imageInitializations.append(" = \"");
_imageInitializations.append(URL);
_imageInitializations.append("\";\n");
_imageMap.put(URL, reference);
}
return reference;
}
/**
* Adds other initialization, in the form of additional JavaScript
* code to execute from the <body>'s <code>onLoad</code> event
* handler. The caller is responsible for adding a semicolon (statement
* terminator). This method will add a newline after the script.
*
**/
public void addInitializationScript(String script)
{
if (_initializationScript == null)
_initializationScript = new StringBuffer(script.length() + 1);
_initializationScript.append(script);
_initializationScript.append('\n');
}
/**
* Adds additional scripting code to the page. This code
* will be added to a large block of scripting code at the
* top of the page (i.e., the before the <body> tag).
*
* <p>This is typically used to add some form of JavaScript
* event handler to a page. For example, the
* {@link Rollover} component makes use of this.
*
* <p>Another way this is invoked is by using the
* {@link Script} component.
*
* <p>The string will be added, as-is, within
* the <script> block generated by this <code>Body</code> component.
* The script should <em>not</em> contain HTML comments, those will
* be supplied by this Body component.
*
* <p>A frequent use is to add an initialization function using
* this method, then cause it to be executed using
* {@link #addInitializationScript(String)}.
*
**/
public void addBodyScript(String script)
{
if (_bodyScript == null)
_bodyScript = new StringBuffer(script.length());
_bodyScript.append(script);
}
/**
* Used to include a script from an outside URL (the scriptLocation
* is a URL, probably obtained from an asset. This adds
* an <script src="..."> tag before the main
* <script> tag. The Body component ensures
* that each URL is included only once.
*
* @since 1.0.5
*
**/
public void addExternalScript(IResourceLocation scriptLocation)
{
if (_externalScripts == null)
_externalScripts = new ArrayList();
if (_externalScripts.contains(scriptLocation))
return;
// Alas, this won't give a good ILocation for the actual problem.
if (!(scriptLocation instanceof ClasspathResourceLocation))
throw new ApplicationRuntimeException(
Tapestry.format("Body.include-classpath-script-only", scriptLocation),
this,
null,
null);
// Record the URL so we don't include it twice.
_externalScripts.add(scriptLocation);
}
/**
* Writes <script> elements for all the external scripts.
*/
private void writeExternalScripts(IMarkupWriter writer)
{
int count = Tapestry.size(_externalScripts);
for (int i = 0; i < count; i++)
{
ClasspathResourceLocation scriptLocation =
(ClasspathResourceLocation) _externalScripts.get(i);
// This is still very awkward! Should move the code inside PrivateAsset somewhere
// else, so that an asset does not have to be created to to build the URL.
PrivateAsset asset = new PrivateAsset(scriptLocation, null);
String url = asset.buildURL(getPage().getRequestCycle());
// Note: important to use begin(), not beginEmpty(), because browser don't
// interpret <script .../> properly.
writer.begin("script");
writer.attribute("language", "JavaScript");
writer.attribute("type", "text/javascript");
writer.attribute("src", url);
writer.end();
writer.println();
}
}
/**
* Retrieves the <code>Body</code> that was stored into the
* request cycle. This allows components wrapped by the
* <code>Body</code> to locate it and access the services it
* provides.
*
**/
public static Body get(IRequestCycle cycle)
{
return (Body) cycle.getAttribute(ATTRIBUTE_NAME);
}
protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle)
{
if (cycle.getAttribute(ATTRIBUTE_NAME) != null)
throw new ApplicationRuntimeException(
Tapestry.getMessage("Body.may-not-nest"),
this,
null,
null);
cycle.setAttribute(ATTRIBUTE_NAME, this);
_outerWriter = writer;
IMarkupWriter nested = writer.getNestedWriter();
renderBody(nested, cycle);
// Start the body tag.
writer.println();
writer.begin(getElement());
renderInformalParameters(writer, cycle);
writer.println();
// Write the page's scripting. This is included scripts
// and dynamic JavaScript, including initialization.
writeScript(_outerWriter);
// Close the nested writer, which dumps its buffered content
// into its parent.
nested.close();
writer.end(); // <body>
}
protected void cleanupAfterRender(IRequestCycle cycle)
{
super.cleanupAfterRender(cycle);
if (_idAllocator != null)
_idAllocator.clear();
if (_imageMap != null)
_imageMap.clear();
if (_externalScripts != null)
_externalScripts.clear();
if (_initializationScript != null)
_initializationScript.setLength(0);
if (_imageInitializations != null)
_imageInitializations.setLength(0);
if (_bodyScript != null)
_bodyScript.setLength(0);
_outerWriter = null;
}
/**
* Writes a single large JavaScript block containing:
* <ul>
* <li>Any image initializations
* <li>Any scripting
* <li>Any initializations
* </ul>
*
* <p>The script is written into a nested markup writer.
*
* <p>If there are any other initializations
* (see {@link #addInitializationScript(String)}),
* then a function to execute them is created.
**/
protected void writeScript(IMarkupWriter writer)
{
if (!Tapestry.isEmpty(_externalScripts))
writeExternalScripts(writer);
if (!(any(_initializationScript) || any(_bodyScript) || any(_imageInitializations)))
return;
writer.begin("script");
writer.attribute("language", "JavaScript");
writer.printRaw("<!--");
if (any(_imageInitializations))
{
writer.printRaw("\n\nvar tapestry_preload = new Array();\n");
writer.printRaw("if (document.images)\n");
writer.printRaw("{\n");
writer.printRaw(_imageInitializations.toString());
writer.printRaw("}\n");
}
if (any(_bodyScript))
{
writer.printRaw("\n\n");
writer.printRaw(_bodyScript.toString());
}
if (any(_initializationScript))
{
writer.printRaw("\n\n" + "window.onload = function ()\n" + "{\n");
writer.printRaw(_initializationScript.toString());
writer.printRaw("}");
}
writer.printRaw("\n\n// -->");
writer.end();
}
private boolean any(StringBuffer buffer)
{
if (buffer == null)
return false;
return buffer.length() > 0;
}
public abstract String getElement();
public abstract void setElement(String element);
/**
* Sets the element parameter property to its default, "body".
*
* @since 3.0
*/
protected void finishLoad()
{
setElement("body");
}
/** @since 3.0 */
public String getUniqueString(String baseValue)
{
if (_idAllocator == null)
_idAllocator = new IdAllocator();
return _idAllocator.allocateId(baseValue);
}
}
|
framework/src/org/apache/tapestry/html/Body.java
|
// Copyright 2004 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry.html;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.tapestry.AbstractComponent;
import org.apache.tapestry.ApplicationRuntimeException;
import org.apache.tapestry.IMarkupWriter;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.IResourceLocation;
import org.apache.tapestry.IScriptProcessor;
import org.apache.tapestry.Tapestry;
import org.apache.tapestry.asset.PrivateAsset;
import org.apache.tapestry.resource.ClasspathResourceLocation;
import org.apache.tapestry.util.IdAllocator;
/**
* The body of a Tapestry page. This is used since it allows components on the
* page access to an initialization script (that is written the start, just inside
* the <body> tag). This is currently used by {@link Rollover} and {@link Script}
* components.
*
* [<a href="../../../../../ComponentReference/Body.html">Component Reference</a>]
*
* @author Howard Lewis Ship
* @version $Id$
*
**/
public abstract class Body extends AbstractComponent implements IScriptProcessor
{
// Lines that belong inside the onLoad event handler for the <body> tag.
private StringBuffer _initializationScript;
// The writer initially passed to render() ... wrapped elements render
// into a nested response writer.
private IMarkupWriter _outerWriter;
// Any other scripting desired
private StringBuffer _bodyScript;
// Contains text lines related to image initializations
private StringBuffer _imageInitializations;
/**
* Map of URLs to Strings (preloaded image references).
*
**/
private Map _imageMap;
/**
* List of included scripts. Values are Strings.
*
* @since 1.0.5
*
**/
private List _externalScripts;
private IdAllocator _idAllocator;
private static final String ATTRIBUTE_NAME = "org.apache.tapestry.active.Body";
/**
* Tracks a particular preloaded image.
*
**/
/**
* Adds to the script an initialization for the named variable as
* an Image(), to the given URL.
*
* <p>Returns a reference, a string that can be used to represent
* the preloaded image in a JavaScript function.
*
* @since 1.0.2
**/
public String getPreloadedImageReference(String URL)
{
if (_imageMap == null)
_imageMap = new HashMap();
String reference = (String) _imageMap.get(URL);
if (reference == null)
{
int count = _imageMap.size();
String varName = "tapestry_preload[" + count + "]";
reference = varName + ".src";
if (_imageInitializations == null)
_imageInitializations = new StringBuffer();
_imageInitializations.append(" ");
_imageInitializations.append(varName);
_imageInitializations.append(" = new Image();\n");
_imageInitializations.append(" ");
_imageInitializations.append(reference);
_imageInitializations.append(" = \"");
_imageInitializations.append(URL);
_imageInitializations.append("\";\n");
_imageMap.put(URL, reference);
}
return reference;
}
/**
* Adds other initialization, in the form of additional JavaScript
* code to execute from the <body>'s <code>onLoad</code> event
* handler. The caller is responsible for adding a semicolon (statement
* terminator). This method will add a newline after the script.
*
**/
public void addInitializationScript(String script)
{
if (_initializationScript == null)
_initializationScript = new StringBuffer(script.length() + 1);
_initializationScript.append(script);
_initializationScript.append('\n');
}
/**
* Adds additional scripting code to the page. This code
* will be added to a large block of scripting code at the
* top of the page (i.e., the before the <body> tag).
*
* <p>This is typically used to add some form of JavaScript
* event handler to a page. For example, the
* {@link Rollover} component makes use of this.
*
* <p>Another way this is invoked is by using the
* {@link Script} component.
*
* <p>The string will be added, as-is, within
* the <script> block generated by this <code>Body</code> component.
* The script should <em>not</em> contain HTML comments, those will
* be supplied by this Body component.
*
* <p>A frequent use is to add an initialization function using
* this method, then cause it to be executed using
* {@link #addInitializationScript(String)}.
*
**/
public void addBodyScript(String script)
{
if (_bodyScript == null)
_bodyScript = new StringBuffer(script.length());
_bodyScript.append(script);
}
/**
* Used to include a script from an outside URL (the scriptLocation
* is a URL, probably obtained from an asset. This adds
* an <script src="..."> tag before the main
* <script> tag. The Body component ensures
* that each URL is included only once.
*
* @since 1.0.5
*
**/
public void addExternalScript(IResourceLocation scriptLocation)
{
if (_externalScripts == null)
_externalScripts = new ArrayList();
if (_externalScripts.contains(scriptLocation))
return;
// Alas, this won't give a good ILocation for the actual problem.
if (!(scriptLocation instanceof ClasspathResourceLocation))
throw new ApplicationRuntimeException(
Tapestry.format("Body.include-classpath-script-only", scriptLocation),
this,
null,
null);
// Record the URL so we don't include it twice.
_externalScripts.add(scriptLocation);
}
/**
* Writes <script> elements for all the external scripts.
*/
private void writeExternalScripts(IMarkupWriter writer)
{
int count = Tapestry.size(_externalScripts);
for (int i = 0; i < count; i++)
{
ClasspathResourceLocation scriptLocation =
(ClasspathResourceLocation) _externalScripts.get(i);
// This is still very awkward! Should move the code inside PrivateAsset somewhere
// else, so that an asset does not have to be created to to build the URL.
PrivateAsset asset = new PrivateAsset(scriptLocation, null);
String url = asset.buildURL(getPage().getRequestCycle());
// Note: important to use begin(), not beginEmpty(), because browser don't
// interpret <script .../> properly.
writer.begin("script");
writer.attribute("language", "JavaScript");
writer.attribute("type", "text/javascript");
writer.attribute("src", url);
writer.end();
writer.println();
}
}
/**
* Retrieves the <code>Body</code> that was stored into the
* request cycle. This allows components wrapped by the
* <code>Body</code> to locate it and access the services it
* provides.
*
**/
public static Body get(IRequestCycle cycle)
{
return (Body) cycle.getAttribute(ATTRIBUTE_NAME);
}
protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle)
{
if (cycle.getAttribute(ATTRIBUTE_NAME) != null)
throw new ApplicationRuntimeException(
Tapestry.getMessage("Body.may-not-nest"),
this,
null,
null);
cycle.setAttribute(ATTRIBUTE_NAME, this);
_outerWriter = writer;
IMarkupWriter nested = writer.getNestedWriter();
renderBody(nested, cycle);
// Start the body tag.
writer.println();
writer.begin(getElement());
renderInformalParameters(writer, cycle);
writer.println();
// Write the page's scripting. This is included scripts
// and dynamic JavaScript, including initialization.
writeScript(_outerWriter);
// Close the nested writer, which dumps its buffered content
// into its parent.
nested.close();
writer.end(); // <body>
}
protected void cleanupAfterRender(IRequestCycle cycle)
{
super.cleanupAfterRender(cycle);
if (_idAllocator != null)
_idAllocator.clear();
if (_imageMap != null)
_imageMap.clear();
if (_externalScripts != null)
_externalScripts.clear();
if (_initializationScript != null)
_initializationScript.setLength(0);
if (_imageInitializations != null)
_imageInitializations.setLength(0);
if (_bodyScript != null)
_bodyScript.setLength(0);
_outerWriter = null;
}
/**
* Writes a single large JavaScript block containing:
* <ul>
* <li>Any image initializations
* <li>Any scripting
* <li>Any initializations
* </ul>
*
* <p>The script is written into a nested markup writer.
*
* <p>If there are any other initializations
* (see {@link #addInitializationScript(String)}),
* then a function to execute them is created.
**/
private void writeScript(IMarkupWriter writer)
{
if (!Tapestry.isEmpty(_externalScripts))
writeExternalScripts(writer);
if (!(any(_initializationScript) || any(_bodyScript) || any(_imageInitializations)))
return;
writer.begin("script");
writer.attribute("language", "JavaScript");
writer.printRaw("<!--");
if (any(_imageInitializations))
{
writer.printRaw("\n\nvar tapestry_preload = new Array();\n");
writer.printRaw("if (document.images)\n");
writer.printRaw("{\n");
writer.printRaw(_imageInitializations.toString());
writer.printRaw("}\n");
}
if (any(_bodyScript))
{
writer.printRaw("\n\n");
writer.printRaw(_bodyScript.toString());
}
if (any(_initializationScript))
{
writer.printRaw("\n\n" + "window.onload = function ()\n" + "{\n");
writer.printRaw(_initializationScript.toString());
writer.printRaw("}");
}
writer.printRaw("\n\n// -->");
writer.end();
}
private boolean any(StringBuffer buffer)
{
if (buffer == null)
return false;
return buffer.length() > 0;
}
public abstract String getElement();
public abstract void setElement(String element);
/**
* Sets the element parameter property to its default, "body".
*
* @since 3.0
*/
protected void finishLoad()
{
setElement("body");
}
/** @since 3.0 */
public String getUniqueString(String baseValue)
{
if (_idAllocator == null)
_idAllocator = new IdAllocator();
return _idAllocator.allocateId(baseValue);
}
}
|
Make the writeScript() method of Body protected, so that a subclass can invoke it.
git-svn-id: 6d735c88f1bbfceeda8c3bfb53092482a4818e48@243979 13f79535-47bb-0310-9956-ffa450edef68
|
framework/src/org/apache/tapestry/html/Body.java
|
Make the writeScript() method of Body protected, so that a subclass can invoke it.
|
|
Java
|
apache-2.0
|
300275916bcd9330cccf219ee23eda35e05f8f94
| 0
|
dsyang/buck,sdwilsh/buck,k21/buck,vschs007/buck,sdwilsh/buck,JoelMarcey/buck,davido/buck,dsyang/buck,darkforestzero/buck,SeleniumHQ/buck,k21/buck,brettwooldridge/buck,grumpyjames/buck,rmaz/buck,clonetwin26/buck,SeleniumHQ/buck,Addepar/buck,shs96c/buck,ilya-klyuchnikov/buck,SeleniumHQ/buck,facebook/buck,Addepar/buck,ilya-klyuchnikov/buck,brettwooldridge/buck,davido/buck,romanoid/buck,davido/buck,grumpyjames/buck,marcinkwiatkowski/buck,nguyentruongtho/buck,LegNeato/buck,sdwilsh/buck,rmaz/buck,kageiit/buck,k21/buck,grumpyjames/buck,zhan-xiong/buck,clonetwin26/buck,LegNeato/buck,SeleniumHQ/buck,clonetwin26/buck,davido/buck,zhan-xiong/buck,zhan-xiong/buck,daedric/buck,shs96c/buck,SeleniumHQ/buck,brettwooldridge/buck,sdwilsh/buck,k21/buck,zpao/buck,nguyentruongtho/buck,grumpyjames/buck,romanoid/buck,clonetwin26/buck,brettwooldridge/buck,JoelMarcey/buck,LegNeato/buck,shs96c/buck,nguyentruongtho/buck,daedric/buck,shybovycha/buck,kageiit/buck,LegNeato/buck,marcinkwiatkowski/buck,sdwilsh/buck,Addepar/buck,davido/buck,daedric/buck,clonetwin26/buck,shs96c/buck,davido/buck,ilya-klyuchnikov/buck,clonetwin26/buck,Addepar/buck,dsyang/buck,romanoid/buck,daedric/buck,daedric/buck,clonetwin26/buck,rmaz/buck,ilya-klyuchnikov/buck,grumpyjames/buck,kageiit/buck,robbertvanginkel/buck,darkforestzero/buck,shs96c/buck,k21/buck,robbertvanginkel/buck,k21/buck,romanoid/buck,SeleniumHQ/buck,JoelMarcey/buck,dsyang/buck,brettwooldridge/buck,brettwooldridge/buck,vschs007/buck,daedric/buck,clonetwin26/buck,Addepar/buck,shybovycha/buck,ilya-klyuchnikov/buck,daedric/buck,zpao/buck,clonetwin26/buck,marcinkwiatkowski/buck,rmaz/buck,shs96c/buck,marcinkwiatkowski/buck,JoelMarcey/buck,zpao/buck,marcinkwiatkowski/buck,robbertvanginkel/buck,dsyang/buck,marcinkwiatkowski/buck,romanoid/buck,vschs007/buck,JoelMarcey/buck,Addepar/buck,grumpyjames/buck,k21/buck,darkforestzero/buck,JoelMarcey/buck,ilya-klyuchnikov/buck,romanoid/buck,zhan-xiong/buck,SeleniumHQ/buck,zhan-xiong/buck,rmaz/buck,shs96c/buck,darkforestzero/buck,dsyang/buck,davido/buck,darkforestzero/buck,clonetwin26/buck,shybovycha/buck,facebook/buck,dsyang/buck,robbertvanginkel/buck,marcinkwiatkowski/buck,ilya-klyuchnikov/buck,marcinkwiatkowski/buck,rmaz/buck,LegNeato/buck,facebook/buck,rmaz/buck,sdwilsh/buck,vschs007/buck,zhan-xiong/buck,romanoid/buck,vschs007/buck,daedric/buck,robbertvanginkel/buck,kageiit/buck,darkforestzero/buck,shs96c/buck,grumpyjames/buck,ilya-klyuchnikov/buck,facebook/buck,brettwooldridge/buck,clonetwin26/buck,davido/buck,shybovycha/buck,zhan-xiong/buck,zpao/buck,shs96c/buck,LegNeato/buck,dsyang/buck,daedric/buck,brettwooldridge/buck,nguyentruongtho/buck,nguyentruongtho/buck,darkforestzero/buck,ilya-klyuchnikov/buck,davido/buck,clonetwin26/buck,shs96c/buck,marcinkwiatkowski/buck,marcinkwiatkowski/buck,k21/buck,brettwooldridge/buck,rmaz/buck,LegNeato/buck,romanoid/buck,zhan-xiong/buck,vschs007/buck,ilya-klyuchnikov/buck,k21/buck,grumpyjames/buck,shs96c/buck,dsyang/buck,LegNeato/buck,facebook/buck,Addepar/buck,Addepar/buck,romanoid/buck,shybovycha/buck,JoelMarcey/buck,kageiit/buck,LegNeato/buck,shybovycha/buck,SeleniumHQ/buck,vschs007/buck,sdwilsh/buck,shybovycha/buck,JoelMarcey/buck,kageiit/buck,vschs007/buck,romanoid/buck,darkforestzero/buck,JoelMarcey/buck,vschs007/buck,davido/buck,marcinkwiatkowski/buck,brettwooldridge/buck,JoelMarcey/buck,brettwooldridge/buck,vschs007/buck,sdwilsh/buck,k21/buck,grumpyjames/buck,daedric/buck,LegNeato/buck,shybovycha/buck,LegNeato/buck,rmaz/buck,brettwooldridge/buck,ilya-klyuchnikov/buck,rmaz/buck,LegNeato/buck,vschs007/buck,robbertvanginkel/buck,shs96c/buck,dsyang/buck,davido/buck,dsyang/buck,sdwilsh/buck,grumpyjames/buck,romanoid/buck,darkforestzero/buck,nguyentruongtho/buck,SeleniumHQ/buck,SeleniumHQ/buck,zhan-xiong/buck,romanoid/buck,zhan-xiong/buck,darkforestzero/buck,brettwooldridge/buck,zpao/buck,zpao/buck,shybovycha/buck,zhan-xiong/buck,robbertvanginkel/buck,daedric/buck,ilya-klyuchnikov/buck,facebook/buck,robbertvanginkel/buck,Addepar/buck,robbertvanginkel/buck,robbertvanginkel/buck,Addepar/buck,robbertvanginkel/buck,clonetwin26/buck,kageiit/buck,dsyang/buck,Addepar/buck,robbertvanginkel/buck,zhan-xiong/buck,shybovycha/buck,Addepar/buck,ilya-klyuchnikov/buck,romanoid/buck,zhan-xiong/buck,shybovycha/buck,vschs007/buck,shybovycha/buck,JoelMarcey/buck,shs96c/buck,marcinkwiatkowski/buck,davido/buck,dsyang/buck,daedric/buck,JoelMarcey/buck,rmaz/buck,grumpyjames/buck,rmaz/buck,rmaz/buck,davido/buck,Addepar/buck,SeleniumHQ/buck,sdwilsh/buck,darkforestzero/buck,sdwilsh/buck,nguyentruongtho/buck,zpao/buck,marcinkwiatkowski/buck,darkforestzero/buck,LegNeato/buck,vschs007/buck,darkforestzero/buck,SeleniumHQ/buck,k21/buck,shybovycha/buck,grumpyjames/buck,sdwilsh/buck,facebook/buck,k21/buck,sdwilsh/buck,JoelMarcey/buck,SeleniumHQ/buck,daedric/buck,k21/buck,robbertvanginkel/buck
|
/*
* 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.python;
import static com.facebook.buck.rules.BuildableProperties.Kind.PACKAGING;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.rules.AddToRuleKey;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
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.HasRuntimeDeps;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.rules.args.SourcePathArg;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.buck.step.fs.MkdirStep;
import com.facebook.buck.step.fs.RmStep;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import java.nio.file.Path;
public class PythonPackagedBinary extends PythonBinary implements HasRuntimeDeps {
private static final BuildableProperties OUTPUT_TYPE = new BuildableProperties(PACKAGING);
@AddToRuleKey
private final Tool builder;
@AddToRuleKey
private final ImmutableList<String> buildArgs;
private final Tool pathToPexExecuter;
@AddToRuleKey
private final String mainModule;
@AddToRuleKey
private final PythonPackageComponents components;
@AddToRuleKey
private final PythonEnvironment pythonEnvironment;
@AddToRuleKey
private final ImmutableSet<String> preloadLibraries;
private final boolean cache;
protected PythonPackagedBinary(
BuildRuleParams params,
SourcePathResolver resolver,
PythonPlatform pythonPlatform,
Tool builder,
ImmutableList<String> buildArgs,
Tool pathToPexExecuter,
String pexExtension,
PythonEnvironment pythonEnvironment,
String mainModule,
PythonPackageComponents components,
ImmutableSet<String> preloadLibraries,
boolean cache,
boolean legacyOutputPath) {
super(
params,
resolver,
pythonPlatform,
mainModule,
components,
preloadLibraries,
pexExtension,
legacyOutputPath);
this.builder = builder;
this.buildArgs = buildArgs;
this.pathToPexExecuter = pathToPexExecuter;
this.pythonEnvironment = pythonEnvironment;
this.mainModule = mainModule;
this.components = components;
this.preloadLibraries = preloadLibraries;
this.cache = cache;
}
@Override
public BuildableProperties getProperties() {
return OUTPUT_TYPE;
}
@Override
public Tool getExecutableCommand() {
return new CommandTool.Builder(pathToPexExecuter)
.addArg(
new SourcePathArg(
getResolver(),
new BuildTargetSourcePath(getBuildTarget(), getBinPath())))
.build();
}
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context,
BuildableContext buildableContext) {
ImmutableList.Builder<Step> steps = ImmutableList.builder();
Path binPath = getBinPath();
// Make sure the parent directory exists.
steps.add(new MkdirStep(getProjectFilesystem(), binPath.getParent()));
// Delete any other pex that was there (when switching between pex styles).
steps.add(new RmStep(getProjectFilesystem(), binPath, /* force */ true, /* recurse */ true));
Path workingDirectory = BuildTargets.getGenPath(
getProjectFilesystem(),
getBuildTarget(),
"__%s__working_directory");
steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), workingDirectory));
// Generate and return the PEX build step.
steps.add(
new PexStep(
getProjectFilesystem(),
builder.getEnvironment(),
ImmutableList.<String>builder()
.addAll(builder.getCommandPrefix(getResolver()))
.addAll(buildArgs)
.build(),
pythonEnvironment.getPythonPath(),
pythonEnvironment.getPythonVersion(),
workingDirectory,
binPath,
mainModule,
getResolver().getMappedPaths(components.getModules()),
getResolver().getMappedPaths(components.getResources()),
getResolver().getMappedPaths(components.getNativeLibraries()),
ImmutableSet.copyOf(
getResolver().getAllAbsolutePaths(components.getPrebuiltLibraries())),
preloadLibraries,
components.isZipSafe().orElse(true)));
// Record the executable package for caching.
buildableContext.recordArtifact(getBinPath());
return steps.build();
}
@Override
public ImmutableSortedSet<BuildRule> getRuntimeDeps() {
return ImmutableSortedSet.<BuildRule>naturalOrder()
.addAll(super.getRuntimeDeps())
.addAll(pathToPexExecuter.getDeps(getResolver()))
.build();
}
@Override
public boolean isCacheable() {
return cache;
}
}
|
src/com/facebook/buck/python/PythonPackagedBinary.java
|
/*
* 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.python;
import static com.facebook.buck.rules.BuildableProperties.Kind.PACKAGING;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.rules.AddToRuleKey;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
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.HasRuntimeDeps;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.rules.args.SourcePathArg;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.buck.step.fs.MkdirStep;
import com.facebook.buck.step.fs.RmStep;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import java.nio.file.Path;
public class PythonPackagedBinary extends PythonBinary implements HasRuntimeDeps {
private static final BuildableProperties OUTPUT_TYPE = new BuildableProperties(PACKAGING);
@AddToRuleKey
private final Tool builder;
@AddToRuleKey
private final ImmutableList<String> buildArgs;
private final Tool pathToPexExecuter;
@AddToRuleKey
private final String mainModule;
@AddToRuleKey
private final PythonPackageComponents components;
@AddToRuleKey
private final PythonEnvironment pythonEnvironment;
@AddToRuleKey
private final ImmutableSet<String> preloadLibraries;
private final boolean cache;
protected PythonPackagedBinary(
BuildRuleParams params,
SourcePathResolver resolver,
PythonPlatform pythonPlatform,
Tool builder,
ImmutableList<String> buildArgs,
Tool pathToPexExecuter,
String pexExtension,
PythonEnvironment pythonEnvironment,
String mainModule,
PythonPackageComponents components,
ImmutableSet<String> preloadLibraries,
boolean cache,
boolean legacyOutputPath) {
super(
params,
resolver,
pythonPlatform,
mainModule,
components,
preloadLibraries,
pexExtension,
legacyOutputPath);
this.builder = builder;
this.buildArgs = buildArgs;
this.pathToPexExecuter = pathToPexExecuter;
this.pythonEnvironment = pythonEnvironment;
this.mainModule = mainModule;
this.components = components;
this.preloadLibraries = preloadLibraries;
this.cache = cache;
}
@Override
public BuildableProperties getProperties() {
return OUTPUT_TYPE;
}
@Override
public Tool getExecutableCommand() {
return new CommandTool.Builder(pathToPexExecuter)
.addArg(
new SourcePathArg(
getResolver(),
new BuildTargetSourcePath(getBuildTarget(), getBinPath())))
.build();
}
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context,
BuildableContext buildableContext) {
ImmutableList.Builder<Step> steps = ImmutableList.builder();
Path binPath = getBinPath();
// Make sure the parent directory exists.
steps.add(new MkdirStep(getProjectFilesystem(), binPath.getParent()));
// Delete any other pex that was there (when switching between pex styles).
steps.add(new RmStep(getProjectFilesystem(), binPath, /* force */ true, /* recurse */ true));
Path workingDirectory = BuildTargets.getGenPath(
getProjectFilesystem(),
getBuildTarget(),
"__%s__working_directory");
steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), workingDirectory));
// Generate and return the PEX build step.
steps.add(
new PexStep(
getProjectFilesystem(),
builder.getEnvironment(),
ImmutableList.<String>builder()
.addAll(builder.getCommandPrefix(getResolver()))
.addAll(buildArgs)
.build(),
pythonEnvironment.getPythonPath(),
pythonEnvironment.getPythonVersion(),
workingDirectory,
binPath,
mainModule,
getResolver().getMappedPaths(components.getModules()),
getResolver().getMappedPaths(components.getResources()),
getResolver().getMappedPaths(components.getNativeLibraries()),
ImmutableSet.copyOf(
getResolver().deprecatedAllPaths(components.getPrebuiltLibraries())),
preloadLibraries,
components.isZipSafe().orElse(true)));
// Record the executable package for caching.
buildableContext.recordArtifact(getBinPath());
return steps.build();
}
@Override
public ImmutableSortedSet<BuildRule> getRuntimeDeps() {
return ImmutableSortedSet.<BuildRule>naturalOrder()
.addAll(super.getRuntimeDeps())
.addAll(pathToPexExecuter.getDeps(getResolver()))
.build();
}
@Override
public boolean isCacheable() {
return cache;
}
}
|
Remove deprecated method call
Summary:
The other paths written to the file this writes are absolute, so these
probably should be too.
Test Plan: CI
Reviewed By: plamenko
fbshipit-source-id: 9ee3de1
|
src/com/facebook/buck/python/PythonPackagedBinary.java
|
Remove deprecated method call
|
|
Java
|
apache-2.0
|
c043e3f2934ed7b1eff49fc851016ce0c3b49cc9
| 0
|
tempbottle/commons-bcel,mohanaraosv/commons-bcel,tempbottle/commons-bcel,mohanaraosv/commons-bcel,typetools/commons-bcel,tempbottle/commons-bcel,typetools/commons-bcel,mohanaraosv/commons-bcel,apache/commons-bcel,Maccimo/commons-bcel,Maccimo/commons-bcel,apache/commons-bcel,Maccimo/commons-bcel,typetools/commons-bcel,apache/commons-bcel
|
/*
* Copyright 2000-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.bcel.util;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
/**
* This repository is used in situations where a Class is created
* outside the realm of a ClassLoader. Classes are loaded from
* the file systems using the paths specified in the given
* class path. By default, this is the value returned by
* ClassPath.getClassPath().
* <br>
* It is designed to be used as a singleton, however it
* can also be used with custom classpaths.
*
/**
* Abstract definition of a class repository. Instances may be used
* to load classes from different sources and may be used in the
* Repository.setRepository method.
*
* @see org.apache.bcel.Repository
*
* @version $Id$
* @author <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A>
* @author David Dixon-Peugh
*/
public class SyntheticRepository implements Repository {
private static final String DEFAULT_PATH = ClassPath.getClassPath();
private static HashMap _instances = new HashMap(); // CLASSPATH X REPOSITORY
private ClassPath _path = null;
private HashMap _loadedClasses = new HashMap(); // CLASSNAME X JAVACLASS
private SyntheticRepository(ClassPath path) {
_path = path;
}
public static SyntheticRepository getInstance() {
return getInstance(ClassPath.SYSTEM_CLASS_PATH);
}
public static SyntheticRepository getInstance(ClassPath classPath) {
SyntheticRepository rep = (SyntheticRepository)_instances.get(classPath);
if (rep == null) {
rep = new SyntheticRepository(classPath);
_instances.put(classPath, rep);
}
return rep;
}
/**
* Store a new JavaClass instance into this Repository.
*/
public void storeClass(JavaClass clazz) {
_loadedClasses.put(clazz.getClassName(), new SoftReference(clazz));
clazz.setRepository(this);
}
/**
* Remove class from repository
*/
public void removeClass(JavaClass clazz) {
_loadedClasses.remove(clazz.getClassName());
}
/**
* Find an already defined (cached) JavaClass object by name.
*/
public JavaClass findClass(String className) {
SoftReference ref = (SoftReference)_loadedClasses.get(className);
if (ref == null)
return null;
return (JavaClass)ref.get();
}
/**
* Find a JavaClass object by name.
* If it is already in this Repository, the Repository version
* is returned. Otherwise, the Repository's classpath is searched for
* the class (and it is added to the Repository if found).
*
* @param className the name of the class
* @return the JavaClass object
* @throws ClassNotFoundException if the class is not in the
* Repository, and could not be found on the classpath
*/
public JavaClass loadClass(String className) throws ClassNotFoundException {
if (className == null || className.equals("")) {
throw new IllegalArgumentException("Invalid class name " + className);
}
className = className.replace('/', '.'); // Just in case, canonical form
JavaClass clazz = findClass(className);
if (clazz != null) {
return clazz;
}
try {
return loadClass(_path.getInputStream(className), className);
} catch (IOException e) {
throw new ClassNotFoundException(
"Exception while looking for class " + className + ": " + e.toString());
}
}
/**
* Find the JavaClass object for a runtime Class object.
* If a class with the same name is already in this Repository,
* the Repository version is returned. Otherwise, getResourceAsStream()
* is called on the Class object to find the class's representation.
* If the representation is found, it is added to the Repository.
*
* @see Class
* @param clazz the runtime Class object
* @return JavaClass object for given runtime class
* @throws ClassNotFoundException if the class is not in the
* Repository, and its representation could not be found
*/
public JavaClass loadClass(Class clazz) throws ClassNotFoundException {
String className = clazz.getName();
JavaClass repositoryClass = findClass(className);
if (repositoryClass != null) {
return repositoryClass;
}
String name = className;
int i = name.lastIndexOf('.');
if (i > 0) {
name = name.substring(i + 1);
}
return loadClass(clazz.getResourceAsStream(name + ".class"), className);
}
private JavaClass loadClass(InputStream is, String className)
throws ClassNotFoundException {
try {
if (is != null) {
ClassParser parser = new ClassParser(is, className);
JavaClass clazz = parser.parse();
storeClass(clazz);
return clazz;
}
} catch (IOException e) {
throw new ClassNotFoundException(
"Exception while looking for class " + className + ": " + e.toString());
}
throw new ClassNotFoundException(
"SyntheticRepository could not load " + className);
}
/** ClassPath associated with the Repository.
*/
public ClassPath getClassPath() {
return _path;
}
/** Clear all entries from cache.
*/
public void clear() {
_loadedClasses.clear();
}
}
|
src/java/org/apache/bcel/util/SyntheticRepository.java
|
/*
* Copyright 2000-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.bcel.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
/**
* This repository is used in situations where a Class is created
* outside the realm of a ClassLoader. Classes are loaded from
* the file systems using the paths specified in the given
* class path. By default, this is the value returned by
* ClassPath.getClassPath().
* <br>
* It is designed to be used as a singleton, however it
* can also be used with custom classpaths.
*
/**
* Abstract definition of a class repository. Instances may be used
* to load classes from different sources and may be used in the
* Repository.setRepository method.
*
* @see org.apache.bcel.Repository
*
* @version $Id$
* @author <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A>
* @author David Dixon-Peugh
*/
public class SyntheticRepository implements Repository {
private static final String DEFAULT_PATH = ClassPath.getClassPath();
private static HashMap _instances = new HashMap(); // CLASSPATH X REPOSITORY
private ClassPath _path = null;
private HashMap _loadedClasses = new HashMap(); // CLASSNAME X JAVACLASS
private SyntheticRepository(ClassPath path) {
_path = path;
}
public static SyntheticRepository getInstance() {
return getInstance(ClassPath.SYSTEM_CLASS_PATH);
}
public static SyntheticRepository getInstance(ClassPath classPath) {
SyntheticRepository rep = (SyntheticRepository)_instances.get(classPath);
if (rep == null) {
rep = new SyntheticRepository(classPath);
_instances.put(classPath, rep);
}
return rep;
}
/**
* Store a new JavaClass instance into this Repository.
*/
public void storeClass(JavaClass clazz) {
_loadedClasses.put(clazz.getClassName(), clazz);
clazz.setRepository(this);
}
/**
* Remove class from repository
*/
public void removeClass(JavaClass clazz) {
_loadedClasses.remove(clazz.getClassName());
}
/**
* Find an already defined (cached) JavaClass object by name.
*/
public JavaClass findClass(String className) {
return (JavaClass)_loadedClasses.get(className);
}
/**
* Find a JavaClass object by name.
* If it is already in this Repository, the Repository version
* is returned. Otherwise, the Repository's classpath is searched for
* the class (and it is added to the Repository if found).
*
* @param className the name of the class
* @return the JavaClass object
* @throws ClassNotFoundException if the class is not in the
* Repository, and could not be found on the classpath
*/
public JavaClass loadClass(String className) throws ClassNotFoundException {
if (className == null || className.equals("")) {
throw new IllegalArgumentException("Invalid class name " + className);
}
className = className.replace('/', '.'); // Just in case, canonical form
JavaClass clazz = findClass(className);
if (clazz != null) {
return clazz;
}
try {
return loadClass(_path.getInputStream(className), className);
} catch (IOException e) {
throw new ClassNotFoundException(
"Exception while looking for class " + className + ": " + e.toString());
}
}
/**
* Find the JavaClass object for a runtime Class object.
* If a class with the same name is already in this Repository,
* the Repository version is returned. Otherwise, getResourceAsStream()
* is called on the Class object to find the class's representation.
* If the representation is found, it is added to the Repository.
*
* @see Class
* @param clazz the runtime Class object
* @return JavaClass object for given runtime class
* @throws ClassNotFoundException if the class is not in the
* Repository, and its representation could not be found
*/
public JavaClass loadClass(Class clazz) throws ClassNotFoundException {
String className = clazz.getName();
JavaClass repositoryClass = findClass(className);
if (repositoryClass != null) {
return repositoryClass;
}
String name = className;
int i = name.lastIndexOf('.');
if (i > 0) {
name = name.substring(i + 1);
}
return loadClass(clazz.getResourceAsStream(name + ".class"), className);
}
private JavaClass loadClass(InputStream is, String className)
throws ClassNotFoundException {
try {
if (is != null) {
ClassParser parser = new ClassParser(is, className);
JavaClass clazz = parser.parse();
storeClass(clazz);
return clazz;
}
} catch (IOException e) {
throw new ClassNotFoundException(
"Exception while looking for class " + className + ": " + e.toString());
}
throw new ClassNotFoundException(
"SyntheticRepository could not load " + className);
}
/** ClassPath associated with the Repository.
*/
public ClassPath getClassPath() {
return _path;
}
/** Clear all entries from cache.
*/
public void clear() {
_loadedClasses.clear();
}
}
|
Apply Patch 32945 Make the SyntheticRepository a memory sensitive cache.
git-svn-id: 77ab32d24b47fe90dc24bcc15ad4d4ee91dcaedf@153176 13f79535-47bb-0310-9956-ffa450edef68
|
src/java/org/apache/bcel/util/SyntheticRepository.java
|
Apply Patch 32945 Make the SyntheticRepository a memory sensitive cache.
|
|
Java
|
apache-2.0
|
a744ca0d154b14001c5cc742ee74652930951fde
| 0
|
dimagi/commcare-core,dimagi/commcare,dimagi/commcare,dimagi/commcare-core,dimagi/commcare,dimagi/commcare-core
|
package org.commcare.suite.model;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapList;
import org.javarosa.core.util.externalizable.ExtWrapMap;
import org.javarosa.core.util.externalizable.ExtWrapNullable;
import org.javarosa.core.util.externalizable.Externalizable;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.xpath.XPathParseTool;
import org.javarosa.xpath.expr.FunctionUtils;
import org.javarosa.xpath.parser.XPathSyntaxException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* Application callout described in suite.xml
* Used in callouts from EntitySelectActivity and EntityDetailActivity
*
* @author wpride1 on 4/14/15.
*/
public class Callout implements Externalizable, DetailTemplate {
private String actionName;
private String image;
private String displayName;
private String type;
private Hashtable<String, String> extras;
private Vector<String> responses;
private boolean isAutoLaunching;
private boolean assumePlainTextValues;
private static final String KEY_FORCE_XPATH_PARSING = "force_xpath_parsing";
private static final String KEY_FORCE_XPATH_PARSING_VALUE_TRUE = "yes";
/**
* Allows case list intent callouts to map result data to cases. 'header'
* is the column header text and 'template' is the key used for mapping a
* callout result data point to a case, should usually be the case id.
*/
private DetailField responseDetail;
/**
* For externalization
*/
public Callout() {
}
public Callout(String actionName, String image, String displayName,
Hashtable<String, String> extras, Vector<String> responses,
DetailField responseDetail, String type, boolean isAutoLaunching) {
this.actionName = actionName;
this.image = image;
this.displayName = displayName;
this.extras = extras;
this.responses = responses;
this.responseDetail = responseDetail;
this.type = type;
this.isAutoLaunching = isAutoLaunching;
this.assumePlainTextValues = false;
}
@Override
public CalloutData evaluate(EvaluationContext context) {
Hashtable<String, String> evaluatedExtras = new Hashtable<>();
boolean forceXpathParsing = forceXpathParsing();
Enumeration keys = extras.keys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String rawValue = extras.get(key);
if (assumePlainTextValues && !forceXpathParsing) {
evaluatedExtras.put(key, rawValue);
} else {
try {
String evaluatedValue =
FunctionUtils.toString(XPathParseTool.parseXPath(rawValue).eval(context));
evaluatedExtras.put(key, evaluatedValue);
} catch (XPathSyntaxException e) {
// do nothing
}
}
}
// emit a CalloutData with the extras evaluated. used for the detail screen.
return new CalloutData(actionName, image, displayName, evaluatedExtras, responses, type);
}
// Returns true if force_xpath_parsing is yes
private boolean forceXpathParsing() {
Enumeration keys = extras.keys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
if (key.contentEquals(KEY_FORCE_XPATH_PARSING)) {
String forceXpathVal = extras.get(key);
extras.remove(key);
return forceXpathVal.contentEquals(KEY_FORCE_XPATH_PARSING_VALUE_TRUE);
}
}
return false;
}
@Override
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
displayName = ExtUtil.readString(in);
actionName = (String)ExtUtil.read(in, new ExtWrapNullable(String.class), pf);
image = (String)ExtUtil.read(in, new ExtWrapNullable(String.class), pf);
extras = (Hashtable<String, String>)ExtUtil.read(in, new ExtWrapMap(String.class, String.class), pf);
responses = (Vector<String>)ExtUtil.read(in, new ExtWrapList(String.class), pf);
responseDetail = (DetailField)ExtUtil.read(in, new ExtWrapNullable(DetailField.class), pf);
type = (String)ExtUtil.read(in, new ExtWrapNullable(String.class), pf);
isAutoLaunching = ExtUtil.readBool(in);
}
@Override
public void writeExternal(DataOutputStream out) throws IOException {
ExtUtil.writeString(out, displayName);
ExtUtil.write(out, new ExtWrapNullable(actionName));
ExtUtil.write(out, new ExtWrapNullable(image));
ExtUtil.write(out, new ExtWrapMap(extras));
ExtUtil.write(out, new ExtWrapList(responses));
ExtUtil.write(out, new ExtWrapNullable(responseDetail));
ExtUtil.write(out, new ExtWrapNullable(type));
ExtUtil.writeBool(out, isAutoLaunching);
}
public String getImage() {
return image;
}
public String getActionName() {
return actionName;
}
public String getDisplayName() {
return displayName;
}
public Hashtable<String, String> getExtras() {
return extras;
}
public Vector<String> getResponses() {
return responses;
}
public DetailField getResponseDetailField() {
return responseDetail;
}
public boolean isAutoLaunching() {
return isAutoLaunching;
}
public boolean isSimprintsCallout() {
return "com.simprints.id.IDENTIFY".equals(actionName);
}
public void setAssumePlainTextValues() {
this.assumePlainTextValues = true;
}
}
|
src/main/java/org/commcare/suite/model/Callout.java
|
package org.commcare.suite.model;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapList;
import org.javarosa.core.util.externalizable.ExtWrapMap;
import org.javarosa.core.util.externalizable.ExtWrapNullable;
import org.javarosa.core.util.externalizable.Externalizable;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.xpath.XPathException;
import org.javarosa.xpath.XPathParseTool;
import org.javarosa.xpath.expr.FunctionUtils;
import org.javarosa.xpath.parser.XPathSyntaxException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* Application callout described in suite.xml
* Used in callouts from EntitySelectActivity and EntityDetailActivity
*
* @author wpride1 on 4/14/15.
*/
public class Callout implements Externalizable, DetailTemplate {
private String actionName;
private String image;
private String displayName;
private String type;
private Hashtable<String, String> extras;
private Vector<String> responses;
private boolean isAutoLaunching;
private boolean assumePlainTextValues;
private static final String OVERRIDE_PLAIN_TEXT_ASSUMPTION_PREFIX = "cc:xpath_prefix:";
/**
* Allows case list intent callouts to map result data to cases. 'header'
* is the column header text and 'template' is the key used for mapping a
* callout result data point to a case, should usually be the case id.
*/
private DetailField responseDetail;
/**
* For externalization
*/
public Callout() {
}
public Callout(String actionName, String image, String displayName,
Hashtable<String, String> extras, Vector<String> responses,
DetailField responseDetail, String type, boolean isAutoLaunching) {
this.actionName = actionName;
this.image = image;
this.displayName = displayName;
this.extras = extras;
this.responses = responses;
this.responseDetail = responseDetail;
this.type = type;
this.isAutoLaunching = isAutoLaunching;
this.assumePlainTextValues = false;
}
@Override
public CalloutData evaluate(EvaluationContext context) {
Hashtable<String, String> evaluatedExtras = new Hashtable<>();
Enumeration keys = extras.keys();
boolean overridePlainTextAssumption = checkForPlainTextPrefix(keys);
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
key = key.replace(OVERRIDE_PLAIN_TEXT_ASSUMPTION_PREFIX, "");
String rawValue = extras.get(key);
if (assumePlainTextValues && !overridePlainTextAssumption) {
evaluatedExtras.put(key, rawValue);
} else {
try {
String evaluatedValue =
FunctionUtils.toString(XPathParseTool.parseXPath(rawValue).eval(context));
evaluatedExtras.put(key, evaluatedValue);
} catch (XPathSyntaxException e) {
// do nothing
}
}
}
// emit a CalloutData with the extras evaluated. used for the detail screen.
return new CalloutData(actionName, image, displayName, evaluatedExtras, responses, type);
}
// Returns true if any of the keys has OVERRIDE_PLAIN_TEXT_ASSUMPTION_PREFIX
private boolean checkForPlainTextPrefix(Enumeration keys) {
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
if (key.startsWith(OVERRIDE_PLAIN_TEXT_ASSUMPTION_PREFIX)) {
return true;
}
}
return false;
}
@Override
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
displayName = ExtUtil.readString(in);
actionName = (String)ExtUtil.read(in, new ExtWrapNullable(String.class), pf);
image = (String)ExtUtil.read(in, new ExtWrapNullable(String.class), pf);
extras = (Hashtable<String, String>)ExtUtil.read(in, new ExtWrapMap(String.class, String.class), pf);
responses = (Vector<String>)ExtUtil.read(in, new ExtWrapList(String.class), pf);
responseDetail = (DetailField)ExtUtil.read(in, new ExtWrapNullable(DetailField.class), pf);
type = (String)ExtUtil.read(in, new ExtWrapNullable(String.class), pf);
isAutoLaunching = ExtUtil.readBool(in);
}
@Override
public void writeExternal(DataOutputStream out) throws IOException {
ExtUtil.writeString(out, displayName);
ExtUtil.write(out, new ExtWrapNullable(actionName));
ExtUtil.write(out, new ExtWrapNullable(image));
ExtUtil.write(out, new ExtWrapMap(extras));
ExtUtil.write(out, new ExtWrapList(responses));
ExtUtil.write(out, new ExtWrapNullable(responseDetail));
ExtUtil.write(out, new ExtWrapNullable(type));
ExtUtil.writeBool(out, isAutoLaunching);
}
public String getImage() {
return image;
}
public String getActionName() {
return actionName;
}
public String getDisplayName() {
return displayName;
}
public Hashtable<String, String> getExtras() {
return extras;
}
public Vector<String> getResponses() {
return responses;
}
public DetailField getResponseDetailField() {
return responseDetail;
}
public boolean isAutoLaunching() {
return isAutoLaunching;
}
public boolean isSimprintsCallout() {
return "com.simprints.id.IDENTIFY".equals(actionName);
}
public void setAssumePlainTextValues() {
this.assumePlainTextValues = true;
}
}
|
Decouples force xpath parsing key
|
src/main/java/org/commcare/suite/model/Callout.java
|
Decouples force xpath parsing key
|
|
Java
|
apache-2.0
|
8b31091085498ea038d82ba7ac85f9a306b20271
| 0
|
fcrepo4-labs/fcrepo-import-export
|
/*
* Licensed to DuraSpace under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* DuraSpace 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.fcrepo.importexport.importer;
import static java.util.Arrays.stream;
import static org.apache.jena.rdf.model.ResourceFactory.createResource;
import static org.apache.jena.riot.RDFLanguages.contentTypeToLang;
import static org.fcrepo.importexport.common.FcrepoConstants.BINARY_EXTENSION;
import static org.fcrepo.importexport.common.FcrepoConstants.CONTAINS;
import static org.fcrepo.importexport.common.FcrepoConstants.CONTAINER;
import static org.fcrepo.importexport.common.FcrepoConstants.DESCRIBEDBY;
import static org.fcrepo.importexport.common.FcrepoConstants.EXTERNAL_RESOURCE_EXTENSION;
import static org.fcrepo.importexport.common.FcrepoConstants.HAS_MESSAGE_DIGEST;
import static org.fcrepo.importexport.common.FcrepoConstants.HAS_MIME_TYPE;
import static org.fcrepo.importexport.common.FcrepoConstants.HAS_SIZE;
import static org.fcrepo.importexport.common.FcrepoConstants.MEMBERSHIP_RESOURCE;
import static org.fcrepo.importexport.common.FcrepoConstants.NON_RDF_SOURCE;
import static org.fcrepo.importexport.common.FcrepoConstants.PAIRTREE;
import static org.fcrepo.importexport.common.FcrepoConstants.RDF_SOURCE;
import static org.fcrepo.importexport.common.FcrepoConstants.RDF_TYPE;
import static org.fcrepo.importexport.common.FcrepoConstants.REPOSITORY_NAMESPACE;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import org.fcrepo.client.FcrepoClient;
import org.fcrepo.client.FcrepoOperationFailedException;
import org.fcrepo.client.FcrepoResponse;
import org.fcrepo.client.PutBuilder;
import org.fcrepo.importexport.common.AuthenticationRequiredRuntimeException;
import org.fcrepo.importexport.common.Config;
import org.fcrepo.importexport.common.TransferProcess;
import org.apache.commons.io.IOUtils;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.ResIterator;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RiotException;
import org.slf4j.Logger;
import gov.loc.repository.bagit.domain.Bag;
import gov.loc.repository.bagit.reader.BagReader;
import gov.loc.repository.bagit.verify.BagVerifier;
/**
* Fedora Import Utility
*
* @author awoods
* @author escowles
* @since 2016-08-29
*/
public class Importer implements TransferProcess {
private static final Logger logger = getLogger(Importer.class);
private Config config;
protected FcrepoClient.FcrepoClientBuilder clientBuilder;
private final List<URI> membershipResources = new ArrayList<>();
private Bag bag;
private MessageDigest sha1;
private Map<File, String> sha1FileMap;
private Logger importLogger;
private AtomicLong successCount = new AtomicLong(); // set to zero at start
/**
* A directory within the metadata directory that serves as the
* root of the resource being imported. If the export directory
* contains /fcrepo/rest/one/two/three and we're importing
* the resource at /fcrepo/rest/one/two, this stores that path.
*/
protected File importContainerDirectory;
/**
* Constructor that takes the Import/Export configuration
*
* @param config for import
* @param clientBuilder for sending resources to Fedora
*/
public Importer(final Config config, final FcrepoClient.FcrepoClientBuilder clientBuilder) {
this.config = config;
this.clientBuilder = clientBuilder;
this.importLogger = config.getAuditLog();
if (config.getBagProfile() == null) {
this.bag = null;
this.sha1 = null;
this.sha1FileMap = null;
} else {
try {
final File bagdir = config.getBaseDirectory().getParentFile();
// TODO: Maybe use this once we get an updated release of bagit-java library
//if (verifyBag(bagdir)) {
final Path manifestPath = Paths.get(bagdir.getAbsolutePath()).resolve("manifest-SHA1.txt");
this.sha1FileMap = TransferProcess.getSha1FileMap(bagdir, manifestPath);
this.sha1 = MessageDigest.getInstance("SHA-1");
// }
} catch (NoSuchAlgorithmException e) {
// never happens with known algorithm names
}
}
}
private FcrepoClient client() {
if (config.getUsername() != null) {
clientBuilder.credentials(config.getUsername(), config.getPassword());
}
return clientBuilder.build();
}
/**
* This method does the import
*/
@Override
public void run() {
logger.info("Running importer...");
final File importContainerMetadataFile = fileForContainerURI(config.getResource());
importContainerDirectory = TransferProcess.directoryForContainer(config.getResource(),
config.getBaseDirectory());
discoverMembershipResources(importContainerDirectory);
if (!importContainerMetadataFile.exists()) {
logger.debug("No container exists in the metadata directory {} for the requested resource {},"
+ " importing all contained resources instead.", importContainerMetadataFile.getPath(),
config.getResource());
} else {
importFile(importContainerMetadataFile);
}
importDirectory(importContainerDirectory);
importMembershipResources();
importLogger.info("Finished import... {} resources imported", successCount.get());
}
private void discoverMembershipResources(final File dir) {
if (dir.listFiles() != null) {
stream(dir.listFiles()).filter(File::isFile).forEach(f -> parseMembershipResources(f));
stream(dir.listFiles()).filter(File::isDirectory).forEach(d -> discoverMembershipResources(d));
}
}
private void parseMembershipResources(final File f) {
// skip files that aren't RDF
if (!f.getName().endsWith(config.getRdfExtension())) {
return;
}
try {
final Model model = parseStream(new FileInputStream(f));
if (model.contains(null, MEMBERSHIP_RESOURCE, (RDFNode)null)) {
model.listObjectsOfProperty(MEMBERSHIP_RESOURCE).forEachRemaining(node -> {
logger.info("Membership resource: {}", node);
membershipResources.add(URI.create(node.toString()));
});
}
} catch (final IOException e) {
throw new RuntimeException("Error reading file: " + f.getAbsolutePath() + ": " + e.toString());
} catch (final RiotException e) {
throw new RuntimeException("Error parsing RDF: " + f.getAbsolutePath() + ": " + e.toString());
}
}
private void importMembershipResources() {
membershipResources.stream().forEach(uri -> importMembershipResource(uri));
}
private void importMembershipResource(final URI uri) {
final File f = fileForContainerURI(uri);
try {
final Model diskModel = parseStream(new FileInputStream(f));
final Model repoModel = parseStream(client().get(uri).perform().getBody());
final FcrepoResponse response = importContainer(uri, sanitize(diskModel.difference(repoModel)));
if (response.getStatusCode() == 401) {
importLogger.error("Error importing {} to {}, 401 Unauthorized", f.getAbsolutePath(), uri);
throw new AuthenticationRequiredRuntimeException();
} else if (response.getStatusCode() > 204 || response.getStatusCode() < 200) {
importLogger.error("Error importing {} to {}, received {}", f.getAbsolutePath(), uri,
response.getStatusCode());
throw new RuntimeException("Error while importing membership resource " + f.getAbsolutePath()
+ " (" + response.getStatusCode() + "): " + IOUtils.toString(response.getBody()));
} else {
logger.info("Imported membership resource {}: {}", f.getAbsolutePath(), uri);
importLogger.info("import {} to {}", f.getAbsolutePath(), uri);
successCount.incrementAndGet();
}
} catch (FcrepoOperationFailedException ex) {
importLogger.error(
String.format("Error importing: {} to {}, Message: {}", f.getAbsolutePath(), uri, ex.getMessage()), ex);
throw new RuntimeException("Error importing " + f.getAbsolutePath() + ": " + ex.toString(), ex);
} catch (IOException ex) {
importLogger.error(
String.format("Error reading/parsing file: {}, Message: {}", f.getAbsolutePath(), ex.getMessage()), ex);
throw new RuntimeException(
"Error reading or parsing " + f.getAbsolutePath() + ": " + ex.toString(), ex);
}
}
private void importDirectory(final File dir) {
// process all the files first (because otherwise they might be
// created as peartree nodes which can't be updated with properties
// later.
if (dir.listFiles() != null) {
stream(dir.listFiles()).filter(File::isFile).forEach(file -> importFile(file));
stream(dir.listFiles()).filter(File::isDirectory).forEach(directory -> importDirectory(directory));
}
}
private void importFile(final File f) {
// The path, relative to the base in the export directory.
// This is used in place of the full path to make the output more readable.
final String sourceRelativePath =
config.getBaseDirectory().toPath().relativize(f.toPath()).toString();
final String filePath = f.getPath();
if (filePath.endsWith(BINARY_EXTENSION) || filePath.endsWith(EXTERNAL_RESOURCE_EXTENSION)) {
// ... this is only expected to happen when binaries and metadata are written to the same directory...
if (config.isIncludeBinaries()) {
logger.debug("Skipping binary {}: it will be imported when its metadata is imported.",
sourceRelativePath);
} else {
logger.debug("Skipping binary {}", sourceRelativePath);
}
return;
} else if (!filePath.endsWith(config.getRdfExtension())) {
// this could be hidden files created by the OS
logger.info("Skipping file with unexpected extension ({}).", sourceRelativePath);
return;
} else {
FcrepoResponse response = null;
URI destinationUri = null;
try {
final Model model = parseStream(new FileInputStream(f));
if (model.contains(null, RDF_TYPE, createResource(REPOSITORY_NAMESPACE + "RepositoryRoot"))) {
logger.debug("Skipping import of repository root.");
return;
}
final ResIterator binaryResources = model.listResourcesWithProperty(RDF_TYPE, NON_RDF_SOURCE);
if (binaryResources.hasNext()) {
if (!config.isIncludeBinaries()) {
return;
}
destinationUri = new URI(binaryResources.nextResource().getURI());
logger.info("Importing binary {}", sourceRelativePath);
response = importBinary(destinationUri, model);
} else {
destinationUri = new URI(config.getResource().toString() + "/"
+ uriPathForFile(f, importContainerDirectory));
if (membershipResources.contains(destinationUri)) {
logger.warn("Skipping Membership Resource: {}", destinationUri);
return;
}
if (model.contains(null, RDF_TYPE, PAIRTREE)) {
logger.info("Skipping PairTree Resource: {}", destinationUri);
return;
}
logger.info("Importing container {} to {}", f.getAbsolutePath(), destinationUri);
response = importContainer(destinationUri, sanitize(model));
}
if (response == null) {
logger.warn("Failed to import {}", f.getAbsolutePath());
} else if (response.getStatusCode() == 401) {
importLogger.error("Error importing {} to {}, 401 Unauthorized", f.getAbsolutePath(),
destinationUri);
throw new AuthenticationRequiredRuntimeException();
} else if (response.getStatusCode() > 204 || response.getStatusCode() < 200) {
final String message = "Error while importing " + f.getAbsolutePath() + " ("
+ response.getStatusCode() + "): " + IOUtils.toString(response.getBody());
logger.error(message);
importLogger.error("Error importing {} to {}, received {}", f.getAbsolutePath(), destinationUri,
response.getStatusCode());
} else {
logger.info("Imported {}: {}", f.getAbsolutePath(), destinationUri);
importLogger.info("import {} to {}", f.getAbsolutePath(), destinationUri);
successCount.incrementAndGet();
}
} catch (FcrepoOperationFailedException ex) {
importLogger.error(String.format("Error importing {} to {}, Message: {}", f.getAbsolutePath(),
destinationUri, ex.getMessage()), ex);
throw new RuntimeException("Error importing " + f.getAbsolutePath() + ": " + ex.toString(), ex);
} catch (IOException ex) {
importLogger.error(String.format("Error reading/parsing {} to {}, Message: {}", f.getAbsolutePath(),
destinationUri, ex.getMessage()), ex);
throw new RuntimeException(
"Error reading or parsing " + f.getAbsolutePath() + ": " + ex.toString(), ex);
} catch (URISyntaxException ex) {
importLogger.error(
String.format("Error building URI for {}, Message: {}", f.getAbsolutePath(), ex.getMessage()), ex);
throw new RuntimeException("Error building URI for " + f.getAbsolutePath() + ": " + ex.toString(), ex);
}
}
}
private Model parseStream(final InputStream in) throws IOException {
final URI source = config.getSource();
final SubjectMappingStreamRDF mapper = new SubjectMappingStreamRDF(source, config.getResource());
try (final InputStream in2 = in) {
RDFDataMgr.parse(mapper, in2, contentTypeToLang(config.getRdfLanguage()));
}
return mapper.getModel();
}
private FcrepoResponse importBinary(final URI binaryURI, final Model model)
throws FcrepoOperationFailedException, IOException {
final Resource binaryRes = createResource(binaryURI.toString());
final String contentType = model.getProperty(binaryRes, HAS_MIME_TYPE).getString();
final boolean external = contentType.contains("message/external-body");
final File binaryFile = fileForBinaryURI(binaryURI, external);
final InputStream contentStream;
if (external) {
contentStream = new ByteArrayInputStream(new byte[]{});
} else {
contentStream = new FileInputStream(binaryFile);
}
PutBuilder builder = client().put(binaryURI).body(contentStream, contentType);
if (!external) {
if (sha1FileMap != null) {
// Use the bagIt checksum
final String checksum = sha1FileMap.get(binaryFile);
logger.debug("Using Bagit checksum ({}) for file ({})", checksum, binaryFile.getPath());
builder = builder.digest(checksum);
} else {
builder = builder.digest(model.getProperty(binaryRes, HAS_MESSAGE_DIGEST)
.getObject().toString().replaceAll(".*:",""));
}
}
final FcrepoResponse binaryResponse = builder.perform();
if (binaryResponse.getStatusCode() == 201 || binaryResponse.getStatusCode() == 204) {
logger.info("Imported binary: {}", binaryURI);
importLogger.info("import {} to {}", binaryFile.getAbsolutePath(), binaryURI);
successCount.incrementAndGet();
final URI descriptionURI = binaryResponse.getLinkHeaders("describedby").get(0);
return client().put(descriptionURI).body(modelToStream(sanitize(model)), config.getRdfLanguage())
.preferLenient().perform();
} else {
logger.error("Error while importing {} ({}): {}", binaryFile.getAbsolutePath(),
binaryResponse.getStatusCode(), IOUtils.toString(binaryResponse.getBody()));
return null;
}
}
private FcrepoResponse importContainer(final URI uri, final Model model) throws FcrepoOperationFailedException {
PutBuilder builder = client().put(uri).body(modelToStream(model), config.getRdfLanguage());
if (sha1FileMap != null && config.getBagProfile() != null) {
// Use the bagIt checksum
final File baseDir = config.getBaseDirectory();
final File containerFile = Paths.get(fileForContainerURI(uri).toURI()).normalize().toFile();
final String checksum = sha1FileMap.get(containerFile);
logger.debug("Using Bagit checksum ({}) for file ({})", checksum, containerFile.getPath());
builder = builder.digest(checksum);
}
return builder.preferLenient().perform();
}
private Model sanitize(final Model model) throws IOException, FcrepoOperationFailedException {
final List<Statement> remove = new ArrayList<>();
for (final StmtIterator it = model.listStatements(); it.hasNext(); ) {
final Statement s = it.nextStatement();
if (s.getPredicate().getNameSpace().equals(REPOSITORY_NAMESPACE)
|| s.getSubject().getURI().endsWith("fcr:export?format=jcr/xml")
|| s.getSubject().getURI().equals(REPOSITORY_NAMESPACE + "jcr/xml")
|| s.getPredicate().equals(DESCRIBEDBY)
|| s.getPredicate().equals(CONTAINS)
|| s.getPredicate().equals(HAS_MESSAGE_DIGEST)
|| s.getPredicate().equals(HAS_SIZE)
|| (s.getPredicate().equals(RDF_TYPE) && forbiddenType(s.getResource()))) {
remove.add(s);
} else if (s.getObject().isResource()) {
// make sure that referenced repository objects exist
final String obj = s.getResource().toString();
if (obj.startsWith(config.getResource().toString())) {
ensureExists(URI.create(obj));
}
}
}
return model.remove(remove);
}
private boolean forbiddenType(final Resource resource) {
return resource.getNameSpace().equals(REPOSITORY_NAMESPACE)
|| resource.getURI().equals(CONTAINER.getURI())
|| resource.getURI().equals(NON_RDF_SOURCE.getURI())
|| resource.getURI().equals(RDF_SOURCE.getURI());
}
/**
* Make sure that a URI exists in the repository.
*/
private void ensureExists(final URI uri) throws IOException, FcrepoOperationFailedException {
try (FcrepoResponse response = client().head(uri).perform()) {
if (response.getStatusCode() != 200) {
makePlaceholder(uri);
}
}
}
private void makePlaceholder(final URI uri) throws IOException, FcrepoOperationFailedException {
ensureExists(parent(uri));
final FcrepoResponse response;
if (fileForBinaryURI(uri, false).exists() || fileForBinaryURI(uri, true).exists()) {
response = client().put(uri).body(new ByteArrayInputStream(new byte[]{})).perform();
} else if (fileForContainerURI(uri).exists()) {
response = client().put(uri).body(new ByteArrayInputStream(
"<> a <http://www.w3.org/ns/ldp#Container> .".getBytes()), "text/turtle").perform();
} else {
return;
}
if (response.getStatusCode() != 201) {
logger.error("Unexpected response when creating {} ({}): {}", uri,
response.getStatusCode(), response.getBody());
}
}
private static URI parent(final URI uri) {
String s = uri.toString();
if (s.endsWith("/")) {
s = s.substring(0, s.length() - 1);
}
return URI.create(s.substring(0, s.lastIndexOf("/")));
}
private InputStream modelToStream(final Model model) {
final ByteArrayOutputStream buf = new ByteArrayOutputStream();
model.write(buf, config.getRdfLanguage());
return new ByteArrayInputStream(buf.toByteArray());
}
private String uriPathForFile(final File f, final File baseDir) throws URISyntaxException {
String relative = baseDir.toPath().relativize(f.toPath()).toString();
relative = TransferProcess.decodePath(relative);
// for exported RDF, just remove the ".extension" and you have the encoded path
if (relative.endsWith(config.getRdfExtension())) {
relative = relative.substring(0, relative.length() - config.getRdfExtension().length());
}
return relative;
}
private File fileForBinaryURI(final URI uri, final boolean external) {
return new File(config.getBaseDirectory() + TransferProcess.decodePath(uri.getPath()) +
(external ? EXTERNAL_RESOURCE_EXTENSION : BINARY_EXTENSION));
}
private File fileForContainerURI(final URI uri) {
return TransferProcess.fileForURI(uri, config.getBaseDirectory(), config.getRdfExtension());
}
/**
* Verify the bag we are going to import
*
* @param bagDir root directory of the bag
* @return true if valid
*/
public static boolean verifyBag(final File bagDir) {
try {
final Bag bag = BagReader.read(bagDir);
BagVerifier.isValid(bag, true);
return true;
} catch (Exception e) {
throw new RuntimeException(String.format("Error verifying bag: %s", e.getMessage()), e);
}
}
}
|
src/main/java/org/fcrepo/importexport/importer/Importer.java
|
/*
* Licensed to DuraSpace under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* DuraSpace 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.fcrepo.importexport.importer;
import static java.util.Arrays.stream;
import static org.apache.jena.rdf.model.ResourceFactory.createResource;
import static org.apache.jena.riot.RDFLanguages.contentTypeToLang;
import static org.fcrepo.importexport.common.FcrepoConstants.BINARY_EXTENSION;
import static org.fcrepo.importexport.common.FcrepoConstants.CONTAINS;
import static org.fcrepo.importexport.common.FcrepoConstants.DESCRIBEDBY;
import static org.fcrepo.importexport.common.FcrepoConstants.EXTERNAL_RESOURCE_EXTENSION;
import static org.fcrepo.importexport.common.FcrepoConstants.HAS_MESSAGE_DIGEST;
import static org.fcrepo.importexport.common.FcrepoConstants.HAS_MIME_TYPE;
import static org.fcrepo.importexport.common.FcrepoConstants.HAS_SIZE;
import static org.fcrepo.importexport.common.FcrepoConstants.MEMBERSHIP_RESOURCE;
import static org.fcrepo.importexport.common.FcrepoConstants.NON_RDF_SOURCE;
import static org.fcrepo.importexport.common.FcrepoConstants.PAIRTREE;
import static org.fcrepo.importexport.common.FcrepoConstants.RDF_TYPE;
import static org.fcrepo.importexport.common.FcrepoConstants.REPOSITORY_NAMESPACE;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import org.fcrepo.client.FcrepoClient;
import org.fcrepo.client.FcrepoOperationFailedException;
import org.fcrepo.client.FcrepoResponse;
import org.fcrepo.client.PutBuilder;
import org.fcrepo.importexport.common.AuthenticationRequiredRuntimeException;
import org.fcrepo.importexport.common.Config;
import org.fcrepo.importexport.common.TransferProcess;
import org.apache.commons.io.IOUtils;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.ResIterator;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RiotException;
import org.slf4j.Logger;
import gov.loc.repository.bagit.domain.Bag;
import gov.loc.repository.bagit.reader.BagReader;
import gov.loc.repository.bagit.verify.BagVerifier;
/**
* Fedora Import Utility
*
* @author awoods
* @author escowles
* @since 2016-08-29
*/
public class Importer implements TransferProcess {
private static final Logger logger = getLogger(Importer.class);
private Config config;
protected FcrepoClient.FcrepoClientBuilder clientBuilder;
private final List<URI> membershipResources = new ArrayList<>();
private Bag bag;
private MessageDigest sha1;
private Map<File, String> sha1FileMap;
private Logger importLogger;
private AtomicLong successCount = new AtomicLong(); // set to zero at start
/**
* A directory within the metadata directory that serves as the
* root of the resource being imported. If the export directory
* contains /fcrepo/rest/one/two/three and we're importing
* the resource at /fcrepo/rest/one/two, this stores that path.
*/
protected File importContainerDirectory;
/**
* Constructor that takes the Import/Export configuration
*
* @param config for import
* @param clientBuilder for sending resources to Fedora
*/
public Importer(final Config config, final FcrepoClient.FcrepoClientBuilder clientBuilder) {
this.config = config;
this.clientBuilder = clientBuilder;
this.importLogger = config.getAuditLog();
if (config.getBagProfile() == null) {
this.bag = null;
this.sha1 = null;
this.sha1FileMap = null;
} else {
try {
final File bagdir = config.getBaseDirectory().getParentFile();
// TODO: Maybe use this once we get an updated release of bagit-java library
//if (verifyBag(bagdir)) {
final Path manifestPath = Paths.get(bagdir.getAbsolutePath()).resolve("manifest-SHA1.txt");
this.sha1FileMap = TransferProcess.getSha1FileMap(bagdir, manifestPath);
this.sha1 = MessageDigest.getInstance("SHA-1");
// }
} catch (NoSuchAlgorithmException e) {
// never happens with known algorithm names
}
}
}
private FcrepoClient client() {
if (config.getUsername() != null) {
clientBuilder.credentials(config.getUsername(), config.getPassword());
}
return clientBuilder.build();
}
/**
* This method does the import
*/
@Override
public void run() {
logger.info("Running importer...");
final File importContainerMetadataFile = fileForContainerURI(config.getResource());
importContainerDirectory = TransferProcess.directoryForContainer(config.getResource(),
config.getBaseDirectory());
discoverMembershipResources(importContainerDirectory);
if (!importContainerMetadataFile.exists()) {
logger.debug("No container exists in the metadata directory {} for the requested resource {},"
+ " importing all contained resources instead.", importContainerMetadataFile.getPath(),
config.getResource());
} else {
importFile(importContainerMetadataFile);
}
importDirectory(importContainerDirectory);
importMembershipResources();
importLogger.info("Finished import... {} resources imported", successCount.get());
}
private void discoverMembershipResources(final File dir) {
if (dir.listFiles() != null) {
stream(dir.listFiles()).filter(File::isFile).forEach(f -> parseMembershipResources(f));
stream(dir.listFiles()).filter(File::isDirectory).forEach(d -> discoverMembershipResources(d));
}
}
private void parseMembershipResources(final File f) {
// skip files that aren't RDF
if (!f.getName().endsWith(config.getRdfExtension())) {
return;
}
try {
final Model model = parseStream(new FileInputStream(f));
if (model.contains(null, MEMBERSHIP_RESOURCE, (RDFNode)null)) {
model.listObjectsOfProperty(MEMBERSHIP_RESOURCE).forEachRemaining(node -> {
logger.info("Membership resource: {}", node);
membershipResources.add(URI.create(node.toString()));
});
}
} catch (final IOException e) {
throw new RuntimeException("Error reading file: " + f.getAbsolutePath() + ": " + e.toString());
} catch (final RiotException e) {
throw new RuntimeException("Error parsing RDF: " + f.getAbsolutePath() + ": " + e.toString());
}
}
private void importMembershipResources() {
membershipResources.stream().forEach(uri -> importMembershipResource(uri));
}
private void importMembershipResource(final URI uri) {
final File f = fileForContainerURI(uri);
try {
final Model diskModel = parseStream(new FileInputStream(f));
final Model repoModel = parseStream(client().get(uri).perform().getBody());
final FcrepoResponse response = importContainer(uri, sanitize(diskModel.difference(repoModel)));
if (response.getStatusCode() == 401) {
importLogger.error("Error importing {} to {}, 401 Unauthorized", f.getAbsolutePath(), uri);
throw new AuthenticationRequiredRuntimeException();
} else if (response.getStatusCode() > 204 || response.getStatusCode() < 200) {
importLogger.error("Error importing {} to {}, received {}", f.getAbsolutePath(), uri,
response.getStatusCode());
throw new RuntimeException("Error while importing membership resource " + f.getAbsolutePath()
+ " (" + response.getStatusCode() + "): " + IOUtils.toString(response.getBody()));
} else {
logger.info("Imported membership resource {}: {}", f.getAbsolutePath(), uri);
importLogger.info("import {} to {}", f.getAbsolutePath(), uri);
successCount.incrementAndGet();
}
} catch (FcrepoOperationFailedException ex) {
importLogger.error(
String.format("Error importing: {} to {}, Message: {}", f.getAbsolutePath(), uri, ex.getMessage()), ex);
throw new RuntimeException("Error importing " + f.getAbsolutePath() + ": " + ex.toString(), ex);
} catch (IOException ex) {
importLogger.error(
String.format("Error reading/parsing file: {}, Message: {}", f.getAbsolutePath(), ex.getMessage()), ex);
throw new RuntimeException(
"Error reading or parsing " + f.getAbsolutePath() + ": " + ex.toString(), ex);
}
}
private void importDirectory(final File dir) {
// process all the files first (because otherwise they might be
// created as peartree nodes which can't be updated with properties
// later.
if (dir.listFiles() != null) {
stream(dir.listFiles()).filter(File::isFile).forEach(file -> importFile(file));
stream(dir.listFiles()).filter(File::isDirectory).forEach(directory -> importDirectory(directory));
}
}
private void importFile(final File f) {
// The path, relative to the base in the export directory.
// This is used in place of the full path to make the output more readable.
final String sourceRelativePath =
config.getBaseDirectory().toPath().relativize(f.toPath()).toString();
final String filePath = f.getPath();
if (filePath.endsWith(BINARY_EXTENSION) || filePath.endsWith(EXTERNAL_RESOURCE_EXTENSION)) {
// ... this is only expected to happen when binaries and metadata are written to the same directory...
if (config.isIncludeBinaries()) {
logger.debug("Skipping binary {}: it will be imported when its metadata is imported.",
sourceRelativePath);
} else {
logger.debug("Skipping binary {}", sourceRelativePath);
}
return;
} else if (!filePath.endsWith(config.getRdfExtension())) {
// this could be hidden files created by the OS
logger.info("Skipping file with unexpected extension ({}).", sourceRelativePath);
return;
} else {
FcrepoResponse response = null;
URI destinationUri = null;
try {
final Model model = parseStream(new FileInputStream(f));
if (model.contains(null, RDF_TYPE, createResource(REPOSITORY_NAMESPACE + "RepositoryRoot"))) {
logger.debug("Skipping import of repository root.");
return;
}
final ResIterator binaryResources = model.listResourcesWithProperty(RDF_TYPE, NON_RDF_SOURCE);
if (binaryResources.hasNext()) {
if (!config.isIncludeBinaries()) {
return;
}
destinationUri = new URI(binaryResources.nextResource().getURI());
logger.info("Importing binary {}", sourceRelativePath);
response = importBinary(destinationUri, model);
} else {
destinationUri = new URI(config.getResource().toString() + "/"
+ uriPathForFile(f, importContainerDirectory));
if (membershipResources.contains(destinationUri)) {
logger.warn("Skipping Membership Resource: {}", destinationUri);
return;
}
if (model.contains(null, RDF_TYPE, PAIRTREE)) {
logger.info("Skipping PairTree Resource: {}", destinationUri);
return;
}
logger.info("Importing container {} to {}", f.getAbsolutePath(), destinationUri);
response = importContainer(destinationUri, sanitize(model));
}
if (response == null) {
logger.warn("Failed to import {}", f.getAbsolutePath());
} else if (response.getStatusCode() == 401) {
importLogger.error("Error importing {} to {}, 401 Unauthorized", f.getAbsolutePath(),
destinationUri);
throw new AuthenticationRequiredRuntimeException();
} else if (response.getStatusCode() > 204 || response.getStatusCode() < 200) {
final String message = "Error while importing " + f.getAbsolutePath() + " ("
+ response.getStatusCode() + "): " + IOUtils.toString(response.getBody());
logger.error(message);
importLogger.error("Error importing {} to {}, received {}", f.getAbsolutePath(), destinationUri,
response.getStatusCode());
} else {
logger.info("Imported {}: {}", f.getAbsolutePath(), destinationUri);
importLogger.info("import {} to {}", f.getAbsolutePath(), destinationUri);
successCount.incrementAndGet();
}
} catch (FcrepoOperationFailedException ex) {
importLogger.error(String.format("Error importing {} to {}, Message: {}", f.getAbsolutePath(),
destinationUri, ex.getMessage()), ex);
throw new RuntimeException("Error importing " + f.getAbsolutePath() + ": " + ex.toString(), ex);
} catch (IOException ex) {
importLogger.error(String.format("Error reading/parsing {} to {}, Message: {}", f.getAbsolutePath(),
destinationUri, ex.getMessage()), ex);
throw new RuntimeException(
"Error reading or parsing " + f.getAbsolutePath() + ": " + ex.toString(), ex);
} catch (URISyntaxException ex) {
importLogger.error(
String.format("Error building URI for {}, Message: {}", f.getAbsolutePath(), ex.getMessage()), ex);
throw new RuntimeException("Error building URI for " + f.getAbsolutePath() + ": " + ex.toString(), ex);
}
}
}
private Model parseStream(final InputStream in) throws IOException {
final URI source = config.getSource();
final SubjectMappingStreamRDF mapper = new SubjectMappingStreamRDF(source, config.getResource());
try (final InputStream in2 = in) {
RDFDataMgr.parse(mapper, in2, contentTypeToLang(config.getRdfLanguage()));
}
return mapper.getModel();
}
private FcrepoResponse importBinary(final URI binaryURI, final Model model)
throws FcrepoOperationFailedException, IOException {
final Resource binaryRes = createResource(binaryURI.toString());
final String contentType = model.getProperty(binaryRes, HAS_MIME_TYPE).getString();
final boolean external = contentType.contains("message/external-body");
final File binaryFile = fileForBinaryURI(binaryURI, external);
final InputStream contentStream;
if (external) {
contentStream = new ByteArrayInputStream(new byte[]{});
} else {
contentStream = new FileInputStream(binaryFile);
}
PutBuilder builder = client().put(binaryURI).body(contentStream, contentType);
if (!external) {
if (sha1FileMap != null) {
// Use the bagIt checksum
final String checksum = sha1FileMap.get(binaryFile);
logger.debug("Using Bagit checksum ({}) for file ({})", checksum, binaryFile.getPath());
builder = builder.digest(checksum);
} else {
builder = builder.digest(model.getProperty(binaryRes, HAS_MESSAGE_DIGEST)
.getObject().toString().replaceAll(".*:",""));
}
}
final FcrepoResponse binaryResponse = builder.perform();
if (binaryResponse.getStatusCode() == 201 || binaryResponse.getStatusCode() == 204) {
logger.info("Imported binary: {}", binaryURI);
importLogger.info("import {} to {}", binaryFile.getAbsolutePath(), binaryURI);
successCount.incrementAndGet();
final URI descriptionURI = binaryResponse.getLinkHeaders("describedby").get(0);
return client().put(descriptionURI).body(modelToStream(sanitize(model)), config.getRdfLanguage())
.preferLenient().perform();
} else {
logger.error("Error while importing {} ({}): {}", binaryFile.getAbsolutePath(),
binaryResponse.getStatusCode(), IOUtils.toString(binaryResponse.getBody()));
return null;
}
}
private FcrepoResponse importContainer(final URI uri, final Model model) throws FcrepoOperationFailedException {
PutBuilder builder = client().put(uri).body(modelToStream(model), config.getRdfLanguage());
if (sha1FileMap != null && config.getBagProfile() != null) {
// Use the bagIt checksum
final File baseDir = config.getBaseDirectory();
final File containerFile = Paths.get(fileForContainerURI(uri).toURI()).normalize().toFile();
final String checksum = sha1FileMap.get(containerFile);
logger.debug("Using Bagit checksum ({}) for file ({})", checksum, containerFile.getPath());
builder = builder.digest(checksum);
}
return builder.preferLenient().perform();
}
private Model sanitize(final Model model) throws IOException, FcrepoOperationFailedException {
final List<Statement> remove = new ArrayList<>();
for (final StmtIterator it = model.listStatements(); it.hasNext(); ) {
final Statement s = it.nextStatement();
if (s.getPredicate().getNameSpace().equals(REPOSITORY_NAMESPACE)
|| s.getSubject().getURI().endsWith("fcr:export?format=jcr/xml")
|| s.getSubject().getURI().equals(REPOSITORY_NAMESPACE + "jcr/xml")
|| s.getPredicate().equals(DESCRIBEDBY)
|| s.getPredicate().equals(CONTAINS)
|| s.getPredicate().equals(HAS_MESSAGE_DIGEST)
|| s.getPredicate().equals(HAS_SIZE)
|| (s.getPredicate().equals(RDF_TYPE)
&& s.getResource().getNameSpace().equals(REPOSITORY_NAMESPACE)) ) {
remove.add(s);
} else if (s.getObject().isResource()) {
// make sure that referenced repository objects exist
final String obj = s.getResource().toString();
if (obj.startsWith(config.getResource().toString())) {
ensureExists(URI.create(obj));
}
}
}
return model.remove(remove);
}
/**
* Make sure that a URI exists in the repository.
*/
private void ensureExists(final URI uri) throws IOException, FcrepoOperationFailedException {
try (FcrepoResponse response = client().head(uri).perform()) {
if (response.getStatusCode() != 200) {
makePlaceholder(uri);
}
}
}
private void makePlaceholder(final URI uri) throws IOException, FcrepoOperationFailedException {
ensureExists(parent(uri));
final FcrepoResponse response;
if (fileForBinaryURI(uri, false).exists() || fileForBinaryURI(uri, true).exists()) {
response = client().put(uri).body(new ByteArrayInputStream(new byte[]{})).perform();
} else if (fileForContainerURI(uri).exists()) {
response = client().put(uri).body(new ByteArrayInputStream(
"<> a <http://www.w3.org/ns/ldp#Container> .".getBytes()), "text/turtle").perform();
} else {
return;
}
if (response.getStatusCode() != 201) {
logger.error("Unexpected response when creating {} ({}): {}", uri,
response.getStatusCode(), response.getBody());
}
}
private static URI parent(final URI uri) {
String s = uri.toString();
if (s.endsWith("/")) {
s = s.substring(0, s.length() - 1);
}
return URI.create(s.substring(0, s.lastIndexOf("/")));
}
private InputStream modelToStream(final Model model) {
final ByteArrayOutputStream buf = new ByteArrayOutputStream();
model.write(buf, config.getRdfLanguage());
return new ByteArrayInputStream(buf.toByteArray());
}
private String uriPathForFile(final File f, final File baseDir) throws URISyntaxException {
String relative = baseDir.toPath().relativize(f.toPath()).toString();
relative = TransferProcess.decodePath(relative);
// for exported RDF, just remove the ".extension" and you have the encoded path
if (relative.endsWith(config.getRdfExtension())) {
relative = relative.substring(0, relative.length() - config.getRdfExtension().length());
}
return relative;
}
private File fileForBinaryURI(final URI uri, final boolean external) {
return new File(config.getBaseDirectory() + TransferProcess.decodePath(uri.getPath()) +
(external ? EXTERNAL_RESOURCE_EXTENSION : BINARY_EXTENSION));
}
private File fileForContainerURI(final URI uri) {
return TransferProcess.fileForURI(uri, config.getBaseDirectory(), config.getRdfExtension());
}
/**
* Verify the bag we are going to import
*
* @param bagDir root directory of the bag
* @return true if valid
*/
public static boolean verifyBag(final File bagDir) {
try {
final Bag bag = BagReader.read(bagDir);
BagVerifier.isValid(bag, true);
return true;
} catch (Exception e) {
throw new RuntimeException(String.format("Error verifying bag: %s", e.getMessage()), e);
}
}
}
|
Suppress server-managed LDP types
|
src/main/java/org/fcrepo/importexport/importer/Importer.java
|
Suppress server-managed LDP types
|
|
Java
|
apache-2.0
|
4aced8534cfeb571c3bf29e75908ed4bedd7c757
| 0
|
ganskef/LittleProxy-mitm
|
package org.littleshoot.proxy.mitm;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyManagementException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Random;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x500.X500NameBuilder;
import org.bouncycastle.asn1.x500.style.BCStyle;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.cert.CertIOException;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.bc.BcX509ExtensionUtils;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class CertificateHelper {
private static final Logger log = LoggerFactory.getLogger(CertificateHelper.class);
public static final String PROVIDER_NAME = BouncyCastleProvider.PROVIDER_NAME;
static {
Security.addProvider(new BouncyCastleProvider());
}
private static final String KEYGEN_ALGORITHM = "RSA";
private static final String SECURE_RANDOM_ALGORITHM = "SHA1PRNG";
/**
* The signature algorithm starting with the message digest to use when
* signing certificates. On 64-bit systems this should be set to SHA512, on
* 32-bit systems this is SHA256. On 64-bit systems, SHA512 generally
* performs better than SHA256; see this question for details:
* http://crypto.stackexchange.com/questions/26336/sha512-faster-than-sha256
*/
private static final String SIGNATURE_ALGORITHM = is32BitJvm() ? "SHA256" : "SHA512" + "WithRSAEncryption";
/**
* Uses the non-portable system property sun.arch.data.model to help
* determine if we are running on a 32-bit JVM. Since the majority of modern
* systems are 64 bits, this method "assumes" 64 bits and only returns true
* if sun.arch.data.model explicitly indicates a 32-bit JVM.
*
* @return true if we can determine definitively that this is a 32-bit JVM,
* otherwise false
*/
private static boolean is32BitJvm() {
Integer bits = Integer.getInteger("sun.arch.data.model");
return bits != null && bits == 32;
}
private static final int ROOT_KEYSIZE = 2048;
private static final int FAKE_KEYSIZE = 1024;
/**
* Current time minus 1 year, just in case software clock goes back due to
* time synchronization
*/
private static final Date NOT_BEFORE = new Date(System.currentTimeMillis() - 86400000L * 365);
/**
* The maximum possible value in X.509 specification: 9999-12-31 23:59:59,
* new Date(253402300799000L), but Apple iOS 8 fails with a certificate
* expiration date grater than Mon, 24 Jan 6084 02:07:59 GMT (issue #6).
*
* Hundred years in the future from starting the proxy should be enough.
*/
private static final Date NOT_AFTER = new Date(
System.currentTimeMillis() + 86400000L * 365 * 100);
/**
* Enforce TLS 1.2 if available, since it's not default up to Java 8.
* <p>
* Java 7 disables TLS 1.1 and 1.2 for clients. From <a href=
* "http://docs.oracle.com/javase/7/docs/technotes/guides/security/SunProviders.html"
* >Java Cryptography Architecture Oracle Providers Documentation:</a>
* Although SunJSSE in the Java SE 7 release supports TLS 1.1 and TLS 1.2,
* neither version is enabled by default for client connections. Some
* servers do not implement forward compatibility correctly and refuse to
* talk to TLS 1.1 or TLS 1.2 clients. For interoperability, SunJSSE does
* not enable TLS 1.1 or TLS 1.2 by default for client connections.
*/
private static final String SSL_CONTEXT_PROTOCOL = "TLSv1.2";
/**
* {@link SSLContext}: Every implementation of the Java platform is required
* to support the following standard SSLContext protocol: TLSv1
*/
private static final String SSL_CONTEXT_FALLBACK_PROTOCOL = "TLSv1";
public static KeyPair generateKeyPair(int keySize)
throws NoSuchAlgorithmException, NoSuchProviderException {
KeyPairGenerator generator = KeyPairGenerator
.getInstance(KEYGEN_ALGORITHM/* , PROVIDER_NAME */);
SecureRandom secureRandom = SecureRandom
.getInstance(SECURE_RANDOM_ALGORITHM/* , PROVIDER_NAME */);
generator.initialize(keySize, secureRandom);
return generator.generateKeyPair();
}
public static KeyStore createRootCertificate(Authority authority,
String keyStoreType) throws NoSuchAlgorithmException,
NoSuchProviderException, CertIOException, IOException,
OperatorCreationException, CertificateException, KeyStoreException {
KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE);
X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
nameBuilder.addRDN(BCStyle.CN, authority.commonName());
nameBuilder.addRDN(BCStyle.O, authority.organization());
nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName());
X500Name issuer = nameBuilder.build();
BigInteger serial = BigInteger.valueOf(initRandomSerial());
X500Name subject = issuer;
PublicKey pubKey = keyPair.getPublic();
X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(
issuer, serial, NOT_BEFORE, NOT_AFTER, subject, pubKey);
generator.addExtension(Extension.subjectKeyIdentifier, false,
createSubjectKeyIdentifier(pubKey));
generator.addExtension(Extension.basicConstraints, true,
new BasicConstraints(true));
KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign
| KeyUsage.digitalSignature | KeyUsage.keyEncipherment
| KeyUsage.dataEncipherment | KeyUsage.cRLSign);
generator.addExtension(Extension.keyUsage, false, usage);
ASN1EncodableVector purposes = new ASN1EncodableVector();
purposes.add(KeyPurposeId.id_kp_serverAuth);
purposes.add(KeyPurposeId.id_kp_clientAuth);
purposes.add(KeyPurposeId.anyExtendedKeyUsage);
generator.addExtension(Extension.extendedKeyUsage, false,
new DERSequence(purposes));
X509Certificate cert = signCertificate(generator, keyPair.getPrivate());
KeyStore result = KeyStore
.getInstance(keyStoreType/* , PROVIDER_NAME */);
result.load(null, null);
result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
authority.password(), new Certificate[] { cert });
return result;
}
private static SubjectKeyIdentifier createSubjectKeyIdentifier(Key key)
throws IOException {
ByteArrayInputStream bIn = new ByteArrayInputStream(key.getEncoded());
ASN1InputStream is = null;
try {
is = new ASN1InputStream(bIn);
ASN1Sequence seq = (ASN1Sequence) is.readObject();
SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(seq);
return new BcX509ExtensionUtils().createSubjectKeyIdentifier(info);
} finally {
IOUtils.closeQuietly(is);
}
}
public static KeyStore createServerCertificate(String commonName,
SubjectAlternativeNameHolder subjectAlternativeNames,
Authority authority, Certificate caCert, PrivateKey caPrivKey)
throws NoSuchAlgorithmException, NoSuchProviderException,
IOException, OperatorCreationException, CertificateException,
InvalidKeyException, SignatureException, KeyStoreException {
KeyPair keyPair = generateKeyPair(FAKE_KEYSIZE);
X500Name issuer = new X509CertificateHolder(caCert.getEncoded())
.getSubject();
BigInteger serial = BigInteger.valueOf(initRandomSerial());
X500NameBuilder name = new X500NameBuilder(BCStyle.INSTANCE);
name.addRDN(BCStyle.CN, commonName);
name.addRDN(BCStyle.O, authority.certOrganisation());
name.addRDN(BCStyle.OU, authority.certOrganizationalUnitName());
X500Name subject = name.build();
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
issuer, serial, NOT_BEFORE, NOT_AFTER, subject,
keyPair.getPublic());
builder.addExtension(Extension.subjectKeyIdentifier, false,
createSubjectKeyIdentifier(keyPair.getPublic()));
builder.addExtension(Extension.basicConstraints, false,
new BasicConstraints(false));
subjectAlternativeNames.fillInto(builder);
X509Certificate cert = signCertificate(builder, caPrivKey);
cert.checkValidity(new Date());
cert.verify(caCert.getPublicKey());
KeyStore result = KeyStore.getInstance(KeyStore.getDefaultType()
/* , PROVIDER_NAME */);
result.load(null, null);
Certificate[] chain = { cert, caCert };
result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
authority.password(), chain);
return result;
}
private static X509Certificate signCertificate(
X509v3CertificateBuilder certificateBuilder,
PrivateKey signedWithPrivateKey) throws OperatorCreationException,
CertificateException {
ContentSigner signer = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM)
.setProvider(PROVIDER_NAME).build(signedWithPrivateKey);
X509Certificate cert = new JcaX509CertificateConverter().setProvider(
PROVIDER_NAME).getCertificate(certificateBuilder.build(signer));
return cert;
}
public static TrustManager[] getTrustManagers(KeyStore keyStore)
throws KeyStoreException, NoSuchAlgorithmException,
NoSuchProviderException {
String trustManAlg = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManAlg
/* , PROVIDER_NAME */);
tmf.init(keyStore);
return tmf.getTrustManagers();
}
public static KeyManager[] getKeyManagers(KeyStore keyStore,
Authority authority) throws NoSuchAlgorithmException,
NoSuchProviderException, UnrecoverableKeyException,
KeyStoreException {
String keyManAlg = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManAlg
/* , PROVIDER_NAME */);
kmf.init(keyStore, authority.password());
return kmf.getKeyManagers();
}
public static SSLContext newClientContext(KeyManager[] keyManagers,
TrustManager[] trustManagers) throws NoSuchAlgorithmException,
KeyManagementException, NoSuchProviderException {
SSLContext result = newSSLContext();
result.init(keyManagers, trustManagers, null);
return result;
}
public static SSLContext newServerContext(KeyManager[] keyManagers)
throws NoSuchAlgorithmException, NoSuchProviderException,
KeyManagementException {
SSLContext result = newSSLContext();
SecureRandom random = new SecureRandom();
random.setSeed(System.currentTimeMillis());
result.init(keyManagers, null, random);
return result;
}
private static SSLContext newSSLContext() throws NoSuchAlgorithmException {
try {
log.debug("Using protocol {}", SSL_CONTEXT_PROTOCOL);
return SSLContext.getInstance(SSL_CONTEXT_PROTOCOL
/* , PROVIDER_NAME */);
} catch (NoSuchAlgorithmException e) {
log.warn("Protocol {} not available, falling back to {}", SSL_CONTEXT_PROTOCOL,
SSL_CONTEXT_FALLBACK_PROTOCOL);
return SSLContext.getInstance(SSL_CONTEXT_FALLBACK_PROTOCOL
/* , PROVIDER_NAME */);
}
}
public static long initRandomSerial() {
final Random rnd = new Random();
rnd.setSeed(System.currentTimeMillis());
// prevent browser certificate caches, cause of doubled serial numbers
// using 48bit random number
long sl = ((long) rnd.nextInt()) << 32 | (rnd.nextInt() & 0xFFFFFFFFL);
// let reserve of 16 bit for increasing, serials have to be positive
sl = sl & 0x0000FFFFFFFFFFFFL;
return sl;
}
}
|
src/main/java/org/littleshoot/proxy/mitm/CertificateHelper.java
|
package org.littleshoot.proxy.mitm;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyManagementException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Random;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x500.X500NameBuilder;
import org.bouncycastle.asn1.x500.style.BCStyle;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.cert.CertIOException;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.bc.BcX509ExtensionUtils;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class CertificateHelper {
private static final Logger log = LoggerFactory.getLogger(CertificateHelper.class);
public static final String PROVIDER_NAME = BouncyCastleProvider.PROVIDER_NAME;
static {
Security.addProvider(new BouncyCastleProvider());
}
private static final String KEYGEN_ALGORITHM = "RSA";
private static final String SECURE_RANDOM_ALGORITHM = "SHA1PRNG";
private static final String SIGNATURE_ALGORITHM = "SHA1WithRSAEncryption";
private static final int ROOT_KEYSIZE = 2048;
private static final int FAKE_KEYSIZE = 1024;
/**
* Current time minus 1 year, just in case software clock goes back due to
* time synchronization
*/
private static final Date NOT_BEFORE = new Date(
System.currentTimeMillis() - 86400000L * 365);
/**
* The maximum possible value in X.509 specification: 9999-12-31 23:59:59,
* new Date(253402300799000L), but Apple iOS 8 fails with a certificate
* expiration date grater than Mon, 24 Jan 6084 02:07:59 GMT (issue #6).
*
* Hundred years in the future from starting the proxy should be enough.
*/
private static final Date NOT_AFTER = new Date(
System.currentTimeMillis() + 86400000L * 365 * 100);
/**
* Enforce TLS 1.2 if available, since it's not default up to Java 8.
* <p>
* Java 7 disables TLS 1.1 and 1.2 for clients. From <a href=
* "http://docs.oracle.com/javase/7/docs/technotes/guides/security/SunProviders.html"
* >Java Cryptography Architecture Oracle Providers Documentation:</a>
* Although SunJSSE in the Java SE 7 release supports TLS 1.1 and TLS 1.2,
* neither version is enabled by default for client connections. Some
* servers do not implement forward compatibility correctly and refuse to
* talk to TLS 1.1 or TLS 1.2 clients. For interoperability, SunJSSE does
* not enable TLS 1.1 or TLS 1.2 by default for client connections.
*/
private static final String SSL_CONTEXT_PROTOCOL = "TLSv1.2";
/**
* {@link SSLContext}: Every implementation of the Java platform is required
* to support the following standard SSLContext protocol: TLSv1
*/
private static final String SSL_CONTEXT_FALLBACK_PROTOCOL = "TLSv1";
public static KeyPair generateKeyPair(int keySize)
throws NoSuchAlgorithmException, NoSuchProviderException {
KeyPairGenerator generator = KeyPairGenerator
.getInstance(KEYGEN_ALGORITHM/* , PROVIDER_NAME */);
SecureRandom secureRandom = SecureRandom
.getInstance(SECURE_RANDOM_ALGORITHM/* , PROVIDER_NAME */);
generator.initialize(keySize, secureRandom);
return generator.generateKeyPair();
}
public static KeyStore createRootCertificate(Authority authority,
String keyStoreType) throws NoSuchAlgorithmException,
NoSuchProviderException, CertIOException, IOException,
OperatorCreationException, CertificateException, KeyStoreException {
KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE);
X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
nameBuilder.addRDN(BCStyle.CN, authority.commonName());
nameBuilder.addRDN(BCStyle.O, authority.organization());
nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName());
X500Name issuer = nameBuilder.build();
BigInteger serial = BigInteger.valueOf(initRandomSerial());
X500Name subject = issuer;
PublicKey pubKey = keyPair.getPublic();
X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(
issuer, serial, NOT_BEFORE, NOT_AFTER, subject, pubKey);
generator.addExtension(Extension.subjectKeyIdentifier, false,
createSubjectKeyIdentifier(pubKey));
generator.addExtension(Extension.basicConstraints, true,
new BasicConstraints(true));
KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign
| KeyUsage.digitalSignature | KeyUsage.keyEncipherment
| KeyUsage.dataEncipherment | KeyUsage.cRLSign);
generator.addExtension(Extension.keyUsage, false, usage);
ASN1EncodableVector purposes = new ASN1EncodableVector();
purposes.add(KeyPurposeId.id_kp_serverAuth);
purposes.add(KeyPurposeId.id_kp_clientAuth);
purposes.add(KeyPurposeId.anyExtendedKeyUsage);
generator.addExtension(Extension.extendedKeyUsage, false,
new DERSequence(purposes));
X509Certificate cert = signCertificate(generator, keyPair.getPrivate());
KeyStore result = KeyStore
.getInstance(keyStoreType/* , PROVIDER_NAME */);
result.load(null, null);
result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
authority.password(), new Certificate[] { cert });
return result;
}
private static SubjectKeyIdentifier createSubjectKeyIdentifier(Key key)
throws IOException {
ByteArrayInputStream bIn = new ByteArrayInputStream(key.getEncoded());
ASN1InputStream is = null;
try {
is = new ASN1InputStream(bIn);
ASN1Sequence seq = (ASN1Sequence) is.readObject();
SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(seq);
return new BcX509ExtensionUtils().createSubjectKeyIdentifier(info);
} finally {
IOUtils.closeQuietly(is);
}
}
public static KeyStore createServerCertificate(String commonName,
SubjectAlternativeNameHolder subjectAlternativeNames,
Authority authority, Certificate caCert, PrivateKey caPrivKey)
throws NoSuchAlgorithmException, NoSuchProviderException,
IOException, OperatorCreationException, CertificateException,
InvalidKeyException, SignatureException, KeyStoreException {
KeyPair keyPair = generateKeyPair(FAKE_KEYSIZE);
X500Name issuer = new X509CertificateHolder(caCert.getEncoded())
.getSubject();
BigInteger serial = BigInteger.valueOf(initRandomSerial());
X500NameBuilder name = new X500NameBuilder(BCStyle.INSTANCE);
name.addRDN(BCStyle.CN, commonName);
name.addRDN(BCStyle.O, authority.certOrganisation());
name.addRDN(BCStyle.OU, authority.certOrganizationalUnitName());
X500Name subject = name.build();
X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
issuer, serial, NOT_BEFORE, NOT_AFTER, subject,
keyPair.getPublic());
builder.addExtension(Extension.subjectKeyIdentifier, false,
createSubjectKeyIdentifier(keyPair.getPublic()));
builder.addExtension(Extension.basicConstraints, false,
new BasicConstraints(false));
subjectAlternativeNames.fillInto(builder);
X509Certificate cert = signCertificate(builder, caPrivKey);
cert.checkValidity(new Date());
cert.verify(caCert.getPublicKey());
KeyStore result = KeyStore.getInstance(KeyStore.getDefaultType()
/* , PROVIDER_NAME */);
result.load(null, null);
Certificate[] chain = { cert, caCert };
result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
authority.password(), chain);
return result;
}
private static X509Certificate signCertificate(
X509v3CertificateBuilder certificateBuilder,
PrivateKey signedWithPrivateKey) throws OperatorCreationException,
CertificateException {
ContentSigner signer = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM)
.setProvider(PROVIDER_NAME).build(signedWithPrivateKey);
X509Certificate cert = new JcaX509CertificateConverter().setProvider(
PROVIDER_NAME).getCertificate(certificateBuilder.build(signer));
return cert;
}
public static TrustManager[] getTrustManagers(KeyStore keyStore)
throws KeyStoreException, NoSuchAlgorithmException,
NoSuchProviderException {
String trustManAlg = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManAlg
/* , PROVIDER_NAME */);
tmf.init(keyStore);
return tmf.getTrustManagers();
}
public static KeyManager[] getKeyManagers(KeyStore keyStore,
Authority authority) throws NoSuchAlgorithmException,
NoSuchProviderException, UnrecoverableKeyException,
KeyStoreException {
String keyManAlg = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManAlg
/* , PROVIDER_NAME */);
kmf.init(keyStore, authority.password());
return kmf.getKeyManagers();
}
public static SSLContext newClientContext(KeyManager[] keyManagers,
TrustManager[] trustManagers) throws NoSuchAlgorithmException,
KeyManagementException, NoSuchProviderException {
SSLContext result = newSSLContext();
result.init(keyManagers, trustManagers, null);
return result;
}
public static SSLContext newServerContext(KeyManager[] keyManagers)
throws NoSuchAlgorithmException, NoSuchProviderException,
KeyManagementException {
SSLContext result = newSSLContext();
SecureRandom random = new SecureRandom();
random.setSeed(System.currentTimeMillis());
result.init(keyManagers, null, random);
return result;
}
private static SSLContext newSSLContext() throws NoSuchAlgorithmException {
try {
log.debug("Using protocol {}", SSL_CONTEXT_PROTOCOL);
return SSLContext.getInstance(SSL_CONTEXT_PROTOCOL
/* , PROVIDER_NAME */);
} catch (NoSuchAlgorithmException e) {
log.warn("Protocol {} not available, falling back to {}", SSL_CONTEXT_PROTOCOL,
SSL_CONTEXT_FALLBACK_PROTOCOL);
return SSLContext.getInstance(SSL_CONTEXT_FALLBACK_PROTOCOL
/* , PROVIDER_NAME */);
}
}
public static long initRandomSerial() {
final Random rnd = new Random();
rnd.setSeed(System.currentTimeMillis());
// prevent browser certificate caches, cause of doubled serial numbers
// using 48bit random number
long sl = ((long) rnd.nextInt()) << 32 | (rnd.nextInt() & 0xFFFFFFFFL);
// let reserve of 16 bit for increasing, serials have to be positive
sl = sl & 0x0000FFFFFFFFFFFFL;
return sl;
}
}
|
Replace SHA1 message digest to make Google Chrome happy.
|
src/main/java/org/littleshoot/proxy/mitm/CertificateHelper.java
|
Replace SHA1 message digest to make Google Chrome happy.
|
|
Java
|
apache-2.0
|
07845d26351290e2c67732ea92235ec7421cbb14
| 0
|
jnidzwetzki/scalephant,jnidzwetzki/bboxdb,jnidzwetzki/scalephant,jnidzwetzki/bboxdb,jnidzwetzki/bboxdb
|
/*******************************************************************************
*
* Copyright (C) 2015-2018 the BBoxDB 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 org.bboxdb;
import java.io.Closeable;
import java.io.IOException;
import java.util.function.Consumer;
import org.bboxdb.commons.CloseableHelper;
import org.junit.Test;
import org.mockito.Mockito;
public class TestCloseableHelper {
@Test
public void testCloseAutocloseable() throws Exception {
@SuppressWarnings("unchecked")
final Consumer<Exception> consumer = Mockito.mock(Consumer.class);
final AutoCloseable autoCloseable = Mockito.mock(AutoCloseable.class);
final IOException ioException = new IOException();
CloseableHelper.closeWithoutException(autoCloseable);
(Mockito.verify(autoCloseable, Mockito.times(1))).close();
CloseableHelper.closeWithoutException(null);
CloseableHelper.closeWithoutException(autoCloseable, consumer);
(Mockito.verify(autoCloseable, Mockito.times(2))).close();
(Mockito.verify(consumer, Mockito.times(0))).accept(ioException);
Mockito.doThrow(ioException).when(autoCloseable).close();
CloseableHelper.closeWithoutException(autoCloseable, consumer);
(Mockito.verify(autoCloseable, Mockito.times(3))).close();
(Mockito.verify(consumer, Mockito.times(1))).accept(ioException);
}
@Test
public void testCloseCloseable() throws IOException {
@SuppressWarnings("unchecked")
final Consumer<Exception> consumer = Mockito.mock(Consumer.class);
final Closeable coseable = Mockito.mock(Closeable.class);
final IOException ioException = new IOException();
CloseableHelper.closeWithoutException(coseable);
(Mockito.verify(coseable, Mockito.times(1))).close();
CloseableHelper.closeWithoutException(null);
CloseableHelper.closeWithoutException(coseable, consumer);
(Mockito.verify(coseable, Mockito.times(2))).close();
(Mockito.verify(consumer, Mockito.times(0))).accept(ioException);
Mockito.doThrow(ioException).when(coseable).close();
CloseableHelper.closeWithoutException(coseable, consumer);
(Mockito.verify(coseable, Mockito.times(3))).close();
(Mockito.verify(consumer, Mockito.times(1))).accept(ioException);
}
}
|
bboxdb-commons/src/test/java/org/bboxdb/TestCloseableHelper.java
|
/*******************************************************************************
*
* Copyright (C) 2015-2018 the BBoxDB 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 org.bboxdb;
import java.io.Closeable;
import java.io.IOException;
import java.util.function.Consumer;
import org.bboxdb.commons.CloseableHelper;
import org.junit.Test;
import org.mockito.Mockito;
public class TestCloseableHelper {
@Test
public void testCloseAutocloseable() throws Exception {
@SuppressWarnings("unchecked")
final Consumer<Exception> consumer = Mockito.mock(Consumer.class);
final AutoCloseable autoCloseable = Mockito.mock(AutoCloseable.class);
final IOException ioException = new IOException();
CloseableHelper.closeWithoutException(autoCloseable);
(Mockito.verify(autoCloseable, Mockito.times(1))).close();
CloseableHelper.closeWithoutException(autoCloseable, consumer);
(Mockito.verify(autoCloseable, Mockito.times(2))).close();
(Mockito.verify(consumer, Mockito.times(0))).accept(ioException);
Mockito.doThrow(ioException).when(autoCloseable).close();
CloseableHelper.closeWithoutException(autoCloseable, consumer);
(Mockito.verify(autoCloseable, Mockito.times(3))).close();
(Mockito.verify(consumer, Mockito.times(1))).accept(ioException);
}
@Test
public void testCloseCloseable() throws IOException {
@SuppressWarnings("unchecked")
final Consumer<Exception> consumer = Mockito.mock(Consumer.class);
final Closeable coseable = Mockito.mock(Closeable.class);
final IOException ioException = new IOException();
CloseableHelper.closeWithoutException(coseable);
(Mockito.verify(coseable, Mockito.times(1))).close();
CloseableHelper.closeWithoutException(coseable, consumer);
(Mockito.verify(coseable, Mockito.times(2))).close();
(Mockito.verify(consumer, Mockito.times(0))).accept(ioException);
Mockito.doThrow(ioException).when(coseable).close();
CloseableHelper.closeWithoutException(coseable, consumer);
(Mockito.verify(coseable, Mockito.times(3))).close();
(Mockito.verify(consumer, Mockito.times(1))).accept(ioException);
}
}
|
Added null test
|
bboxdb-commons/src/test/java/org/bboxdb/TestCloseableHelper.java
|
Added null test
|
|
Java
|
bsd-3-clause
|
3f4f6b4ad226c82e0241b8cc8392daf4c3327f84
| 0
|
mccraigmccraig/prefuse,mccraigmccraig/prefuse
|
package edu.berkeley.guir.prefuse.util;
import java.awt.Color;
import java.awt.Paint;
import edu.berkeley.guir.prefuse.action.ColorFunction;
/**
* A color map that maps numeric values to colors for visualizing
* a spectrum of values.
*
* @version 1.0
* @author <a href="http://jheer.org">Jeffrey Heer</a> prefuse(AT)jheer.org
*/
public class ColorMap {
/**
* The default length of a color map array if its size
* is not otherwise specified.
*/
public static final int DEFAULT_MAP_SIZE = 64;
private Paint colorMap[];
private double minValue, maxValue;
/**
* Creates a new ColorMap instance using the given internal color map
* array and minimum and maximum index values.
* @param map a Paint array constituing the color map
* @param min the minimum value in the color map
* @param max the maximum value in the color map
*/
public ColorMap(Paint[] map, double min, double max) {
colorMap = map;
minValue = min;
maxValue = max;
} //
/**
* Returns the color associated with the given value. If the value
* is outside the range defined by this map's minimum or maximum
* values, a saturated value is returned (i.e. the first entry
* in the color map for values below the minimum, the last enty
* for value above the maximum).
* @param val the value for which to retrieve the corresponding color
* @return
*/
public Paint getColor(double val) {
if ( val < minValue ) {
return colorMap[0];
} else if ( val > maxValue ) {
return colorMap[colorMap.length-1];
} else {
int idx = (int)Math.round((colorMap.length-1) *
(val-minValue)/(maxValue-minValue));
return colorMap[idx];
}
} //
/**
* Sets the internal color map, an array of Paint values.
* @return Returns the colormap.
*/
public Paint[] getColorMap() {
return colorMap;
} //
/**
* Sets the internal color map, an array of Paint values.
* @param colorMap The new colormap.
*/
public void setColorMap(Paint[] colorMap) {
this.colorMap = colorMap;
} //
/**
* Gets the maximum value that corresponds to the last
* color in the color map.
* @return Returns the max index value into the colormap.
*/
public double getMaxValue() {
return maxValue;
} //
/**
* Sets the maximum value that corresponds to the last
* color in the color map.
* @param maxValue The max index value to set.
*/
public void setMaxValue(double maxValue) {
this.maxValue = maxValue;
} //
/**
* Sets the minimum value that corresponds to the first
* color in the color map.
* @return Returns the min index value.
*/
public double getMinValue() {
return minValue;
} //
/**
* Gets the minimum value that corresponds to the first
* color in the color map.
* @param minValue The min index value to set.
*/
public void setMinValue(double minValue) {
this.minValue = minValue;
} //
/**
* Returns a color map array of default size that ranges from black to
* white through shades of gray.
* @return the color map array
*/
public static Paint[] getGrayscaleMap() {
return getGrayscaleMap(DEFAULT_MAP_SIZE);
} //
/**
* /**
* Returns a color map array of specified size that ranges from black to
* white through shades of gray.
* @param size the size of the color map array
* @return the color map array
*/
public static Paint[] getGrayscaleMap(int size) {
Paint[] cm = new Paint[size];
for ( int i=0; i<size; i++ ) {
float g = ((float)i)/(size-1);
cm[i] = new Color(g,g,g);
}
return cm;
} //
/**
* Returns a color map array of default size that ranges from one
* given color to the other.
* @param c1 the initial color in the color map
* @param c2 the final color in the color map
* @return the color map array
*/
public static Paint[] getInterpolatedMap(Color c1, Color c2) {
return getInterpolatedMap(DEFAULT_MAP_SIZE, c1, c2);
} //
/**
* Returns a color map array of given size that ranges from one
* given color to the other.
* @param size the size of the color map array
* @param c1 the initial color in the color map
* @param c2 the final color in the color map
* @return the color map array
*/
public static Paint[] getInterpolatedMap(int size, Color c1, Color c2) {
Paint[] cm = new Paint[size];
for ( int i=0; i<size; i++ ) {
float f = ((float)i)/(size-1);
cm[i] = ColorFunction.calcIntermediateColor(c1,c2,f);
}
return cm;
} //
/**
* Returns a color map array of default size that cycles through
* the hues of the HSB (Hue/Saturation/Brightness) color space at
* full saturation and brightness.
* @return the color map array
*/
public static Paint[] getHSBMap() {
return getHSBMap(DEFAULT_MAP_SIZE, 1.f, 1.f);
} //
/**
* Returns a color map array of given size that cycles through
* the hues of the HSB (Hue/Saturation/Brightness) color space.
* @param size the size of the color map array
* @param s the saturation value to use
* @param b the brightness value to use
* @return the color map array
*/
public static Paint[] getHSBMap(int size, float s, float b) {
Paint[] cm = new Paint[size];
for ( int i=0; i<size; i++ ) {
float h = ((float)i)/(size-1);
cm[i] = new Color(Color.HSBtoRGB(h,s,b));
}
return cm;
} //
/**
* Returns a color map of default size that moves from black to
* red to yellow to white.
* @return the color map array
*/
public static Paint[] getHotMap() {
return getHotMap(DEFAULT_MAP_SIZE);
} //
/**
* Returns a color map that moves from black to red to yellow
* to white.
* @param size the size of the color map array
* @return the color map array
*/
public static Paint[] getHotMap(int size) {
Paint[] cm = new Paint[size];
for ( int i=0; i<size; i++ ) {
int n = (3*size)/8;
float r = ( i<n ? ((float)(i+1))/n : 1.f );
float g = ( i<n ? 0.f : ( i<2*n ? ((float)(i-n))/n : 1.f ));
float b = ( i<2*n ? 0.f : ((float)(i-2*n))/(size-2*n) );
cm[i] = new Color(r,g,b);
}
return cm;
} //
/**
* Returns a color map array of default size that uses a "cool",
* blue-heavy color scheme.
* @return the color map array
*/
public static Paint[] getCoolMap() {
return getCoolMap(DEFAULT_MAP_SIZE);
} //
/**
* Returns a color map array that uses a "cool",
* blue-heavy color scheme.
* @param size the size of the color map array
* @return the color map array
*/
public static Paint[] getCoolMap(int size) {
Paint[] cm = new Paint[size];
for( int i=0; i<size; i++ ) {
float r = ((float)i) / Math.max(size-1,1.f);
cm[i] = new Color(r,1-r,1.f);
}
return cm;
} //
} // end of class ColorMap
|
src/edu/berkeley/guir/prefuse/util/ColorMap.java
|
package edu.berkeley.guir.prefuse.util;
import java.awt.Color;
import java.awt.Paint;
import edu.berkeley.guir.prefuse.action.ColorFunction;
/**
* A color map that maps numeric values to colors for visualizing
* a spectrum of values.
*
* @version 1.0
* @author <a href="http://jheer.org">Jeffrey Heer</a> prefuse(AT)jheer.org
*/
public class ColorMap {
/**
* The default length of a color map array if its size
* is not otherwise specified.
*/
public static final int DEFAULT_MAP_SIZE = 64;
private Paint colorMap[];
private double minValue, maxValue;
/**
* Creates a new ColorMap instance using the given internal color map
* array and minimum and maximum index values.
* @param map a Paint array constituing the color map
* @param min the minimum value in the color map
* @param max the maximum value in the color map
*/
public ColorMap(Paint[] map, double min, double max) {
colorMap = map;
minValue = min;
maxValue = max;
} //
/**
* Returns the color associated with the given value. If the value
* is outside the range defined by this map's minimum or maximum
* values, a saturated value is returned (i.e. the first entry
* in the color map for values below the minimum, the last enty
* for value above the maximum).
* @param val the value for which to retrieve the corresponding color
* @return
*/
public Paint getColor(double val) {
if ( val < minValue ) {
return colorMap[0];
} else if ( val > maxValue ) {
return colorMap[colorMap.length-1];
} else {
int idx = (int)Math.round((colorMap.length-1) *
(val-minValue)/(maxValue-minValue));
return colorMap[idx];
}
} //
/**
* Sets the internal color map, an array of Paint values.
* @return Returns the colormap.
*/
public Paint[] getColorMap() {
return colorMap;
} //
/**
* Sets the internal color map, an array of Paint values.
* @param colorMap The new colormap.
*/
public void setColorMap(Paint[] colorMap) {
this.colorMap = colorMap;
} //
/**
* Gets the maximum value that corresponds to the last
* color in the color map.
* @return Returns the max index value into the colormap.
*/
public double getMaxValue() {
return maxValue;
} //
/**
* Sets the maximum value that corresponds to the last
* color in the color map.
* @param maxValue The max index value to set.
*/
public void setMaxValue(double maxValue) {
this.maxValue = maxValue;
} //
/**
* Sets the minimum value that corresponds to the first
* color in the color map.
* @return Returns the min index value.
*/
public double getMinValue() {
return minValue;
} //
/**
* Gets the minimum value that corresponds to the first
* color in the color map.
* @param minValue The min index value to set.
*/
public void setMinValue(double minValue) {
this.minValue = minValue;
} //
/**
* Returns a color map array of default size that ranges from black to
* white through shades of gray.
* @return the color map array
*/
public static Paint[] getGrayscaleMap() {
return getGrayscaleMap(DEFAULT_MAP_SIZE);
} //
/**
* /**
* Returns a color map array of specified size that ranges from black to
* white through shades of gray.
* @param size the size of the color map array
* @return the color map array
*/
public static Paint[] getGrayscaleMap(int size) {
Paint[] cm = new Paint[size];
for ( int i=0; i<size; i++ ) {
float g = ((float)i)/(size-1);
cm[i] = new Color(g,g,g);
}
return cm;
} //
/**
* Returns a color map array of default size that ranges from one
* given color to the other.
* @param c1 the initial color in the color map
* @param c2 the final color in the color map
* @return the color map array
*/
public static Paint[] getInterpolatedMap(Color c1, Color c2) {
return getInterpolatedMap(DEFAULT_MAP_SIZE, c1, c2);
} //
/**
* Returns a color map array of given size that ranges from one
* given color to the other.
* @param size the size of the color map array
* @param c1 the initial color in the color map
* @param c2 the final color in the color map
* @return the color map array
*/
public static Paint[] getInterpolatedMap(int size, Color c1, Color c2) {
Paint[] cm = new Paint[size];
for ( int i=0; i<size; i++ ) {
float f = ((float)i)/(size-1);
cm[i] = ColorFunction.calcIntermediateColor(c1,c2,f);
}
return cm;
} //
/**
* Returns a color map array of default size that cycles through
* the hues of the HSB color space at full saturation and brightness.
* @return the color map array
*/
public static Paint[] getHSBMap() {
return getHSBMap(DEFAULT_MAP_SIZE, 1.f, 1.f);
} //
/**
* Returns a color map array of given size that cycles through
* the hues of the HSB color space.
* @param size the size of the color map array
* @param s the saturation value to use
* @param b the brightness value to use
* @return the color map array
*/
public static Paint[] getHSBMap(int size, float s, float b) {
Paint[] cm = new Paint[size];
for ( int i=0; i<size; i++ ) {
float h = ((float)i)/(size-1);
cm[i] = new Color(Color.HSBtoRGB(h,s,b));
}
return cm;
} //
} // end of class ColorMap
|
Added hot and cool to ColorMap
|
src/edu/berkeley/guir/prefuse/util/ColorMap.java
|
Added hot and cool to ColorMap
|
|
Java
|
mit
|
e588110a4331df51495ac0efe1553e24625ed44a
| 0
|
JosuaKrause/Bubble-Sets
|
src/setvis/shape/QuadShapeGenerator.java
|
/**
*
*/
package setvis.shape;
import static setvis.VecUtil.addVec;
import static setvis.VecUtil.getOrthoLeft;
import static setvis.VecUtil.getOrthoRight;
import static setvis.VecUtil.invVec;
import static setvis.VecUtil.middleVec;
import static setvis.VecUtil.mulVec;
import static setvis.VecUtil.normVec;
import static setvis.VecUtil.subVec;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import setvis.SetOutline;
/**
* Generates a quadratic interpolated {@link Shape} for the vertices generated
* by {@link SetOutline#createOutline(Rectangle2D[], Rectangle2D[])}.
*
* @author Joschi <josua.krause@googlemail.com>
*
*/
public class QuadShapeGenerator extends RoundShapeGenerator {
/**
* Creates an {@link QuadShapeGenerator} with a given set outline creator.
*
* @param outline
* The creator of the set outlines.
* @param clockwise
* Whether the result of the set outlines are interpreted in
* clockwise order.
*/
public QuadShapeGenerator(final SetOutline outline, final boolean clockwise) {
super(outline, clockwise);
}
@Override
protected Shape convertToShape(final Point2D[] points) {
final GeneralPath res = new GeneralPath();
final int len = points.length;
Point2D first = null;
final Point2D[] buff = new Point2D[2];
for (int i = 0; i < len; ++i) {
for (final Point2D p : getOrthos(points, i, getRadius())) {
if (first == null) {
first = p;
res.moveTo(p.getX(), p.getY());
continue;
}
feedPoint(res, buff, p);
}
}
feedPoint(res, buff, first);
// close the line, if the buffer is not empty
if (buff[0] != null) {
feedPoint(res, buff, buff[0]);
}
return res;
}
/**
* Adds a point to the buffer and flushes the buffer when it is full, by
* drawing a quadratic interpolated curve.
*
* @param path
* The path drawer.
* @param buff
* The buffer of size 2.
* @param p
* The new point.
*/
private void feedPoint(final GeneralPath path, final Point2D[] buff,
final Point2D p) {
if (buff[0] == null) {
buff[0] = p;
return;
}
buff[1] = p;
if (buff[1] == null) {
return;
}
path.quadTo(buff[0].getX(), buff[0].getY(), buff[1].getX(), buff[1]
.getY());
buff[0] = null;
buff[1] = null;
}
private Point2D[] getOrthos(final Point2D[] points, final int index,
final double distance) {
final int len = points.length;
switch (len) {
case 1:
return singleOrthos(points[index], distance);
case 2:
return doubleOrthos(points[index], points[getOtherIndex(index, len,
false)], distance);
default:
return defaultOrthos(points, index, distance);
}
}
private Point2D[] singleOrthos(final Point2D p, final double d) {
final Point2D x = new Point2D.Double(d, 0.0);
final Point2D y = new Point2D.Double(0.0, d);
final Point2D r = addVec(p, x);
final Point2D t = addVec(p, y);
final Point2D l = addVec(p, invVec(x));
final Point2D b = addVec(p, invVec(y));
return new Point2D[] { l, middleVec(p, l, t, d), t,
middleVec(p, t, r, d), r, middleVec(p, r, b, d), b,
middleVec(p, b, l, d) };
}
private Point2D[] doubleOrthos(final Point2D p, final Point2D other,
final double d) {
final Point2D same = mulVec(normVec(subVec(p, other)), d);
final Point2D left = getOrthoLeft(same);
final Point2D right = getOrthoRight(same);
final Point2D l = addVec(p, left);
final Point2D m = addVec(p, same);
final Point2D r = addVec(p, right);
return new Point2D[] { l, middleVec(p, l, m, d), m,
middleVec(p, m, r, d), r };
}
private Point2D[] defaultOrthos(final Point2D[] points, final int index,
final double distance) {
final int len = points.length;
final Point2D point = points[index];
final Point2D left = points[getOtherIndex(index, len, false)];
final Point2D right = points[getOtherIndex(index, len, true)];
final Point2D lp = subVec(left, point);
final Point2D pr = subVec(right, point);
final Point2D ol = getOrthoRight(lp);
final Point2D or = getOrthoLeft(pr);
final Point2D nol = mulVec(normVec(ol), distance);
final Point2D nor = mulVec(normVec(or), distance);
final Point2D first = addVec(nor, point);
final Point2D second = addVec(nol, point);
final Point2D mid = middleVec(point, first, second, distance);
return new Point2D[] { first, mid, second };
}
}
|
removed quad shape generator
git-svn-id: ded14da315768278bb53c6e950099ad70da4adad@14 ddcbcb1e-7873-aa44-b559-865c2020aa11
|
src/setvis/shape/QuadShapeGenerator.java
|
removed quad shape generator
|
||
Java
|
mit
|
a90cede4b6530315730747888252a7c2352436a2
| 0
|
FAU-Inf2/yasme-android
|
package net.yasme.android.ui;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import net.yasme.android.R;
import net.yasme.android.entities.Chat;
import net.yasme.android.entities.Message;
import net.yasme.android.entities.User;
import net.yasme.android.storage.DatabaseManager;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;
/**
* Created by martin on 18.06.2014.
*/
public class ChatListAdapter extends ArrayAdapter<Chat> {
Context context;
int layoutResourceId;
List<Chat> chats = null;
private final static int CHATPARTNER_VISIBLE_CNT = 10;
public ChatListAdapter(Context context, int layoutResourceId, List<Chat> chats) {
super(context, layoutResourceId, chats);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.chats = chats;
}
@Override
public void notifyDataSetChanged() {
Collections.sort(chats, new Comparator<Object>() {
@Override
public int compare(Object o, Object o2) {
Chat c1 = (Chat) o;
Chat c2 = (Chat) o2;
return c1.getLastModified().compareTo(c2.getLastModified());
}
});
super.notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ChatListViewHolder holder;
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
if (convertView == null) {
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ChatListViewHolder();
holder.titleView = (TextView)row.findViewById(R.id.chatlist_item_title);
holder.subtitleView = (TextView)row.findViewById(R.id.chatlist_item_subtitle);
holder.lastMessageView = (TextView)row.findViewById(R.id.chatlist_item_last_message);
holder.chatpartnerList = (LinearLayout) row.findViewById(R.id.chatpartner);
holder.moreUsers = (TextView) row.findViewById(R.id.chatlist_more_users);
row.setTag(holder);
} else {
holder = (ChatListViewHolder) convertView.getTag();
}
holder.lastMessageView.setVisibility(View.GONE);
Chat chat = chats.get(position);
holder.titleView.setText(chat.getName());
holder.subtitleView.setText(chat.getStatus());
Message lastMessage = DatabaseManager.INSTANCE.getMessageDAO().
getNewestMessageOfChat(chat.getId());
if(!lastMessage.getMessage().isEmpty()) {
holder.lastMessageView.setText(lastMessage.getSender().getName()
+ ": " + lastMessage.getMessage());
holder.lastMessageView.setVisibility(View.VISIBLE);
}
holder.chatpartnerList.removeAllViews(); // TODO: also recycle these
ArrayList<User> users = chat.getParticipants();
for (int i = 0; i < users.size() && i < CHATPARTNER_VISIBLE_CNT; i++) {
// TODO: skip self
View chatpartner = inflater.inflate(R.layout.chatpartner_item, null);
ImageView img = (ImageView) chatpartner.findViewById(R.id.chatpartner_picture);
img.setImageResource(R.drawable.chatlist_default_icon);
img.setBackgroundColor(ChatAdapter.CONTACT_DUMMY_COLORS_ARGB[(int)users.get(i).getId() % ChatAdapter.CONTACT_DUMMY_COLORS_ARGB.length]);
TextView text = (TextView) chatpartner.findViewById(R.id.chatpartner_picture_text);
text.setText(users.get(i).getName().substring(0,1));
holder.chatpartnerList.addView(chatpartner);
}
if (users.size() > CHATPARTNER_VISIBLE_CNT) {
holder.moreUsers.setText("and " + (users.size() - CHATPARTNER_VISIBLE_CNT) + " more...");
} else {
holder.moreUsers.setVisibility(View.GONE);
}
return row;
}
public void updateChats(List<Chat> updatedChats) {
// This:
// chats = updatedChats;
// does not work. No update at runtime!
chats.clear();
for (int i=0; i < updatedChats.size(); i++) {
chats.add(updatedChats.get(i));
}
Log.d(this.getClass().getSimpleName(), "Chats updated: " + this.chats.size());
}
static class ChatListViewHolder {
TextView titleView, subtitleView, lastMessageView, moreUsers;
LinearLayout chatpartnerList;
}
}
|
yasme/src/main/java/net/yasme/android/ui/ChatListAdapter.java
|
package net.yasme.android.ui;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import net.yasme.android.R;
import net.yasme.android.entities.Chat;
import net.yasme.android.entities.Message;
import net.yasme.android.entities.User;
import net.yasme.android.storage.DatabaseManager;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;
/**
* Created by martin on 18.06.2014.
*/
public class ChatListAdapter extends ArrayAdapter<Chat> {
Context context;
int layoutResourceId;
List<Chat> chats = null;
private final static int CHATPARTNER_VISIBLE_CNT = 10;
public ChatListAdapter(Context context, int layoutResourceId, List<Chat> chats) {
super(context, layoutResourceId, chats);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.chats = chats;
}
@Override
public void notifyDataSetChanged() {
Collections.sort(chats, new Comparator<Object>() {
@Override
public int compare(Object o, Object o2) {
Chat c1 = (Chat) o;
Chat c2 = (Chat) o2;
return c1.getLastModified().compareTo(c2.getLastModified());
}
});
super.notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
//ChatHolder holder = null;
/*
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ChatHolder();
holder.iconView = (ImageView)row.findViewById(R.id.chatlist_item_icon);
holder.titleView = (TextView)row.findViewById(R.id.chatlist_item_title);
holder.subtitleView = (TextView)row.findViewById(R.id.chatlist_item_subtitle);
row.setTag(holder);
}
else
{
holder = (ChatHolder)row.getTag();
}
Chat chat = chats.get(position);
holder.titleView.setText(chat.getName());
holder.subtitleView.setText(chat.getNumberOfParticipants() + " Teilnehmer");
holder.iconView.setImageResource(R.drawable.ic_action_cc_bcc);
*/
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
TextView titleView = (TextView)row.findViewById(R.id.chatlist_item_title);
TextView subtitleView = (TextView)row.findViewById(R.id.chatlist_item_subtitle);
TextView lastMessageView = (TextView)row.findViewById(R.id.chatlist_item_last_message);
lastMessageView.setVisibility(View.GONE);
Chat chat = chats.get(position);
titleView.setText(chat.getName());
subtitleView.setText(chat.getStatus());
Message lastMessage = DatabaseManager.INSTANCE.getMessageDAO().
getNewestMessageOfChat(chat.getId());
if(!lastMessage.getMessage().isEmpty()) {
lastMessageView.setText(lastMessage.getSender().getName()
+ ": " + lastMessage.getMessage());
lastMessageView.setVisibility(View.VISIBLE);
}
LinearLayout chatpartnerList = (LinearLayout) row.findViewById(R.id.chatpartner);
ArrayList<User> users = chat.getParticipants();
for (int i = 0; i < users.size() && i < CHATPARTNER_VISIBLE_CNT; i++) {
// TODO: skip self
View chatpartner = inflater.inflate(R.layout.chatpartner_item, null);
ImageView img = (ImageView) chatpartner.findViewById(R.id.chatpartner_picture);
img.setImageResource(R.drawable.chatlist_default_icon);
img.setBackgroundColor(ChatAdapter.CONTACT_DUMMY_COLORS_ARGB[(int)users.get(i).getId() % ChatAdapter.CONTACT_DUMMY_COLORS_ARGB.length]);
TextView text = (TextView) chatpartner.findViewById(R.id.chatpartner_picture_text);
text.setText(users.get(i).getName().substring(0,1));
chatpartnerList.addView(chatpartner);
}
TextView moreUsers = (TextView) row.findViewById(R.id.chatlist_more_users);
if (users.size() > CHATPARTNER_VISIBLE_CNT) {
moreUsers.setText("and " + (users.size() - CHATPARTNER_VISIBLE_CNT) + " more...");
} else {
moreUsers.setVisibility(View.GONE);
}
row.setTag(chat.getId());
return row;
}
/*
static class ChatHolder
{
ImageView iconView;
TextView titleView;
TextView subtitleView;
}
*/
public void updateChats(List<Chat> updatedChats) {
// This:
// chats = updatedChats;
// does not work. No update at runtime!
chats.clear();
for (int i=0; i < updatedChats.size(); i++) {
chats.add(updatedChats.get(i));
}
Log.d(this.getClass().getSimpleName(), "Chats updated: " + this.chats.size());
}
}
|
Use view holder pattern to remove lag while scrolling in chat list.
|
yasme/src/main/java/net/yasme/android/ui/ChatListAdapter.java
|
Use view holder pattern to remove lag while scrolling in chat list.
|
|
Java
|
mit
|
c4c4cbb1ab350d89d12926306b9d5e6bd4674885
| 0
|
AleZonta/tgcfs
|
package tgcfs.EA;
import lgds.trajectories.Point;
import org.datavec.image.loader.NativeImageLoader;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.indexing.INDArrayIndex;
import org.nd4j.linalg.indexing.NDArrayIndex;
import tgcfs.Agents.InputNetwork;
import tgcfs.Agents.Models.Clax;
import tgcfs.Agents.Models.ConvAgent;
import tgcfs.Agents.Models.LSTMAgent;
import tgcfs.Agents.OutputNetwork;
import tgcfs.Config.ReadConfig;
import tgcfs.Idsa.IdsaLoader;
import tgcfs.InputOutput.FollowingTheGraph;
import tgcfs.InputOutput.Transformation;
import tgcfs.Loader.TrainReal;
import tgcfs.NN.EvolvableModel;
import tgcfs.NN.InputsNetwork;
import tgcfs.NN.OutputsNetwork;
import tgcfs.Networks.Convolutionary;
import tgcfs.Performances.SaveToFile;
import tgcfs.Utils.MultyScores;
import tgcfs.Utils.PointWithBearing;
import tgcfs.Utils.Scores;
import java.io.File;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by Alessandro Zonta on 29/05/2017.
* PhD Situational Analytics
* <p>
* Computational Intelligence Group
* Computer Science Department
* Faculty of Sciences - VU University Amsterdam
* <p>
* a.zonta@vu.nl
*
* Class implementing the algorithm for the agents.
*/
public class Agents extends Algorithm {
private MultyScores scores;
/**
* Constructor zero parameter
* Call the super constructor
* @param logger logger
* @throws Exception if the super constructor has problem in reading the config files
*/
public Agents(Logger logger) throws Exception {
super(logger);
this.scores = new MultyScores();
}
/**
* Generate the population for the EA
* set the max fitness achievable by an agent
* @param model the model of the population
* @throws Exception exception
*/
@Override
public void generatePopulation(EvolvableModel model) throws Exception {
super.generatePopulation(model);
if(ReadConfig.Configurations.getHallOfFame()){
this.maxFitnessAchievable = (ReadConfig.Configurations.getClassifierPopulationSize() + ReadConfig.Configurations.getClassifierOffspringSize() + ReadConfig.Configurations.getHallOfFameSample()) * ReadConfig.Configurations.getTrajectoriesTrained();
}else{
this.maxFitnessAchievable = (ReadConfig.Configurations.getClassifierPopulationSize() + ReadConfig.Configurations.getClassifierOffspringSize()) * ReadConfig.Configurations.getTrajectoriesTrained();
}
SaveToFile.Saver.saveMaxFitnessAchievable(this.maxFitnessAchievable, this.getClass().getName());
}
/**
* Generate the population for the EA
* set the max fitness achievable by an agent
* using the information loaded from file
* @param model the model of the population
* @param populationLoaded the popolation loaded from file
* @throws Exception exception
*/
@Override
public void generatePopulation(EvolvableModel model, List<INDArray> populationLoaded) throws Exception {
super.generatePopulation(model,populationLoaded);
this.maxFitnessAchievable = (ReadConfig.Configurations.getClassifierPopulationSize() + ReadConfig.Configurations.getClassifierOffspringSize()) * ReadConfig.Configurations.getTrajectoriesTrained();
SaveToFile.Saver.saveMaxFitnessAchievable(this.maxFitnessAchievable, this.getClass().getName());
}
/**
* @implNote Implementation from Abstract class Algorithm
* @param input the input of the model
* @throws Exception if there are problems in reading the info
*/
@Override
public void runIndividuals(List<TrainReal> input) throws Exception {
//reset input
for(Individual ind: super.getPopulationWithHallOfFame()){
ind.resetInputOutput();
}
/**
* Class for multithreading
* Run one agent against all the classifiers
*/
class ComputeUnit implements Runnable {
private CountDownLatch latch;
private Individual agent;
/**
* Constructor
* @param agent agent
*/
private ComputeUnit(Individual agent) {
this.agent = agent;
}
/**
* CountDownLatch is a java class in the java.util.concurrent package. It is a mechanism to safely handle
* counting the number of completed tasks. You should call latch.countDown() whenever the run method competes.
* @param latch {@link CountDownLatch}
*/
private void setLatch(CountDownLatch latch) {
this.latch = latch;
}
/**
* Run the agent
*/
@Override
public void run() {
try {
//retrieve model from the individual
EvolvableModel model = this.agent.getModel();
//set the weights
model.setWeights(this.agent.getObjectiveParameters());
//select which model I am using
if(model.getClass().equals(LSTMAgent.class)){
this.runLSTM(input, model, this.agent);
}else {
throw new Exception("Not yet Implemented");
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Errors with the neural network " + e.getMessage());
e.printStackTrace();
}
latch.countDown();
}
/**
* Run the LSTM agent
* @param input the input of the model
* @param model the model LSTM used
* @param individual the individual under evaluation
*/
private void runLSTM(List<TrainReal> input, EvolvableModel model, Individual individual) {
//compute Output of the network
INDArray lastOutput = null;
int number;
try{
number = ReadConfig.Configurations.getAgentTimeSteps();
}catch (Exception e){
number = 1;
}
for (TrainReal inputsNetwork : input) {
TrainReal currentInputsNetwork = inputsNetwork.deepCopy();
//now for the number of time step that I want to check save the output
List<OutputsNetwork> outputsNetworks = new ArrayList<>();
List<InputsNetwork> in = currentInputsNetwork.getTrainingPoint();
int size = in.size();
int inputSize = InputNetwork.inputSize;
INDArray features = Nd4j.create(new int[]{1, inputSize, size}, 'f');
for (int j = 0; j < size; j++) {
INDArray vector = in.get(j).serialise();
features.put(new INDArrayIndex[]{NDArrayIndex.point(0), NDArrayIndex.all(), NDArrayIndex.point(j)}, vector);
}
if(ReadConfig.debug) logger.log(Level.INFO, "Input LSTM ->" + features.toString());
lastOutput = model.computeOutput(features);
int timeSeriesLength = lastOutput.size(2); //Size of time dimension
INDArray realLastOut = lastOutput.get(NDArrayIndex.point(0), NDArrayIndex.all(), NDArrayIndex.point(timeSeriesLength-1));
if(ReadConfig.debug) logger.log(Level.INFO, "Output LSTM ->" + realLastOut.toString());
this.addOutput(realLastOut, outputsNetworks);
logger.log(Level.INFO, inputsNetwork.getId() + " Output LSTM transformed ->" + outputsNetworks.toString());
//output has only two fields, input needs three
//I am using the last direction present into input I am adding that one to the last output
Double directionAPF = ((InputNetwork) currentInputsNetwork.getTrainingPoint().get(currentInputsNetwork.getTrainingPoint().size() - 1)).getDirectionAPF();
for (int i = 0; i < number - 1; i++) {
//transform output into input and add the direction
OutputNetwork outLocal = new OutputNetwork();
outLocal.deserialise(lastOutput);
InputNetwork inputLocal = new InputNetwork(directionAPF, outLocal.getSpeed(), outLocal.getBearing(), currentInputsNetwork.getLastTime());
lastOutput = model.computeOutput(inputLocal.serialise());
if(ReadConfig.debug) logger.log(Level.INFO, "Output LSTM ->" + lastOutput.toString());
this.addOutput(realLastOut, outputsNetworks);
}
//assign the output to this individual
currentInputsNetwork.setOutputComputed(outputsNetworks);
individual.addMyInputandOutput(currentInputsNetwork.deepCopy());
((LSTMAgent)model).clearPreviousState();
}
}
/**
* if I am considerind the time I need to de-serialise the output considering also the time, otherwise not
* @param realLastOut output generator
* @param outputsNetworks collection of outputs
*/
private void addOutput(INDArray realLastOut, List<OutputsNetwork> outputsNetworks){
// if(!this.time){
OutputNetwork out = new OutputNetwork();
out.deserialise(realLastOut);
outputsNetworks.add(out);
// }else{
// OutputNetworkTime out = new OutputNetworkTime();
// out.deserialise(realLastOut);
// outputsNetworks.add(out);
// }
}
}
ExecutorService exec = Executors.newFixedThreadPool(16);
CountDownLatch latch = new CountDownLatch(super.getPopulationWithHallOfFame().size());
ComputeUnit[] runnables = new ComputeUnit[super.getPopulationWithHallOfFame().size()];
for(int i = 0; i < super.getPopulationWithHallOfFame().size(); i ++){
runnables[i] = new ComputeUnit(super.getPopulationWithHallOfFame().get(i));
}
for(ComputeUnit r : runnables) {
r.setLatch(latch);
exec.execute(r);
}
try {
latch.await();
exec.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
// for(Individual agent: super.getPopulationWithHallOfFame()){
// //retrieve model from the individual
// EvolvableModel model = agent.getModel();
// //set the weights
// model.setWeights(agent.getObjectiveParameters());
// //select which model I am using
// if (model.getClass().equals(LSTMAgent.class)) {
// this.runLSTM(input, model, agent);
// } else {
// throw new Exception("Not yet Implemented");
// }
// }
}
/**
* run the convolutional model
* @param input the input of the model
* @param model the model Convolutional used
* @param individual the individual under evaluation
* @throws Exception if something bad happened
*/
private void runConvol(List<TrainReal> input, EvolvableModel model, Individual individual) throws Exception {
NativeImageLoader imageLoader = new NativeImageLoader();
INDArray lastOutput = null;
INDArray conditionalInputConverted = null;
IdsaLoader refLoader = input.get(0).getIdsaLoader();
for (TrainReal inputsNetwork : input) {
//need to genereta a picture for every timestep of the trajectory
List<Point> growingTrajectory = new ArrayList<>();
for(Point p : inputsNetwork.getPoints()){
growingTrajectory.add(p);
Boolean res = inputsNetwork.getIdsaLoader().generatePicture(growingTrajectory);
if(!res) throw new Exception("Creation of the pictures did not work out");
//erase image
//((ConvAgent)model).erasePictureCreated(Paths.get(inputsNetwork.getNormalImage()));
//if the conversion worked correctly I know where the actual picture is stored
File realInput = new File(inputsNetwork.getNormalImage());
INDArray realInputConverted = imageLoader.asMatrix(realInput);
//since it is always the same lets compute it only the first time
if(conditionalInputConverted == null) {
File conditionalInput = new File(inputsNetwork.getConditionalImage());
conditionalInputConverted = imageLoader.asMatrix(conditionalInput);
((Convolutionary)model).setConditionalPicture(conditionalInputConverted);
}
//compute output
lastOutput = model.computeOutput(realInputConverted);
//now for the number of time step that I want to check save the output
List<OutputsNetwork> outputsNetworks = new ArrayList<>();
OutputNetwork out = new OutputNetwork();
out.deserialise(lastOutput);
outputsNetworks.add(out);
//need this to transform the the value into point
FollowingTheGraph transformation = new FollowingTheGraph();
//I need to set the feeder
transformation.setFeeder(((ConvAgent)model).getFeeder());
//and the last point
transformation.setLastPoint(new PointWithBearing(growingTrajectory.get(growingTrajectory.size() - 1)));
for (int i = 0; i < ReadConfig.Configurations.getAgentTimeSteps(); i++) {
//transform output into input and add the direction
OutputNetwork outLocal = new OutputNetwork();
outLocal.deserialise(lastOutput);
//TODO if using convolutionary I need to enable the following lines
//Point toAdd = transformation.singlePointConversion(outLocal);
// transformation.setLastPoint(new PointWithBearing(toAdd));
// growingTrajectory.add(toAdd);
res = inputsNetwork.getIdsaLoader().generatePicture(growingTrajectory);
if(!res) throw new Exception("Creation of the pictures did not work out");
//erase image
//((ConvAgent)model).erasePictureCreated(Paths.get(inputsNetwork.getNormalImage()));
realInput = new File(inputsNetwork.getNormalImage());
realInputConverted = imageLoader.asMatrix(realInput);
//compute output
lastOutput = model.computeOutput(realInputConverted);
out = new OutputNetwork();
out.deserialise(lastOutput);
outputsNetworks.add(out);
}
//assign the output to this individual
inputsNetwork.setOutputComputed(outputsNetworks);
individual.addMyInputandOutput(inputsNetwork);
}
}
}
/**
* run the Clax model
* @param input the input of the model
* @param model the model Clax used
* @param individual the individual under evaluation
* @throws Exception if something bad happened
*/
private void runClax(List<TrainReal> input, EvolvableModel model, Individual individual) throws Exception {
//with clax is slightly different
Clax m = (Clax) model; //cast to clax for the proprietary method
//I have more training input in the list
for (TrainReal inputsNetwork : input) {
m.setStart(inputsNetwork.getLastPoint());
m.setTarget(((InputNetwork)inputsNetwork.getTrainingPoint().get(inputsNetwork.getTrainingPoint().size())).getTargetPoint());
//need to compute the trajectory
List<INDArray> out = m.computeTrajectory();
//now for the number of time step that I want to check save the output
List<OutputsNetwork> outputsNetworks = new ArrayList<>();
out.forEach(o -> {
OutputNetwork outClax = new OutputNetwork();
outClax.deserialise(o);
outputsNetworks.add(outClax);
});
//assign the output to this individual
inputsNetwork.setOutputComputed(outputsNetworks);
individual.addMyInputandOutput(inputsNetwork);
}
}
/**
* Run the LSTM agent
* @param input the input of the model
* @param model the model LSTM used
* @param individual the individual under evaluation
* @throws Exception if something bad happened
*/
private void runLSTM(List<TrainReal> input, EvolvableModel model, Individual individual) throws Exception {
//compute Output of the network
INDArray lastOutput = null;
int number;
try{
number = ReadConfig.Configurations.getAgentTimeSteps();
}catch (Exception e){
number = 1;
}
for (TrainReal inputsNetwork : input) {
TrainReal currentInputsNetwork = inputsNetwork.deepCopy();
//now for the number of time step that I want to check save the output
List<OutputsNetwork> outputsNetworks = new ArrayList<>();
List<InputsNetwork> in = currentInputsNetwork.getTrainingPoint();
int size = in.size();
INDArray features = Nd4j.create(new int[]{1, InputNetwork.inputSize, size}, 'f');
for (int j = 0; j < size; j++) {
INDArray vector = in.get(j).serialise();
features.put(new INDArrayIndex[]{NDArrayIndex.point(0), NDArrayIndex.all(), NDArrayIndex.point(j)}, vector);
}
lastOutput = model.computeOutput(features);
int timeSeriesLength = lastOutput.size(2); //Size of time dimension
INDArray realLastOut = lastOutput.get(NDArrayIndex.point(0), NDArrayIndex.all(), NDArrayIndex.point(timeSeriesLength-1));
if(ReadConfig.debug) logger.log(Level.INFO, "Output LSTM ->" + realLastOut.toString());
OutputNetwork out = new OutputNetwork();
out.deserialise(realLastOut);
outputsNetworks.add(out);
logger.log(Level.INFO, "Output LSTM transformed ->" + outputsNetworks.toString());
//output has only two fields, input needs three
//I am using the last direction present into input I am adding that one to the last output
Double directionAPF = ((InputNetwork) currentInputsNetwork.getTrainingPoint().get(currentInputsNetwork.getTrainingPoint().size() - 1)).getDirectionAPF();
for (int i = 0; i < number - 1; i++) {
//transform output into input and add the direction
OutputNetwork outLocal = new OutputNetwork();
outLocal.deserialise(lastOutput);
InputNetwork inputLocal = new InputNetwork(directionAPF, outLocal.getSpeed(), outLocal.getBearing(), currentInputsNetwork.getLastTime());
lastOutput = model.computeOutput(inputLocal.serialise());
if(ReadConfig.debug) logger.log(Level.INFO, "Output LSTM ->" + lastOutput.toString());
out = new OutputNetwork();
out.deserialise(lastOutput);
outputsNetworks.add(out);
}
//assign the output to this individual
currentInputsNetwork.setOutputComputed(outputsNetworks);
//create the output already computed
individual.addMyInputandOutput(currentInputsNetwork);
((LSTMAgent)model).clearPreviousState();
}
}
/**
* @implNote Implementation from Abstract class Algorithm
* @param individual individual with the parameter of the classifier
* @param input input to assign to the classifier
* @return the output of the classifier
* @throws Exception if the nn has problem an exception is raised
*/
public OutputsNetwork runIndividual(Individual individual, List<InputsNetwork> input) throws Exception {
throw new Exception("Method not usable for a Agent");
}
/**
* @implNote Implementation from Abstract class Algorithm
* Method to evaluate the agent using the classifiers
* The fitness of each model is obtained by evaluating it with each of the classifiers in the competing population
* For every classifier that wrongly judges the model as being the real agent, the model’s fitness increases by one.
*
* At the same time I can evaluate the classifier
* The fitness of each classifier is obtained by using it to evaluate each model in the competing population
* For each correct judgement, the classifier’s fitness increases by one
*
* It is evaluating the false trajectory and also the real one
*
* @param competingPopulation competing population
* @param transformation the class that will transform from one output to the new input
*/
public void evaluateIndividuals(Algorithm competingPopulation, Transformation transformation){
/**
* Class for multithreading
* Run one agent against all the classifiers
* Compute the fitness function in this way:
* Now if the classifier (ENN) is returning the value x (>=0.5 -> true) as output, the fitness is computed in this way:
* - agent fitness is x, classifier is (1-x)
* In the other case, output x (<0.5 -> false), the fitness is:
* - classifier is x, agent is (1-x)
*/
class ComputeUnit implements Runnable {
private CountDownLatch latch;
private Individual agent;
private List<Individual> adersarialPopulation;
private MultyScores scores;
private boolean score;
/**
* Constructor
* @param agent current agent
* @param adersarialPopulation adversarial population
* @param score do I want the score
* @param scores where to save the score
*/
private ComputeUnit(Individual agent, List<Individual> adersarialPopulation, boolean score, MultyScores scores) {
this.agent = agent;
this.adersarialPopulation = adersarialPopulation;
this.scores = scores;
this.score = score;
}
/**
* CountDownLatch is a java class in the java.util.concurrent package. It is a mechanism to safely handle
* counting the number of completed tasks. You should call latch.countDown() whenever the run method competes.
* @param latch {@link CountDownLatch}
*/
private void setLatch(CountDownLatch latch) {
this.latch = latch;
}
/**
* Override method run
* run the classifier over the agent
*/
@Override
public void run() {
List<TrainReal> inputOutput = agent.getMyInputandOutput();
for(Individual opponent: this.adersarialPopulation){
for(TrainReal example: inputOutput){
//run the classifier for the Fake trajectory
try {
this.runClassifier(competingPopulation ,agent, opponent, example, true);
} catch (Exception e) {
logger.log(Level.SEVERE, "Error Classifier Fake Input" + e.getMessage());
e.printStackTrace();
}
//run the classifier for the Real trajectory
try {
this.runClassifier(competingPopulation ,agent, opponent, example, false);
} catch (Exception e) {
logger.log(Level.SEVERE, "Error Classifier Real Input" + e.getMessage());
e.printStackTrace();
}
}
}
latch.countDown();
}
/**
* Run the classifier
* @param model model of the classifier
* @param agent agent individual
* @param classifier agent classifier
* @param totalInput TrainReal
* @param real Boolean value. If it is false I do not need to increment the agent fitness since I am checking the real trajectory
*/
private synchronized void runClassifier(Algorithm model, Individual agent, Individual classifier, TrainReal totalInput, boolean real) throws Exception {
List<InputsNetwork> input;
if(real){
input = totalInput.getAllThePartTransformedFake();
}else{
input = totalInput.getAllThePartTransformedReal();
}
tgcfs.Classifiers.OutputNetwork result = (tgcfs.Classifiers.OutputNetwork) model.runIndividual(classifier, input);
if (ReadConfig.debug) logger.log(Level.INFO, "Output network ->" + result.toString() + " realValue -> " + result.getRealValue() + " -->" + real);
double decision = result.getRealValue();
if( decision > 0.5 ) {
//it is saying it is true
//counting this only if the fake trajectory
if(real) {
agent.increaseFitness(decision);
classifier.increaseFitness(1 - decision);
if (this.score) {
Scores sc = new Scores(agent.getModel().getId(),totalInput.getId(), classifier.getModel().getId(), decision);
this.scores.addScore(sc);
}
}
}else{
//it is false
classifier.increaseFitness(decision);
if(real) {
agent.increaseFitness(1 - decision);
if (this.score) {
Scores sc = new Scores(agent.getModel().getId(), totalInput.getId(), classifier.getModel().getId(), decision);
this.scores.addScore(sc);
}
}
}
}
}
/**
* Class for multithreading
* Run one agent against all the classifiers
* Compute the fitness function in this way:
*
* R = #real
* T_jk = (sum_i( classifier_j(agent_i)))k <- in this module
* Y_ijk = (R * classifier_j(agent_i) / T_j)k
* E_ijk = ({ i = real : 1 - Y_ij, i = fake: Y_ij })k
*
* FitnessAgent = sum_k sum_j( E_ijk )
* FitnessClassifier = sum_k sum_i( 1 - E_ijk)
*
*
*
*
*
*
*/
class ComputeSelmarFitnessUnit implements Runnable{
private CountDownLatch latch;
private Individual classifier;
private List<Individual> adersarialPopulation;
private Map<Integer, Map<UUID, Double>> Tik;
private Map<Integer, UUID> toForget;
/**
* Constructor
* @param classifier current classifier
* @param adersarialPopulation adversarial population
*/
private ComputeSelmarFitnessUnit(Individual classifier, List<Individual> adersarialPopulation) {
this.classifier = classifier;
this.adersarialPopulation = adersarialPopulation;
this.Tik = new HashMap<>();
this.toForget = new HashMap<>();
}
/**
* CountDownLatch is a java class in the java.util.concurrent package. It is a mechanism to safely handle
* counting the number of completed tasks. You should call latch.countDown() whenever the run method competes.
* @param latch {@link CountDownLatch}
*/
private void setLatch(CountDownLatch latch) {
this.latch = latch;
}
/**
* Getter for the classifier's model ID
* @return int id
*/
private int getClassifierID(){
return this.classifier.getModel().getId();
}
/**
* Getting to forget elements
* @return Map<Integer, UUID>> containing id agent and id trajectory
*/
private Map<Integer, UUID> getToForget(){
return this.toForget;
}
/**
* Getter for the results from the classification
* @return Map<Integer, Map<UUID, Double>> containing id agent and his classification
*/
private Map<Integer, Map<UUID, Double>> getResults(){
return this.Tik;
}
/**
* Override method run
* run the classifier over the agent
*
* classifierResultAgentI = classifier_j(agent_i)
* classifierResultAgentI = agent_i classification using classifier j
*/
@Override
public void run() {
for(Individual agent: this.adersarialPopulation){
List<TrainReal> inputOutput = agent.getMyInputandOutput();
// //agent id is always the same for all the trajectories
// int agentId = agent.getModel().getId();
//
// // trajectory result
// Map<UUID, Double> Tj = new HashMap<>();
//
// for(TrainReal example: inputOutput) {
// //run the classifier for the Fake trajectory
// try {
// tgcfs.Classifiers.OutputNetwork result = (tgcfs.Classifiers.OutputNetwork) competingPopulation.runIndividual(classifier, example.getAllThePartTransformedFake());
// if (ReadConfig.debug) logger.log(Level.INFO, "Fake Output network ->" + result.toString() + " realValue -> " + result.getRealValue());
// //save all the results
// Tj.put(example.getId(), result.getRealValue());
// } catch (Exception e) {
// logger.log(Level.SEVERE, "Error Classifier Fake Input" + e.getMessage());
// e.printStackTrace();
// }
// }
// //update the main result with the agent id
// this.Tik.put(agentId, Tj);
//
// //also this one is going to be always the same. Lets use only the first real one
// int realAgentId = inputOutput.get(0).getIdRealPoint().getId();
// // trajectory result
// Map<UUID, Double> T2j = new HashMap<>();
//
// for(TrainReal example: inputOutput){
// //run the classifier for the Real trajectory
// try {
// tgcfs.Classifiers.OutputNetwork resultReal = (tgcfs.Classifiers.OutputNetwork) competingPopulation.runIndividual(classifier, example.getAllThePartTransformedReal());
// if (ReadConfig.debug) logger.log(Level.INFO, "Real Output network ->" + resultReal.toString() + " realValue -> " + resultReal.getRealValue());
// //save all the results
// T2j.put(example.getId(), resultReal.getRealValue());
//
// } catch (Exception e) {
// logger.log(Level.SEVERE, "Error Classifier Real Input" + e.getMessage());
// e.printStackTrace();
// }
// }
// //update the main result with the agent id
// this.Tik.put(realAgentId, T2j);
//agent id is always the same for all the trajectories
int agentId = agent.getModel().getId();
//also this one is going to be always the same. Lets use only the first real one
int realAgentId = inputOutput.get(0).getIdRealPoint().getId();
// trajectory result
Map<UUID, Double> Tj = new HashMap<>();
// trajectory result
Map<UUID, Double> T2j = new HashMap<>();
for(TrainReal example: inputOutput) {
//run the classifier for the Fake trajectory
tgcfs.Classifiers.OutputNetwork result = null;
try {
result = (tgcfs.Classifiers.OutputNetwork) competingPopulation.runIndividual(classifier, example.getAllThePartTransformedFake());
if (ReadConfig.debug)
logger.log(Level.INFO, "Fake Output network ->" + result.toString() + " realValue -> " + result.getRealValue());
//save all the results
} catch (Exception e) {
logger.log(Level.SEVERE, "Error Classifier Fake Input" + e.getMessage());
e.printStackTrace();
}
tgcfs.Classifiers.OutputNetwork resultReal = null;
//run the classifier for the Real trajectory
try {
resultReal = (tgcfs.Classifiers.OutputNetwork) competingPopulation.runIndividual(classifier, example.getAllThePartTransformedReal());
if (ReadConfig.debug) logger.log(Level.INFO, "Real Output network ->" + resultReal.toString() + " realValue -> " + resultReal.getRealValue());
//save all the results
} catch (Exception e) {
logger.log(Level.SEVERE, "Error Classifier Real Input" + e.getMessage());
e.printStackTrace();
}
Tj.put(example.getId(), result.getRealValue());
T2j.put(example.getId(), resultReal.getRealValue());
//fake point classified fake | real point classified real = okay
//fake point classified fake | real point classified fake = 0
//fake point classified real | real point classified real = okay
//fake point classified real | real point classified fake = 0
if((result.getRealValue() <= 0.5 && resultReal.getRealValue() > 0.5) || (result.getRealValue() > 0.5 && resultReal.getRealValue() > 0.5)){
//ok
}else{
//save the ids
this.toForget.put(agentId, example.getId());
this.toForget.put(realAgentId, example.getId());
}
}
//update the main result with the agent id
this.Tik.put(agentId, Tj);
//update the main result with the agent id
this.Tik.put(realAgentId, T2j);
}
latch.countDown();
}
}
//Need this with both fitness functions
List<Integer> realAgentsId = new ArrayList<>();
//transform the outputs into the input for the classifiers
for(Individual ind : super.getPopulationWithHallOfFame()){
//transform trajectory in advance to prevent multiprocessing errors
List<TrainReal> inputOutput = ind.getMyInputandOutput();
for(TrainReal trainReal: inputOutput){
((FollowingTheGraph)transformation).setLastPoint(trainReal.getLastPoint());
transformation.transform(trainReal);
realAgentsId.add(trainReal.getIdRealPoint().getId());
}
}
logger.log(Level.SEVERE, "Start real classification");
//set the default fitness as the normal fitness
int fitnessTypology = 0;
try {
fitnessTypology = ReadConfig.Configurations.getFitnessFunction();
} catch (Exception ignored) { }
switch (fitnessTypology){
case 0:
// original fitness function implemented
boolean score = false;
try {
score = ReadConfig.Configurations.getScore();
} catch (Exception ignored) { }
//launch my way to compute the fitness
ExecutorService execOriginal = Executors.newFixedThreadPool(16);
CountDownLatch latchOriginal = new CountDownLatch(super.getPopulationWithHallOfFame().size());
ComputeUnit[] runnablesOriginal = new ComputeUnit[super.getPopulationWithHallOfFame().size()];
for(int i = 0; i < super.getPopulationWithHallOfFame().size(); i ++){
runnablesOriginal[i] = new ComputeUnit(super.getPopulationWithHallOfFame().get(i), competingPopulation.getPopulationWithHallOfFame(), score, this.scores);
}
for(ComputeUnit r : runnablesOriginal) {
r.setLatch(latchOriginal);
execOriginal.execute(r);
}
try {
latchOriginal.await();
execOriginal.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
case 1:
// selmar fitness function
// number real trajectories = total number of trajectories said as real = # trajectories trained * # individuals
int R = super.getPopulationWithHallOfFame().size();
//classifier id, agent id, trajectory id, result
HashMap<Integer, Map<Integer, Map<UUID, Double>>> results = new HashMap<>();
//id to not use in fitness
HashMap<Integer, Map<Integer, UUID>> toAvoid = new HashMap<>();
//launch the threads for the computations
ExecutorService exec = Executors.newFixedThreadPool(96);
CountDownLatch latch = new CountDownLatch(competingPopulation.getPopulationWithHallOfFame().size());
ComputeSelmarFitnessUnit[] runnables = new ComputeSelmarFitnessUnit[competingPopulation.getPopulationWithHallOfFame().size()];
//create all the runnables
for(int i = 0; i < competingPopulation.getPopulationWithHallOfFame().size(); i ++){
runnables[i] = new ComputeSelmarFitnessUnit(competingPopulation.getPopulationWithHallOfFame().get(i), super.getPopulationWithHallOfFame());
}
//execute them and wait them till they have finished
for(ComputeSelmarFitnessUnit r : runnables) {
r.setLatch(latch);
exec.execute(r);
}
try {
latch.await();
exec.shutdown();
//collecting the results
for (ComputeSelmarFitnessUnit runnable : runnables) {
//all the i, j fixed -> classifier_j(agent_i))
results.put(runnable.getClassifierID(), runnable.getResults());
toAvoid.put(runnable.getClassifierID(), runnable.getToForget());
}
//find list of trajectories id
Map<Integer, Map<UUID, Double>> a = results.get(results.keySet().toArray()[0]);
Map<UUID, Double> b = a.get(a.keySet().toArray()[0]);
List<UUID> trajectoriesID = new ArrayList<>(b.keySet());
//creation all the Tjk
//T_j_k = (sum_i( classifier_j(agent_i)))_k
//trajectory ID, classifier ID, sum Tjk
HashMap<UUID, HashMap<Integer, Double>> Tjk = new HashMap<>();
//classifier id, agent id, trajectory id, result
for(UUID traID: trajectoriesID){
HashMap<Integer, Double> Tj = new HashMap<>();
for(int classifierID: results.keySet()){
//classifierID is the classifier id -> i
Map<Integer, Map<UUID, Double>> classifierResults = results.get(classifierID);
double classifierTotal = 0.0;
for(Integer agentId: classifierResults.keySet()){
Map<UUID, Double> traMap = classifierResults.get(agentId);
classifierTotal += traMap.get(traID);
}
Tj.put(classifierID, classifierTotal);
}
Tjk.put(traID, Tj);
}
//Creation matrix Yij
//Y_jik = (R * classifier_j(agent_i) / T_j)k
//E_jik = ({ i = real : 1 - Y_ij, i = fake: Y_ij } ^ 2)k
HashMap<UUID, HashMap<Integer, HashMap<Integer, Double>>> Yijk = new HashMap<>();
HashMap<UUID, HashMap<Integer, HashMap<Integer, Double>>> Eijk = new HashMap<>();
for(UUID traID: trajectoriesID){
HashMap<Integer, HashMap<Integer, Double>> Yij = new HashMap<>();
HashMap<Integer, HashMap<Integer, Double>> Eij = new HashMap<>();
for(int classifierID: results.keySet()){
//classifierID is the classifier id -> i
Map<Integer, Map<UUID, Double>> classifierResults = results.get(classifierID);
//Creation id agent,classifier
HashMap<Integer, Double> subE = new HashMap<>();
//for debug, remove this hashmap, it is redundant
HashMap<Integer, Double> subY = new HashMap<>();
for(int agentId: classifierResults.keySet()){
Map<UUID, Double> traMap = classifierResults.get(agentId);
//now I have classifier j and looping over agent i
double singleValue = traMap.get(traID);
double y = R * singleValue / Tjk.get(traID).get(classifierID);
if(Double.isNaN(y)){
y = 0.0;
}
if(y > 1.0) y = 1.0;
if(y < 0.0) y = 0.0;
subY.put(agentId, y);
if(realAgentsId.stream().anyMatch(t -> t == agentId)){
//if point is a real point
// subE.put(agentId, Math.pow(1 - y, 2));
if(y > 0.5) {
//if point real point and it is classified as a real
subE.put(agentId, Math.pow(1 - y, 2));
}else {
//if point is a real point and it is classified as fake
subE.put(agentId, Math.pow(1 - y, 2));
}
// subE.put(agentId, Math.pow(1 - y, 2) * 100);
}else{
///if point is a generated point
subE.put(agentId, Math.pow(y, 2));
if(y > 0.5) {
//if point is a generated point and it is classified as real
subE.put(agentId, Math.pow(y, 2));
}else {
//if point is a generated point and it is classified as fake
subE.put(agentId, Math.pow(y, 2));
}
}
}
Eij.put(classifierID, subE);
//for debug, remove this hashmap, it is redundant
Yij.put(classifierID, subY);
}
Yijk.put(traID, Yij);
Eijk.put(traID, Eij);
}
//FitnessAgent = sum_k(sum_j( E_jik ))
for(Individual agent : super.getPopulationWithHallOfFame()){
int id = agent.getModel().getId();
double fitness = 0;
//need to find all the values with that id and with all the trajectories
for(UUID uuid: Eijk.keySet()){
HashMap<Integer, HashMap<Integer, Double>> Eij = Eijk.get(uuid);
//need to find all the values with that id
for(int classifierID: Eij.keySet()){
//find values to avoid
Map<Integer, UUID> toNotUse = toAvoid.get(classifierID);
if(!(toNotUse.containsKey(id) && toNotUse.get(id)==uuid)){
fitness += Eij.get(classifierID).get(id);
}
}
}
agent.setFitness(fitness);
//setting the fitness for the examples of this agent
for(TrainReal example: agent.getMyInputandOutput()){
example.setFitnessGivenByTheClassifier(fitness);
}
}
for(Individual classifier: competingPopulation.getPopulationWithHallOfFame()){
int id = classifier.getModel().getId();
//find values to avoid
Map<Integer, UUID> toNotUse = toAvoid.get(id);
double fitness = 0;
for(UUID uuid: Eijk.keySet()){
HashMap<Integer, HashMap<Integer, Double>> Eij = Eijk.get(uuid);
HashMap<Integer, Double> allTheI = Eij.get(id);
for(int agentId: allTheI.keySet()){
if(!(toNotUse.containsKey(agentId) && toNotUse.get(agentId)==uuid)){
fitness += (Math.abs(1 - allTheI.get(agentId)));
}
}
}
classifier.setFitness(fitness);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
default:
throw new Error("Fitness type not implemented");
}
}
/**
* Method to train the network with the input selected
* @param combineInputList where to find the input to train
*/
@Override
public void trainNetwork(List<TrainReal> combineInputList) {
//obtain list of inputs
try {
if(ReadConfig.Configurations.getTrain()) {
throw new Exception("How should i train a LSTM without bad examples???");
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Error " + e.getMessage());
}
}
/**
* Save in JSON format the trajectory and the generated part of it
* @param generationAgent number of generation for the agent population
* @param generationClassifier number of generation for the classifier population
* @throws Exception if something wrong happens in saving everything
*/
public void saveTrajectoriesAndPointGenerated(int generationAgent, int generationClassifier) throws Exception {
List<TrainReal> totalList = new ArrayList<>();
for(Individual ind: super.getPopulation()){
for(TrainReal train: ind.getMyInputandOutput()){
totalList.add(train.deepCopy());
}
}
SaveToFile.Saver.dumpTrajectoryAndGeneratedPart(totalList, generationAgent, generationClassifier);
}
/**
* Save in JSON format the trajectory and the generated part of it
* @param gen number of generation I am
* @throws Exception if something wrong happens in saving everything
*/
public void saveTrajectoriesAfterSelection(int gen) throws Exception {
List<TrainReal> totalList = new ArrayList<>();
for(Individual ind: super.getPopulation()){
for(TrainReal train: ind.getMyInputandOutput()){
totalList.add(train.deepCopy());
}
}
SaveToFile.Saver.dumpTrajectoryAndGeneratedPart(totalList, gen);
}
/**
* Save score of the battle
* @param generationAgent number of generation for the agent population
* @param generationClassifier number of generation for the classifier population
* @throws Exception if something wrong happens in saving everything
*/
public void saveScoresBattle(int generationAgent, int generationClassifier) throws Exception {
SaveToFile.Saver.saveScoresBattle(this.scores.getScore(), generationAgent, generationClassifier);
}
/**
* Reset scores
*/
public void resetScore(){
this.scores = new MultyScores();
}
/**
* Generate the real last point
* @param transformation {@link FollowingTheGraph} transformation reference to transform the output in real point //TODO generalise this
*/
public void generateRealPoints(FollowingTheGraph transformation) throws Exception {
for(Individual ind: super.getPopulation()) {
for (TrainReal train : ind.getMyInputandOutput()) {
if(train.getRealPointsOutputComputed() == null) {
List<PointWithBearing> generatedPoint = new ArrayList<>();
transformation.setLastPoint(train.getLastPoint());
for(OutputsNetwork outputsNetwork: train.getOutputComputed()){
generatedPoint.add(new PointWithBearing(transformation.singlePointConversion(outputsNetwork, train.getLastTime())));
}
train.setRealPointsOutputComputed(generatedPoint);
train.computeStatistic();
}
}
}
}
}
|
src/main/java/tgcfs/EA/Agents.java
|
package tgcfs.EA;
import lgds.trajectories.Point;
import org.datavec.image.loader.NativeImageLoader;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.indexing.INDArrayIndex;
import org.nd4j.linalg.indexing.NDArrayIndex;
import tgcfs.Agents.InputNetwork;
import tgcfs.Agents.Models.Clax;
import tgcfs.Agents.Models.ConvAgent;
import tgcfs.Agents.Models.LSTMAgent;
import tgcfs.Agents.OutputNetwork;
import tgcfs.Config.ReadConfig;
import tgcfs.Idsa.IdsaLoader;
import tgcfs.InputOutput.FollowingTheGraph;
import tgcfs.InputOutput.Transformation;
import tgcfs.Loader.TrainReal;
import tgcfs.NN.EvolvableModel;
import tgcfs.NN.InputsNetwork;
import tgcfs.NN.OutputsNetwork;
import tgcfs.Networks.Convolutionary;
import tgcfs.Performances.SaveToFile;
import tgcfs.Utils.MultyScores;
import tgcfs.Utils.PointWithBearing;
import tgcfs.Utils.Scores;
import java.io.File;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by Alessandro Zonta on 29/05/2017.
* PhD Situational Analytics
* <p>
* Computational Intelligence Group
* Computer Science Department
* Faculty of Sciences - VU University Amsterdam
* <p>
* a.zonta@vu.nl
*
* Class implementing the algorithm for the agents.
*/
public class Agents extends Algorithm {
private MultyScores scores;
/**
* Constructor zero parameter
* Call the super constructor
* @param logger logger
* @throws Exception if the super constructor has problem in reading the config files
*/
public Agents(Logger logger) throws Exception {
super(logger);
this.scores = new MultyScores();
}
/**
* Generate the population for the EA
* set the max fitness achievable by an agent
* @param model the model of the population
* @throws Exception exception
*/
@Override
public void generatePopulation(EvolvableModel model) throws Exception {
super.generatePopulation(model);
if(ReadConfig.Configurations.getHallOfFame()){
this.maxFitnessAchievable = (ReadConfig.Configurations.getClassifierPopulationSize() + ReadConfig.Configurations.getClassifierOffspringSize() + ReadConfig.Configurations.getHallOfFameSample()) * ReadConfig.Configurations.getTrajectoriesTrained();
}else{
this.maxFitnessAchievable = (ReadConfig.Configurations.getClassifierPopulationSize() + ReadConfig.Configurations.getClassifierOffspringSize()) * ReadConfig.Configurations.getTrajectoriesTrained();
}
SaveToFile.Saver.saveMaxFitnessAchievable(this.maxFitnessAchievable, this.getClass().getName());
}
/**
* Generate the population for the EA
* set the max fitness achievable by an agent
* using the information loaded from file
* @param model the model of the population
* @param populationLoaded the popolation loaded from file
* @throws Exception exception
*/
@Override
public void generatePopulation(EvolvableModel model, List<INDArray> populationLoaded) throws Exception {
super.generatePopulation(model,populationLoaded);
this.maxFitnessAchievable = (ReadConfig.Configurations.getClassifierPopulationSize() + ReadConfig.Configurations.getClassifierOffspringSize()) * ReadConfig.Configurations.getTrajectoriesTrained();
SaveToFile.Saver.saveMaxFitnessAchievable(this.maxFitnessAchievable, this.getClass().getName());
}
/**
* @implNote Implementation from Abstract class Algorithm
* @param input the input of the model
* @throws Exception if there are problems in reading the info
*/
@Override
public void runIndividuals(List<TrainReal> input) throws Exception {
//reset input
for(Individual ind: super.getPopulationWithHallOfFame()){
ind.resetInputOutput();
}
/**
* Class for multithreading
* Run one agent against all the classifiers
*/
class ComputeUnit implements Runnable {
private CountDownLatch latch;
private Individual agent;
/**
* Constructor
* @param agent agent
*/
private ComputeUnit(Individual agent) {
this.agent = agent;
}
/**
* CountDownLatch is a java class in the java.util.concurrent package. It is a mechanism to safely handle
* counting the number of completed tasks. You should call latch.countDown() whenever the run method competes.
* @param latch {@link CountDownLatch}
*/
private void setLatch(CountDownLatch latch) {
this.latch = latch;
}
/**
* Run the agent
*/
@Override
public void run() {
try {
//retrieve model from the individual
EvolvableModel model = this.agent.getModel();
//set the weights
model.setWeights(this.agent.getObjectiveParameters());
//select which model I am using
if(model.getClass().equals(LSTMAgent.class)){
this.runLSTM(input, model, this.agent);
}else {
throw new Exception("Not yet Implemented");
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Errors with the neural network " + e.getMessage());
e.printStackTrace();
}
latch.countDown();
}
/**
* Run the LSTM agent
* @param input the input of the model
* @param model the model LSTM used
* @param individual the individual under evaluation
*/
private void runLSTM(List<TrainReal> input, EvolvableModel model, Individual individual) {
//compute Output of the network
INDArray lastOutput = null;
int number;
try{
number = ReadConfig.Configurations.getAgentTimeSteps();
}catch (Exception e){
number = 1;
}
for (TrainReal inputsNetwork : input) {
TrainReal currentInputsNetwork = inputsNetwork.deepCopy();
//now for the number of time step that I want to check save the output
List<OutputsNetwork> outputsNetworks = new ArrayList<>();
List<InputsNetwork> in = currentInputsNetwork.getTrainingPoint();
int size = in.size();
int inputSize = InputNetwork.inputSize;
INDArray features = Nd4j.create(new int[]{1, inputSize, size}, 'f');
for (int j = 0; j < size; j++) {
INDArray vector = in.get(j).serialise();
features.put(new INDArrayIndex[]{NDArrayIndex.point(0), NDArrayIndex.all(), NDArrayIndex.point(j)}, vector);
}
if(ReadConfig.debug) logger.log(Level.INFO, "Input LSTM ->" + features.toString());
lastOutput = model.computeOutput(features);
int timeSeriesLength = lastOutput.size(2); //Size of time dimension
INDArray realLastOut = lastOutput.get(NDArrayIndex.point(0), NDArrayIndex.all(), NDArrayIndex.point(timeSeriesLength-1));
if(ReadConfig.debug) logger.log(Level.INFO, "Output LSTM ->" + realLastOut.toString());
this.addOutput(realLastOut, outputsNetworks);
logger.log(Level.INFO, inputsNetwork.getId() + " Output LSTM transformed ->" + outputsNetworks.toString());
//output has only two fields, input needs three
//I am using the last direction present into input I am adding that one to the last output
Double directionAPF = ((InputNetwork) currentInputsNetwork.getTrainingPoint().get(currentInputsNetwork.getTrainingPoint().size() - 1)).getDirectionAPF();
for (int i = 0; i < number - 1; i++) {
//transform output into input and add the direction
OutputNetwork outLocal = new OutputNetwork();
outLocal.deserialise(lastOutput);
InputNetwork inputLocal = new InputNetwork(directionAPF, outLocal.getSpeed(), outLocal.getBearing(), currentInputsNetwork.getLastTime());
lastOutput = model.computeOutput(inputLocal.serialise());
if(ReadConfig.debug) logger.log(Level.INFO, "Output LSTM ->" + lastOutput.toString());
this.addOutput(realLastOut, outputsNetworks);
}
//assign the output to this individual
currentInputsNetwork.setOutputComputed(outputsNetworks);
individual.addMyInputandOutput(currentInputsNetwork.deepCopy());
((LSTMAgent)model).clearPreviousState();
}
}
/**
* if I am considerind the time I need to de-serialise the output considering also the time, otherwise not
* @param realLastOut output generator
* @param outputsNetworks collection of outputs
*/
private void addOutput(INDArray realLastOut, List<OutputsNetwork> outputsNetworks){
// if(!this.time){
OutputNetwork out = new OutputNetwork();
out.deserialise(realLastOut);
outputsNetworks.add(out);
// }else{
// OutputNetworkTime out = new OutputNetworkTime();
// out.deserialise(realLastOut);
// outputsNetworks.add(out);
// }
}
}
ExecutorService exec = Executors.newFixedThreadPool(16);
CountDownLatch latch = new CountDownLatch(super.getPopulationWithHallOfFame().size());
ComputeUnit[] runnables = new ComputeUnit[super.getPopulationWithHallOfFame().size()];
for(int i = 0; i < super.getPopulationWithHallOfFame().size(); i ++){
runnables[i] = new ComputeUnit(super.getPopulationWithHallOfFame().get(i));
}
for(ComputeUnit r : runnables) {
r.setLatch(latch);
exec.execute(r);
}
try {
latch.await();
exec.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
// for(Individual agent: super.getPopulationWithHallOfFame()){
// //retrieve model from the individual
// EvolvableModel model = agent.getModel();
// //set the weights
// model.setWeights(agent.getObjectiveParameters());
// //select which model I am using
// if (model.getClass().equals(LSTMAgent.class)) {
// this.runLSTM(input, model, agent);
// } else {
// throw new Exception("Not yet Implemented");
// }
// }
}
/**
* run the convolutional model
* @param input the input of the model
* @param model the model Convolutional used
* @param individual the individual under evaluation
* @throws Exception if something bad happened
*/
private void runConvol(List<TrainReal> input, EvolvableModel model, Individual individual) throws Exception {
NativeImageLoader imageLoader = new NativeImageLoader();
INDArray lastOutput = null;
INDArray conditionalInputConverted = null;
IdsaLoader refLoader = input.get(0).getIdsaLoader();
for (TrainReal inputsNetwork : input) {
//need to genereta a picture for every timestep of the trajectory
List<Point> growingTrajectory = new ArrayList<>();
for(Point p : inputsNetwork.getPoints()){
growingTrajectory.add(p);
Boolean res = inputsNetwork.getIdsaLoader().generatePicture(growingTrajectory);
if(!res) throw new Exception("Creation of the pictures did not work out");
//erase image
//((ConvAgent)model).erasePictureCreated(Paths.get(inputsNetwork.getNormalImage()));
//if the conversion worked correctly I know where the actual picture is stored
File realInput = new File(inputsNetwork.getNormalImage());
INDArray realInputConverted = imageLoader.asMatrix(realInput);
//since it is always the same lets compute it only the first time
if(conditionalInputConverted == null) {
File conditionalInput = new File(inputsNetwork.getConditionalImage());
conditionalInputConverted = imageLoader.asMatrix(conditionalInput);
((Convolutionary)model).setConditionalPicture(conditionalInputConverted);
}
//compute output
lastOutput = model.computeOutput(realInputConverted);
//now for the number of time step that I want to check save the output
List<OutputsNetwork> outputsNetworks = new ArrayList<>();
OutputNetwork out = new OutputNetwork();
out.deserialise(lastOutput);
outputsNetworks.add(out);
//need this to transform the the value into point
FollowingTheGraph transformation = new FollowingTheGraph();
//I need to set the feeder
transformation.setFeeder(((ConvAgent)model).getFeeder());
//and the last point
transformation.setLastPoint(new PointWithBearing(growingTrajectory.get(growingTrajectory.size() - 1)));
for (int i = 0; i < ReadConfig.Configurations.getAgentTimeSteps(); i++) {
//transform output into input and add the direction
OutputNetwork outLocal = new OutputNetwork();
outLocal.deserialise(lastOutput);
//TODO if using convolutionary I need to enable the following lines
//Point toAdd = transformation.singlePointConversion(outLocal);
// transformation.setLastPoint(new PointWithBearing(toAdd));
// growingTrajectory.add(toAdd);
res = inputsNetwork.getIdsaLoader().generatePicture(growingTrajectory);
if(!res) throw new Exception("Creation of the pictures did not work out");
//erase image
//((ConvAgent)model).erasePictureCreated(Paths.get(inputsNetwork.getNormalImage()));
realInput = new File(inputsNetwork.getNormalImage());
realInputConverted = imageLoader.asMatrix(realInput);
//compute output
lastOutput = model.computeOutput(realInputConverted);
out = new OutputNetwork();
out.deserialise(lastOutput);
outputsNetworks.add(out);
}
//assign the output to this individual
inputsNetwork.setOutputComputed(outputsNetworks);
individual.addMyInputandOutput(inputsNetwork);
}
}
}
/**
* run the Clax model
* @param input the input of the model
* @param model the model Clax used
* @param individual the individual under evaluation
* @throws Exception if something bad happened
*/
private void runClax(List<TrainReal> input, EvolvableModel model, Individual individual) throws Exception {
//with clax is slightly different
Clax m = (Clax) model; //cast to clax for the proprietary method
//I have more training input in the list
for (TrainReal inputsNetwork : input) {
m.setStart(inputsNetwork.getLastPoint());
m.setTarget(((InputNetwork)inputsNetwork.getTrainingPoint().get(inputsNetwork.getTrainingPoint().size())).getTargetPoint());
//need to compute the trajectory
List<INDArray> out = m.computeTrajectory();
//now for the number of time step that I want to check save the output
List<OutputsNetwork> outputsNetworks = new ArrayList<>();
out.forEach(o -> {
OutputNetwork outClax = new OutputNetwork();
outClax.deserialise(o);
outputsNetworks.add(outClax);
});
//assign the output to this individual
inputsNetwork.setOutputComputed(outputsNetworks);
individual.addMyInputandOutput(inputsNetwork);
}
}
/**
* Run the LSTM agent
* @param input the input of the model
* @param model the model LSTM used
* @param individual the individual under evaluation
* @throws Exception if something bad happened
*/
private void runLSTM(List<TrainReal> input, EvolvableModel model, Individual individual) throws Exception {
//compute Output of the network
INDArray lastOutput = null;
int number;
try{
number = ReadConfig.Configurations.getAgentTimeSteps();
}catch (Exception e){
number = 1;
}
for (TrainReal inputsNetwork : input) {
TrainReal currentInputsNetwork = inputsNetwork.deepCopy();
//now for the number of time step that I want to check save the output
List<OutputsNetwork> outputsNetworks = new ArrayList<>();
List<InputsNetwork> in = currentInputsNetwork.getTrainingPoint();
int size = in.size();
INDArray features = Nd4j.create(new int[]{1, InputNetwork.inputSize, size}, 'f');
for (int j = 0; j < size; j++) {
INDArray vector = in.get(j).serialise();
features.put(new INDArrayIndex[]{NDArrayIndex.point(0), NDArrayIndex.all(), NDArrayIndex.point(j)}, vector);
}
lastOutput = model.computeOutput(features);
int timeSeriesLength = lastOutput.size(2); //Size of time dimension
INDArray realLastOut = lastOutput.get(NDArrayIndex.point(0), NDArrayIndex.all(), NDArrayIndex.point(timeSeriesLength-1));
if(ReadConfig.debug) logger.log(Level.INFO, "Output LSTM ->" + realLastOut.toString());
OutputNetwork out = new OutputNetwork();
out.deserialise(realLastOut);
outputsNetworks.add(out);
logger.log(Level.INFO, "Output LSTM transformed ->" + outputsNetworks.toString());
//output has only two fields, input needs three
//I am using the last direction present into input I am adding that one to the last output
Double directionAPF = ((InputNetwork) currentInputsNetwork.getTrainingPoint().get(currentInputsNetwork.getTrainingPoint().size() - 1)).getDirectionAPF();
for (int i = 0; i < number - 1; i++) {
//transform output into input and add the direction
OutputNetwork outLocal = new OutputNetwork();
outLocal.deserialise(lastOutput);
InputNetwork inputLocal = new InputNetwork(directionAPF, outLocal.getSpeed(), outLocal.getBearing(), currentInputsNetwork.getLastTime());
lastOutput = model.computeOutput(inputLocal.serialise());
if(ReadConfig.debug) logger.log(Level.INFO, "Output LSTM ->" + lastOutput.toString());
out = new OutputNetwork();
out.deserialise(lastOutput);
outputsNetworks.add(out);
}
//assign the output to this individual
currentInputsNetwork.setOutputComputed(outputsNetworks);
//create the output already computed
individual.addMyInputandOutput(currentInputsNetwork);
((LSTMAgent)model).clearPreviousState();
}
}
/**
* @implNote Implementation from Abstract class Algorithm
* @param individual individual with the parameter of the classifier
* @param input input to assign to the classifier
* @return the output of the classifier
* @throws Exception if the nn has problem an exception is raised
*/
public OutputsNetwork runIndividual(Individual individual, List<InputsNetwork> input) throws Exception {
throw new Exception("Method not usable for a Agent");
}
/**
* @implNote Implementation from Abstract class Algorithm
* Method to evaluate the agent using the classifiers
* The fitness of each model is obtained by evaluating it with each of the classifiers in the competing population
* For every classifier that wrongly judges the model as being the real agent, the model’s fitness increases by one.
*
* At the same time I can evaluate the classifier
* The fitness of each classifier is obtained by using it to evaluate each model in the competing population
* For each correct judgement, the classifier’s fitness increases by one
*
* It is evaluating the false trajectory and also the real one
*
* @param competingPopulation competing population
* @param transformation the class that will transform from one output to the new input
*/
public void evaluateIndividuals(Algorithm competingPopulation, Transformation transformation){
/**
* Class for multithreading
* Run one agent against all the classifiers
* Compute the fitness function in this way:
* Now if the classifier (ENN) is returning the value x (>=0.5 -> true) as output, the fitness is computed in this way:
* - agent fitness is x, classifier is (1-x)
* In the other case, output x (<0.5 -> false), the fitness is:
* - classifier is x, agent is (1-x)
*/
class ComputeUnit implements Runnable {
private CountDownLatch latch;
private Individual agent;
private List<Individual> adersarialPopulation;
private MultyScores scores;
private boolean score;
/**
* Constructor
* @param agent current agent
* @param adersarialPopulation adversarial population
* @param score do I want the score
* @param scores where to save the score
*/
private ComputeUnit(Individual agent, List<Individual> adersarialPopulation, boolean score, MultyScores scores) {
this.agent = agent;
this.adersarialPopulation = adersarialPopulation;
this.scores = scores;
this.score = score;
}
/**
* CountDownLatch is a java class in the java.util.concurrent package. It is a mechanism to safely handle
* counting the number of completed tasks. You should call latch.countDown() whenever the run method competes.
* @param latch {@link CountDownLatch}
*/
private void setLatch(CountDownLatch latch) {
this.latch = latch;
}
/**
* Override method run
* run the classifier over the agent
*/
@Override
public void run() {
List<TrainReal> inputOutput = agent.getMyInputandOutput();
for(Individual opponent: this.adersarialPopulation){
for(TrainReal example: inputOutput){
//run the classifier for the Fake trajectory
try {
this.runClassifier(competingPopulation ,agent, opponent, example, true);
} catch (Exception e) {
logger.log(Level.SEVERE, "Error Classifier Fake Input" + e.getMessage());
e.printStackTrace();
}
//run the classifier for the Real trajectory
try {
this.runClassifier(competingPopulation ,agent, opponent, example, false);
} catch (Exception e) {
logger.log(Level.SEVERE, "Error Classifier Real Input" + e.getMessage());
e.printStackTrace();
}
}
}
latch.countDown();
}
/**
* Run the classifier
* @param model model of the classifier
* @param agent agent individual
* @param classifier agent classifier
* @param totalInput TrainReal
* @param real Boolean value. If it is false I do not need to increment the agent fitness since I am checking the real trajectory
*/
private synchronized void runClassifier(Algorithm model, Individual agent, Individual classifier, TrainReal totalInput, boolean real) throws Exception {
List<InputsNetwork> input;
if(real){
input = totalInput.getAllThePartTransformedFake();
}else{
input = totalInput.getAllThePartTransformedReal();
}
tgcfs.Classifiers.OutputNetwork result = (tgcfs.Classifiers.OutputNetwork) model.runIndividual(classifier, input);
if (ReadConfig.debug) logger.log(Level.INFO, "Output network ->" + result.toString() + " realValue -> " + result.getRealValue() + " -->" + real);
double decision = result.getRealValue();
if( decision > 0.5 ) {
//it is saying it is true
//counting this only if the fake trajectory
if(real) {
agent.increaseFitness(decision);
classifier.increaseFitness(1 - decision);
if (this.score) {
Scores sc = new Scores(agent.getModel().getId(),totalInput.getId(), classifier.getModel().getId(), decision);
this.scores.addScore(sc);
}
}
}else{
//it is false
classifier.increaseFitness(decision);
if(real) {
agent.increaseFitness(1 - decision);
if (this.score) {
Scores sc = new Scores(agent.getModel().getId(), totalInput.getId(), classifier.getModel().getId(), decision);
this.scores.addScore(sc);
}
}
}
}
}
/**
* Class for multithreading
* Run one agent against all the classifiers
* Compute the fitness function in this way:
*
* R = #real
* T_jk = (sum_i( classifier_j(agent_i)))k <- in this module
* Y_ijk = (R * classifier_j(agent_i) / T_j)k
* E_ijk = ({ i = real : 1 - Y_ij, i = fake: Y_ij })k
*
* FitnessAgent = sum_k sum_j( E_ijk )
* FitnessClassifier = sum_k sum_i( 1 - E_ijk)
*
*
*
*
*
*
*/
class ComputeSelmarFitnessUnit implements Runnable{
private CountDownLatch latch;
private Individual classifier;
private List<Individual> adersarialPopulation;
private Map<Integer, Map<UUID, Double>> Tik;
/**
* Constructor
* @param classifier current classifier
* @param adersarialPopulation adversarial population
*/
private ComputeSelmarFitnessUnit(Individual classifier, List<Individual> adersarialPopulation) {
this.classifier = classifier;
this.adersarialPopulation = adersarialPopulation;
this.Tik = new HashMap<>();
}
/**
* CountDownLatch is a java class in the java.util.concurrent package. It is a mechanism to safely handle
* counting the number of completed tasks. You should call latch.countDown() whenever the run method competes.
* @param latch {@link CountDownLatch}
*/
private void setLatch(CountDownLatch latch) {
this.latch = latch;
}
/**
* Getter for the classifier's model ID
* @return int id
*/
private int getClassifierID(){
return this.classifier.getModel().getId();
}
/**
* Getter for the results from the classification
* @return Map<Integer, Map<UUID, Double>> containing id agent and his classification
*/
private Map<Integer, Map<UUID, Double>> getResults(){
return this.Tik;
}
/**
* Override method run
* run the classifier over the agent
*
* classifierResultAgentI = classifier_j(agent_i)
* classifierResultAgentI = agent_i classification using classifier j
*/
@Override
public void run() {
for(Individual agent: this.adersarialPopulation){
List<TrainReal> inputOutput = agent.getMyInputandOutput();
//agent id is always the same for all the trajectories
int agentId = agent.getModel().getId();
// trajectory result
Map<UUID, Double> Tj = new HashMap<>();
for(TrainReal example: inputOutput) {
//run the classifier for the Fake trajectory
try {
tgcfs.Classifiers.OutputNetwork result = (tgcfs.Classifiers.OutputNetwork) competingPopulation.runIndividual(classifier, example.getAllThePartTransformedFake());
if (ReadConfig.debug) logger.log(Level.INFO, "Fake Output network ->" + result.toString() + " realValue -> " + result.getRealValue());
//save all the results
Tj.put(example.getId(), result.getRealValue());
} catch (Exception e) {
logger.log(Level.SEVERE, "Error Classifier Fake Input" + e.getMessage());
e.printStackTrace();
}
}
//update the main result with the agent id
this.Tik.put(agentId, Tj);
//also this one is going to be always the same. Lets use only the first real one
int realAgentId = inputOutput.get(0).getIdRealPoint().getId();
// trajectory result
Tj = new HashMap<>();
for(TrainReal example: inputOutput){
//run the classifier for the Real trajectory
try {
tgcfs.Classifiers.OutputNetwork resultReal = (tgcfs.Classifiers.OutputNetwork) competingPopulation.runIndividual(classifier, example.getAllThePartTransformedReal());
if (ReadConfig.debug) logger.log(Level.INFO, "Real Output network ->" + resultReal.toString() + " realValue -> " + resultReal.getRealValue());
//save all the results
Tj.put(example.getId(), resultReal.getRealValue());
} catch (Exception e) {
logger.log(Level.SEVERE, "Error Classifier Real Input" + e.getMessage());
e.printStackTrace();
}
}
//update the main result with the agent id
this.Tik.put(realAgentId, Tj);
}
latch.countDown();
}
}
//Need this with both fitness functions
List<Integer> realAgentsId = new ArrayList<>();
//transform the outputs into the input for the classifiers
for(Individual ind : super.getPopulationWithHallOfFame()){
//transform trajectory in advance to prevent multiprocessing errors
List<TrainReal> inputOutput = ind.getMyInputandOutput();
for(TrainReal trainReal: inputOutput){
((FollowingTheGraph)transformation).setLastPoint(trainReal.getLastPoint());
transformation.transform(trainReal);
realAgentsId.add(trainReal.getIdRealPoint().getId());
}
}
logger.log(Level.SEVERE, "Start real classification");
//set the default fitness as the normal fitness
int fitnessTypology = 0;
try {
fitnessTypology = ReadConfig.Configurations.getFitnessFunction();
} catch (Exception ignored) { }
switch (fitnessTypology){
case 0:
// original fitness function implemented
boolean score = false;
try {
score = ReadConfig.Configurations.getScore();
} catch (Exception ignored) { }
//launch my way to compute the fitness
ExecutorService execOriginal = Executors.newFixedThreadPool(16);
CountDownLatch latchOriginal = new CountDownLatch(super.getPopulationWithHallOfFame().size());
ComputeUnit[] runnablesOriginal = new ComputeUnit[super.getPopulationWithHallOfFame().size()];
for(int i = 0; i < super.getPopulationWithHallOfFame().size(); i ++){
runnablesOriginal[i] = new ComputeUnit(super.getPopulationWithHallOfFame().get(i), competingPopulation.getPopulationWithHallOfFame(), score, this.scores);
}
for(ComputeUnit r : runnablesOriginal) {
r.setLatch(latchOriginal);
execOriginal.execute(r);
}
try {
latchOriginal.await();
execOriginal.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
case 1:
// selmar fitness function
// number real trajectories = total number of trajectories said as real = # trajectories trained * # individuals
int R = super.getPopulationWithHallOfFame().size();
//classifier id, agent id, trajectory id, result
HashMap<Integer, Map<Integer, Map<UUID, Double>>> results = new HashMap<>();
//launch the threads for the computations
ExecutorService exec = Executors.newFixedThreadPool(96);
CountDownLatch latch = new CountDownLatch(competingPopulation.getPopulationWithHallOfFame().size());
ComputeSelmarFitnessUnit[] runnables = new ComputeSelmarFitnessUnit[competingPopulation.getPopulationWithHallOfFame().size()];
//create all the runnables
for(int i = 0; i < competingPopulation.getPopulationWithHallOfFame().size(); i ++){
runnables[i] = new ComputeSelmarFitnessUnit(competingPopulation.getPopulationWithHallOfFame().get(i), super.getPopulationWithHallOfFame());
}
//execute them and wait them till they have finished
for(ComputeSelmarFitnessUnit r : runnables) {
r.setLatch(latch);
exec.execute(r);
}
try {
latch.await();
exec.shutdown();
//collecting the results
for (ComputeSelmarFitnessUnit runnable : runnables) {
//all the i, j fixed -> classifier_j(agent_i))
results.put(runnable.getClassifierID(), runnable.getResults());
}
//find list of trajectories id
Map<Integer, Map<UUID, Double>> a = results.get(results.keySet().toArray()[0]);
Map<UUID, Double> b = a.get(a.keySet().toArray()[0]);
List<UUID> trajectoriesID = new ArrayList<>(b.keySet());
//creation all the Tjk
//T_j_k = (sum_i( classifier_j(agent_i)))_k
//trajectory ID, classifier ID, sum Tjk
HashMap<UUID, HashMap<Integer, Double>> Tjk = new HashMap<>();
//classifier id, agent id, trajectory id, result
for(UUID traID: trajectoriesID){
HashMap<Integer, Double> Tj = new HashMap<>();
for(int classifierID: results.keySet()){
//classifierID is the classifier id -> i
Map<Integer, Map<UUID, Double>> classifierResults = results.get(classifierID);
double classifierTotal = 0.0;
for(Integer agentId: classifierResults.keySet()){
Map<UUID, Double> traMap = classifierResults.get(agentId);
classifierTotal += traMap.get(traID);
}
Tj.put(classifierID, classifierTotal);
}
Tjk.put(traID, Tj);
}
//Creation matrix Yij
//Y_jik = (R * classifier_j(agent_i) / T_j)k
//E_jik = ({ i = real : 1 - Y_ij, i = fake: Y_ij } ^ 2)k
HashMap<UUID, HashMap<Integer, HashMap<Integer, Double>>> Yijk = new HashMap<>();
HashMap<UUID, HashMap<Integer, HashMap<Integer, Double>>> Eijk = new HashMap<>();
for(UUID traID: trajectoriesID){
HashMap<Integer, HashMap<Integer, Double>> Yij = new HashMap<>();
HashMap<Integer, HashMap<Integer, Double>> Eij = new HashMap<>();
for(int classifierID: results.keySet()){
//classifierID is the classifier id -> i
Map<Integer, Map<UUID, Double>> classifierResults = results.get(classifierID);
//Creation id agent,classifier
HashMap<Integer, Double> subE = new HashMap<>();
//for debug, remove this hashmap, it is redundant
HashMap<Integer, Double> subY = new HashMap<>();
for(int agentId: classifierResults.keySet()){
Map<UUID, Double> traMap = classifierResults.get(agentId);
//now I have classifier j and looping over agent i
double singleValue = traMap.get(traID);
double y = R * singleValue / Tjk.get(traID).get(classifierID);
if(Double.isNaN(y)){
y = 0.0;
}
if(y > 1.0) y = 1.0;
if(y < 0.0) y = 0.0;
subY.put(agentId, y);
if(realAgentsId.stream().anyMatch(t -> t == agentId)){
//if point is a real point
// subE.put(agentId, Math.pow(1 - y, 2));
if(y > 0.5) {
//if point real point and it is classified as a real
subE.put(agentId, Math.pow(1 - y, 2)*100);
}else {
//if point is a real point and it is classified as fake
subE.put(agentId, Math.pow(1 - y, 2));
}
// subE.put(agentId, Math.pow(1 - y, 2) * 100);
}else{
///if point is a generated point
subE.put(agentId, Math.pow(y, 2));
if(y > 0.5) {
//if point is a generated point and it is classified as real
subE.put(agentId, Math.pow(y, 2)*100);
}else {
//if point is a generated point and it is classified as fake
subE.put(agentId, Math.pow(y, 2));
}
}
}
Eij.put(classifierID, subE);
//for debug, remove this hashmap, it is redundant
Yij.put(classifierID, subY);
}
Yijk.put(traID, Yij);
Eijk.put(traID, Eij);
}
//FitnessAgent = sum_k(sum_j( E_jik ))
for(Individual agent : super.getPopulationWithHallOfFame()){
int id = agent.getModel().getId();
double fitness = 0;
//need to find all the values with that id and with all the trajectories
for(UUID uuid: Eijk.keySet()){
HashMap<Integer, HashMap<Integer, Double>> Eij = Eijk.get(uuid);
//need to find all the values with that id
for(int classifierID: Eij.keySet()){
fitness += Eij.get(classifierID).get(id);
}
}
agent.setFitness(fitness);
//setting the fitness for the examples of this agent
for(TrainReal example: agent.getMyInputandOutput()){
example.setFitnessGivenByTheClassifier(fitness);
}
}
for(Individual classifier: competingPopulation.getPopulationWithHallOfFame()){
int id = classifier.getModel().getId();
double fitness = 0;
for(UUID uuid: Eijk.keySet()){
HashMap<Integer, HashMap<Integer, Double>> Eij = Eijk.get(uuid);
HashMap<Integer, Double> allTheI = Eij.get(id);
for(int agentId: allTheI.keySet()){
fitness += (Math.abs(1 - allTheI.get(agentId)));
}
}
classifier.setFitness(fitness);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
default:
throw new Error("Fitness type not implemented");
}
}
/**
* Method to train the network with the input selected
* @param combineInputList where to find the input to train
*/
@Override
public void trainNetwork(List<TrainReal> combineInputList) {
//obtain list of inputs
try {
if(ReadConfig.Configurations.getTrain()) {
throw new Exception("How should i train a LSTM without bad examples???");
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Error " + e.getMessage());
}
}
/**
* Save in JSON format the trajectory and the generated part of it
* @param generationAgent number of generation for the agent population
* @param generationClassifier number of generation for the classifier population
* @throws Exception if something wrong happens in saving everything
*/
public void saveTrajectoriesAndPointGenerated(int generationAgent, int generationClassifier) throws Exception {
List<TrainReal> totalList = new ArrayList<>();
for(Individual ind: super.getPopulation()){
for(TrainReal train: ind.getMyInputandOutput()){
totalList.add(train.deepCopy());
}
}
SaveToFile.Saver.dumpTrajectoryAndGeneratedPart(totalList, generationAgent, generationClassifier);
}
/**
* Save in JSON format the trajectory and the generated part of it
* @param gen number of generation I am
* @throws Exception if something wrong happens in saving everything
*/
public void saveTrajectoriesAfterSelection(int gen) throws Exception {
List<TrainReal> totalList = new ArrayList<>();
for(Individual ind: super.getPopulation()){
for(TrainReal train: ind.getMyInputandOutput()){
totalList.add(train.deepCopy());
}
}
SaveToFile.Saver.dumpTrajectoryAndGeneratedPart(totalList, gen);
}
/**
* Save score of the battle
* @param generationAgent number of generation for the agent population
* @param generationClassifier number of generation for the classifier population
* @throws Exception if something wrong happens in saving everything
*/
public void saveScoresBattle(int generationAgent, int generationClassifier) throws Exception {
SaveToFile.Saver.saveScoresBattle(this.scores.getScore(), generationAgent, generationClassifier);
}
/**
* Reset scores
*/
public void resetScore(){
this.scores = new MultyScores();
}
/**
* Generate the real last point
* @param transformation {@link FollowingTheGraph} transformation reference to transform the output in real point //TODO generalise this
*/
public void generateRealPoints(FollowingTheGraph transformation) throws Exception {
for(Individual ind: super.getPopulation()) {
for (TrainReal train : ind.getMyInputandOutput()) {
if(train.getRealPointsOutputComputed() == null) {
List<PointWithBearing> generatedPoint = new ArrayList<>();
transformation.setLastPoint(train.getLastPoint());
for(OutputsNetwork outputsNetwork: train.getOutputComputed()){
generatedPoint.add(new PointWithBearing(transformation.singlePointConversion(outputsNetwork, train.getLastTime())));
}
train.setRealPointsOutputComputed(generatedPoint);
train.computeStatistic();
}
}
}
}
}
|
dif version fitness
|
src/main/java/tgcfs/EA/Agents.java
|
dif version fitness
|
|
Java
|
mit
|
c22296c2b969b9ef0dbeb974a646fdaa49c3e600
| 0
|
sikuli/sikuli-slides,sikuli/sikuli-slides,sikuli/sikuli-slides
|
/**
Khalid
*/
package org.sikuli.slides.utils;
import java.io.File;
/**
* This class contains constants.
* @author Khalid Alharbi
*
*/
public class Constants {
/**
* The working directory absolute path.
* This holds the sikuli slides working directory in the operating system's temp directory.
*/
public static String workingDirectoryPath;
/**
* The current project directory name that contains the imported and extracted .pptx file.
*/
public static String projectDirectory;
/**
* The name of the directory that sikuli-slides creates in the operating system's tmp directory.
*/
public static final String SIKULI_SLIDES_ROOT_DIRECTORY="org.sikuli.SikuliSlides";
/**
* The name of the directory that contains all sikuli related files in the .pptx file.
*/
public static final String SIKULI_DIRECTORY=File.separator+"sikuli";
/**
* The name of the images directory that contains the cropped target images.
*/
public static final String IMAGES_DIRECTORY=File.separator+"images";
/**
* The slides directory that contains the XML files for each slide in the .pptx file.
*/
public static final String SLIDES_DIRECTORY=File.separator+"ppt"+File.separator+"slides";
/**
* The slides directory that contains the media files for each slide in the .pptx file.
*/
public static final String MEDIA_DIRECTORY=File.separator+"ppt"+File.separator+"media";
/**
* The presentaion.xml absolute path name.
*/
public static final String PRESENTATION_DIRECTORY=File.separator+"ppt"+File.separator+"presentation.xml";
/**
* The relationship directory that contains info about the duplicated media files in the presentation slides.
*/
public static final String RELATIONSHIP_DIRECTORY=File.separator+"ppt"+File.separator+"slides"+File.separator+"_rels";
/**
* The maximum time to wait in milliseconds
*/
public static int MaxWaitTime=15000;
/**
* The duration time in seconds to display annotation (canvas) around the target on the screen.
*/
public static final int CANVAS_DURATION=1;
}
|
src/main/java/org/sikuli/slides/utils/Constants.java
|
/**
Khalid
*/
package org.sikuli.slides.utils;
import java.io.File;
/**
* This class contains constants.
* @author Khalid Alharbi
*
*/
public class Constants {
/**
* The working directory absolute path.
* This is the sikuli slides working directory in the operating system's temp directory.
*/
public static String workingDirectoryPath;
/**
* The current project directory name that contains the imported and extracted .pptx file.
*/
public static String projectDirectory;
/**
* The name of the directory that sikuli-slides creates in the operating system's tmp directory.
*/
public static final String SIKULI_SLIDES_ROOT_DIRECTORY="org.sikuli.SikuliSlides";
/**
* The name of the directory that contains all sikuli related files in the .pptx file.
*/
public static final String SIKULI_DIRECTORY=File.separator+"sikuli";
/**
* The name of the images directory that contains the cropped target images.
*/
public static final String IMAGES_DIRECTORY=File.separator+"images";
/**
* The slides directory that contains the XML files for each slide in the .pptx file.
*/
public static final String SLIDES_DIRECTORY=File.separator+"ppt"+File.separator+"slides";
/**
* The slides directory that contains the media files for each slide in the .pptx file.
*/
public static final String MEDIA_DIRECTORY=File.separator+"ppt"+File.separator+"media";
/**
* The presentaion.xml absolute path name.
*/
public static final String PRESENTATION_DIRECTORY=File.separator+"ppt"+File.separator+"presentation.xml";
/**
* The relationship directory that contains info about the duplicated media files in the presentation slides.
*/
public static final String RELATIONSHIP_DIRECTORY=File.separator+"ppt"+File.separator+"slides"+File.separator+"_rels";
/**
* The maximum time to wait in milliseconds
*/
public static int MaxWaitTime=15000;
/**
* The duration time in seconds to display annotation (canvas) around the target on the screen.
*/
public static final int CANVAS_DURATION=1;
}
|
update javadoc comment
|
src/main/java/org/sikuli/slides/utils/Constants.java
|
update javadoc comment
|
|
Java
|
mit
|
d8c8c1de6ce5ab62951ab6b010e1e649abdc5e02
| 0
|
tlaplus/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,lemmy/tlaplus
|
// Copyright (c) 2003 Compaq Corporation. All rights reserved.
// Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved.
// Last modified on Mon 30 Apr 2007 at 13:33:49 PST by lamport
// modified on Fri Jul 14 15:40:49 PDT 2000 by yuanyu
package tlc2.tool.liveness;
import java.io.PrintStream;
/*
* Roughly speaking, each temporal formula maps 1:1 to OrderOfSolution. Say TLC is set to check
* the three temporal formulas A, B, C, there will be three OrderOfSolution instances
* (one for each of formula). More precisely, each conjunct is represented by an OOS.
*
* For details, see page 405 to 408 of "Temporal verification of Reactive Systems * safety *"
* by Manna and Pnueli (abbreviated to "MP book" in most of TLC's code comments).
*
* Note that TLC does *not* check if A, B or C are identical formulas. If TLC is set to
* check A, A, A (it will still create three OrderOfSolutions). It is up to the
* user to prevent this.
*/
public class OrderOfSolution {
/**
* The algorithm will decompose the fairness spec /\ ~check into a
* disjunction of conjuncts of the following form: (<>[]a /\ []<>b /\ tf1)
* \/ (<>[]c /\ []<>d /\ tf2) .. For efficiency, we will identify disjuncts
* that have the same tableau (tf), and OrderOfSolution groups them
* together: (<>[]a/\[]<>b \/ <>[]c/\[]<>d) /\ tf Each conjunct
* (<>[]a/\[]<>b) is represented by a PossibleErrorModel. The solution then
* proceeds: construct the behaviour graph using the tableau, compute
* strongly connected components, and see if it meets any one of the
* disjunctions. Also, it's likely that a single order of solution will have
* lots of duplication in its <>[] and []<> spread over its disjunctions and
* conjunctions. To avoid waste, we use a lookup table: checkState,
* checkAction: when examining each state and its transitions, these are the
* things we have to remember before throwing it away. The possible error
* model stores indexes into checkState and checkAction arrays, under EA/AE,
* state/action. The field promises are all the promises contained in the
* closure.
*/
/*
* The size of the tableaux graph is a function of the amount of
* disjuncts in the temporal formuals.
*/
public TBGraph tableau; // tableau graph
public LNEven[] promises; // promises in the tableau
public LiveExprNode[] checkState; // state subformula
public LiveExprNode[] checkAction; // action subformula
public PossibleErrorModel[] pems;
public final void printPromises(PrintStream ps) {
for (int i = 0; i < this.promises.length; i++) {
ps.println(this.promises[i].toString());
}
}
public final String toString() {
if (this.pems.length == 0) {
return "";
}
StringBuffer sb = new StringBuffer();
this.toString(sb);
return sb.toString();
}
public final void toString(StringBuffer sb) {
String padding = "";
int plen = this.pems.length;
if (this.tableau != null) {
if (plen == 1 && this.pems[0].isEmpty()) {
this.tableau.tf.toString(sb, " ");
return;
} else {
sb.append("/\\ ");
this.tableau.tf.toString(sb, " ");
sb.append("\n/\\ ");
padding = " ";
}
}
if (plen == 1) {
this.pems[0].toString(sb, padding, this.checkState, this.checkAction);
} else {
sb.append("\\/ ");
String padding1 = padding + " ";
this.pems[0].toString(sb, padding1, this.checkState, this.checkAction);
for (int i = 1; i < plen; i++) {
sb.append(padding + "\\/ ");
this.pems[i].toString(sb, padding1, this.checkState, this.checkAction);
}
}
}
}
|
tlatools/src/tlc2/tool/liveness/OrderOfSolution.java
|
// Copyright (c) 2003 Compaq Corporation. All rights reserved.
// Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved.
// Last modified on Mon 30 Apr 2007 at 13:33:49 PST by lamport
// modified on Fri Jul 14 15:40:49 PDT 2000 by yuanyu
package tlc2.tool.liveness;
import java.io.PrintStream;
public class OrderOfSolution {
/**
* The algorithm will decompose the fairness spec /\ ~check into a
* disjunction of conjuncts of the following form: (<>[]a /\ []<>b /\ tf1)
* \/ (<>[]c /\ []<>d /\ tf2) .. For efficiency, we will identify disjuncts
* that have the same tableau (tf), and OrderOfSolution groups them
* together: (<>[]a/\[]<>b \/ <>[]c/\[]<>d) /\ tf Each conjunct
* (<>[]a/\[]<>b) is represented by a PossibleErrorModel. The solution then
* proceeds: construct the behaviour graph using the tableau, compute
* strongly connected components, and see if it meets any one of the
* disjunctions. Also, it's likely that a single order of solution will have
* lots of duplication in its <>[] and []<> spread over its disjunctions and
* conjunctions. To avoid waste, we use a lookup table: checkState,
* checkAction: when examining each state and its transitions, these are the
* things we have to remember before throwing it away. The possible error
* model stores indexes into checkState and checkAction arrays, under EA/AE,
* state/action. The field promises are all the promises contained in the
* closure.
*/
public TBGraph tableau; // tableau graph
public LNEven[] promises; // promises in the tableau
public LiveExprNode[] checkState; // state subformula
public LiveExprNode[] checkAction; // action subformula
public PossibleErrorModel[] pems;
public final void printPromises(PrintStream ps) {
for (int i = 0; i < this.promises.length; i++) {
ps.println(this.promises[i].toString());
}
}
public final String toString() {
if (this.pems.length == 0) {
return "";
}
StringBuffer sb = new StringBuffer();
this.toString(sb);
return sb.toString();
}
public final void toString(StringBuffer sb) {
String padding = "";
int plen = this.pems.length;
if (this.tableau != null) {
if (plen == 1 && this.pems[0].isEmpty()) {
this.tableau.tf.toString(sb, " ");
return;
} else {
sb.append("/\\ ");
this.tableau.tf.toString(sb, " ");
sb.append("\n/\\ ");
padding = " ";
}
}
if (plen == 1) {
this.pems[0].toString(sb, padding, this.checkState, this.checkAction);
} else {
sb.append("\\/ ");
String padding1 = padding + " ";
this.pems[0].toString(sb, padding1, this.checkState, this.checkAction);
for (int i = 1; i < plen; i++) {
sb.append(padding + "\\/ ");
this.pems[i].toString(sb, padding1, this.checkState, this.checkAction);
}
}
}
}
|
Explain mapping between temporal formuals and OrderOfSolutions (each
temporal maps 1:1 to an OrderOfSolutions).
|
tlatools/src/tlc2/tool/liveness/OrderOfSolution.java
|
Explain mapping between temporal formuals and OrderOfSolutions (each temporal maps 1:1 to an OrderOfSolutions).
|
|
Java
|
mit
|
6ea473c5890210c8b819de4341dd76c5808a0720
| 0
|
rednaxelafx/jvm.go,zxh0/jvm.go,elancom/jvm.go,elancom/jvm.go,zxh0/jvm.go,zxh0/jvm.go,elancom/jvm.go,rednaxelafx/jvm.go,rednaxelafx/jvm.go
|
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class UnsafeTest {
public static void main(String[] args) throws Exception {
//Unsafe unsafe = Unsafe.getUnsafe();
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);
System.out.println(unsafe.arrayBaseOffset(new int[0].getClass()));
System.out.println(unsafe.arrayBaseOffset(new long[0].getClass()));
System.out.println(unsafe.arrayBaseOffset(new Object[0].getClass()));
System.out.println(unsafe.arrayBaseOffset(new Class<?>[0].getClass()));
System.out.println(unsafe.arrayIndexScale(new int[0].getClass()));
System.out.println(unsafe.arrayIndexScale(new long[0].getClass()));
System.out.println(unsafe.arrayIndexScale(new Object[0].getClass()));
System.out.println(unsafe.arrayIndexScale(new Class<?>[0].getClass()));
}
}
|
testclasses/src/main/java/UnsafeTest.java
|
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class UnsafeTest {
public static void main(String[] args) throws Exception {
//Unsafe unsafe = Unsafe.getUnsafe();
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);
System.out.println("OK!");
}
}
|
test Unsafe
|
testclasses/src/main/java/UnsafeTest.java
|
test Unsafe
|
|
Java
|
mit
|
5106eaed5ebcb2638960dde4b3839fcac17c1bf0
| 0
|
thingweb/thingweb-led-demo,thingweb/thingweb-led-demo
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Siemens AG and the thingweb community
*
* 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 de.thingweb.launcher;
import de.thingweb.desc.ThingDescriptionParser;
import de.thingweb.jsruntime.WotJavaScriptRuntime;
import de.thingweb.leddemo.DemoLedAdapter;
import de.thingweb.security.TokenRequirements;
import de.thingweb.servient.ServientBuilder;
import de.thingweb.servient.ThingInterface;
import de.thingweb.servient.ThingServer;
import de.thingweb.thing.Content;
import de.thingweb.thing.MediaType;
import de.thingweb.thing.Thing;
import de.thingweb.util.encoding.ContentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Launches a WoT thing.
*/
public class LedDemoLauncher {
private static final Logger log = LoggerFactory.getLogger(LedDemoLauncher.class);
private static final int STEPLENGTH = 100;
private static final ExecutorService executor = Executors.newCachedThreadPool();
private final ThingServer server;
private final WotJavaScriptRuntime jsrt;
private final Thing srvThing;
public LedDemoLauncher() throws Exception {
ServientBuilder.initialize();
final TokenRequirements tokenRequirements = NicePlugFestTokenReqFactory.createTokenRequirements();
server = ServientBuilder.newThingServer(tokenRequirements);
jsrt = WotJavaScriptRuntime.createOn(server);
final Thing fancyLedDesc = Tools.getThingDescriptionFromFileOrResource("fancy_led.jsonld");
// final Thing basicLedDesc = Tools.getThingDescriptionFromFileOrResource("basic_led.jsonld");
final Thing basicLedDesc = Tools.getThingDescriptionFromFileOrResource("basic_led_beijing.jsonld");
final Thing servientDesc = Tools.getThingDescriptionFromFileOrResource("servientmodel.jsonld");
ThingInterface fancyLed = server.addThing(fancyLedDesc);
ThingInterface basicLed = server.addThing(basicLedDesc);
srvThing = servientDesc;
ThingInterface serverInterface = server.addThing(srvThing);
attachBasicHandlers(basicLed);
attachFancyHandlers(fancyLed);
addServientInterfaceHandlers(serverInterface);
}
public static void main(String[] args) throws Exception {
LedDemoLauncher launcher = new LedDemoLauncher();
launcher.start();
launcher.runAutostart();
}
public void runAutostart() throws IOException {
String sAutoRunFolder = "./autorun";
Path p = Paths.get(sAutoRunFolder);
if(Files.exists(p)) {
Files.walk(p)
.filter(Files::isRegularFile)
.map(Path::toFile)
.forEach(file -> {
try {
jsrt.runFile(file);
} catch (FileNotFoundException | ScriptException e) {
log.error("error running autostart file " + file, e);
}
});
}
}
public void start() throws Exception {
ServientBuilder.start();
}
public void addServientInterfaceHandlers(ThingInterface serverInterface) throws IOException {
serverInterface.setProperty("numberOfThings", server.getThings().size());
serverInterface.setProperty("securityEnabled", false);
serverInterface.onUpdate("securityEnabled", (nV) -> {
final Boolean protectionEnabled = ContentHelper.ensureClass(nV, Boolean.class);
server.getThings().stream()
.filter((thing1 -> !thing1.equals(srvThing)))
.forEach(thing -> {
log.info(" setting security enablement for {} to {}", thing.getName(), protectionEnabled);
thing.setProtection(protectionEnabled);
server.rebindSec(thing.getName(), protectionEnabled); //overwriting handlers, very inefficient
});
});
serverInterface.onInvoke("createThing", (data) -> {
final LinkedHashMap jsonld = ContentHelper.ensureClass(data, LinkedHashMap.class);
try {
final Thing newThing = ThingDescriptionParser.fromJavaMap(jsonld);
server.addThing(newThing);
serverInterface.setProperty("numberOfThings", server.getThings().size());
return newThing.getMetadata();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
serverInterface.onInvoke("addHandlerScript", (data) -> {
final String script = ContentHelper.ensureClass(data, String.class);
try {
jsrt.runScript(script);
} catch (ScriptException e) {
throw new RuntimeException(e);
}
return new Content(new byte[0], MediaType.APPLICATION_JSON);
});
}
public void attachBasicHandlers(final ThingInterface led) {
DemoLedAdapter realLed = new DemoLedAdapter();
Snake snake = new Snake(realLed);
//init block
led.setProperty("rgbValueRed", realLed.getRed() & 0xFF);
led.setProperty("rgbValueGreen", realLed.getGreen() & 0xFF);
led.setProperty("rgbValueBlue", realLed.getBlue() & 0xFF);
led.setProperty("brightness", realLed.getBrightnessPercent());
led.onUpdate("rgbValueBlue", (input) -> {
Integer value = ContentHelper.ensureClass(input, Integer.class);
log.info("setting blue value to " + value);
realLed.setBlue((byte) value.intValue());
});
led.onUpdate("rgbValueRed", (input) -> {
Integer value = ContentHelper.ensureClass(input, Integer.class);
log.info("setting red value to " + value);
realLed.setRed((byte) value.intValue());
});
led.onUpdate("rgbValueGreen", (input) -> {
Integer value = ContentHelper.ensureClass(input, Integer.class);
log.info("setting green value to " + value);
realLed.setGreen((byte) value.intValue());
});
led.onUpdate("brightness", (input) -> {
Integer value = ContentHelper.ensureClass(input, Integer.class);
log.info("setting brightness to " + value);
realLed.setBrightnessPercent(value.byteValue());
});
led.onActionInvoke("startSnake", (input) -> {
snake.start();
led.setProperty("snakes", snake.count());
return null;
});
led.onActionInvoke("stopSnake", (input) -> {
snake.stop();
led.setProperty("snakes", snake.count());
return null;
});
// init 0
led.setProperty("snakes", 0);
}
public void attachFancyHandlers(final ThingInterface fancyLed) {
ThingInterface basicLed = server.getThing("basicLed");
fancyLed.onUpdate("colorTemperature", (input) -> {
ThingInterface led = server.getThing("basicLed");
Integer colorTemperature = ContentHelper.ensureClass(input, Integer.class);
log.info("setting color temperature to " + colorTemperature + " K");
int red= 255;
int green = 255;
int blue = 255;
int ct_scaled = colorTemperature / 100;
if (ct_scaled > 66) {
double fred = ct_scaled - 60;
fred = 329.698727446 * Math.pow(fred, -0.1332047592);
red = DemoLedAdapter.doubletoByte(fred);
double fgreen = ct_scaled - 60;
fgreen = 288.1221695283 * Math.pow(fgreen, -0.0755148492);
green = DemoLedAdapter.doubletoByte(fgreen);
} else {
double fgreen = ct_scaled;
fgreen = 99.4708025861 * Math.log(fgreen) - 161.1195681661;
green = DemoLedAdapter.doubletoByte(fgreen);
if(ct_scaled > 19) {
double fblue = ct_scaled - 10;
fblue = 138.5177312231 * Math.log(fblue) - 305.0447927307;
blue = DemoLedAdapter.doubletoByte(fblue);
}
}
log.info("color temperature equals (" + red + "," + green + "," + blue +")");
led.setProperty("rgbValueGreen",green);
led.setProperty("rgbValueRed", red);
led.setProperty("rgbValueBlue", blue);
});
fancyLed.onInvoke("fadeIn", (input) -> {
ThingInterface led = server.getThing("basicLed");
Integer duration = ContentHelper.ensureClass(input, Integer.class);
log.info("fading in over {}s", duration);
Runnable execution = () -> {
int steps = duration * 1000 / STEPLENGTH;
int delta = Math.max(100 / steps, 1);
int brightness = 0;
led.setProperty("brightness", brightness);
while (brightness < 100) {
led.setProperty("brightness", brightness);
try {
Thread.sleep(STEPLENGTH);
} catch (InterruptedException e) {
break;
}
brightness += delta;
}
};
//TODO assign resource for thread (outside)
new Thread(execution).start();
return new Content("".getBytes(), MediaType.APPLICATION_JSON);
});
fancyLed.onInvoke("fadeOut", (input) -> {
ThingInterface led = server.getThing("basicLed");
Integer duration = ContentHelper.ensureClass(input, Integer.class);
Runnable execution = () -> {
int steps = duration * 1000 / STEPLENGTH;
int delta = Math.max(100 / steps,1);
int brightness = 100;
led.setProperty("brightness", brightness);
while(brightness > 0) {
led.setProperty("brightness", brightness);
try {
Thread.sleep(STEPLENGTH);
} catch (InterruptedException e) {
break;
}
brightness -= delta;
}
};
new Thread(execution).start();
return new Content("".getBytes(), MediaType.APPLICATION_JSON);
});
fancyLed.onInvoke("ledOnOff", (input) -> {
ThingInterface led = server.getThing("basicLed");
Boolean target = ContentHelper.ensureClass(input, Boolean.class);
if(target) {
led.setProperty("rgbValueGreen",255);
led.setProperty("rgbValueRed",255);
led.setProperty("rgbValueBlue", 255);
led.setProperty("brightness", 100);
} else {
led.setProperty("brightness", 0);
led.setProperty("rgbValueGreen",0);
led.setProperty("rgbValueRed",0);
led.setProperty("rgbValueBlue", 0);
}
return new Content("".getBytes(), MediaType.APPLICATION_JSON);
});
fancyLed.onInvoke("trafficLight", (input) -> {
ThingInterface led = server.getThing("basicLed");
Boolean go = ContentHelper.ensureClass(input, Boolean.class);
log.info("trafic light changing state to {}",(go)? "green": "red" );
if(go) {
led.setProperty("rgbValueGreen",255);
led.setProperty("rgbValueRed", 0);
led.setProperty("rgbValueBlue", 0);
} else {
led.setProperty("rgbValueGreen",0);
led.setProperty("rgbValueRed",255);
led.setProperty("rgbValueBlue", 0);
}
return new Content("".getBytes(), MediaType.APPLICATION_JSON);
} );
}
}
|
src/main/java/de/thingweb/launcher/LedDemoLauncher.java
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Siemens AG and the thingweb community
*
* 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 de.thingweb.launcher;
import de.thingweb.desc.ThingDescriptionParser;
import de.thingweb.jsruntime.WotJavaScriptRuntime;
import de.thingweb.leddemo.DemoLedAdapter;
import de.thingweb.security.TokenRequirements;
import de.thingweb.servient.ServientBuilder;
import de.thingweb.servient.ThingInterface;
import de.thingweb.servient.ThingServer;
import de.thingweb.thing.Content;
import de.thingweb.thing.MediaType;
import de.thingweb.thing.Thing;
import de.thingweb.util.encoding.ContentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Launches a WoT thing.
*/
public class LedDemoLauncher {
private static final Logger log = LoggerFactory.getLogger(LedDemoLauncher.class);
private static final int STEPLENGTH = 100;
private static final ExecutorService executor = Executors.newCachedThreadPool();
private final ThingServer server;
private final WotJavaScriptRuntime jsrt;
private final Thing srvThing;
public LedDemoLauncher() throws Exception {
ServientBuilder.initialize();
final TokenRequirements tokenRequirements = NicePlugFestTokenReqFactory.createTokenRequirements();
server = ServientBuilder.newThingServer(tokenRequirements);
jsrt = WotJavaScriptRuntime.createOn(server);
final Thing fancyLedDesc = Tools.getThingDescriptionFromFileOrResource("fancy_led.jsonld");
// final Thing basicLedDesc = Tools.getThingDescriptionFromFileOrResource("basic_led.jsonld");
final Thing basicLedDesc = Tools.getThingDescriptionFromFileOrResource("basic_led_beijing.jsonld");
final Thing servientDesc = Tools.getThingDescriptionFromFileOrResource("servientmodel.jsonld");
ThingInterface fancyLed = server.addThing(fancyLedDesc);
ThingInterface basicLed = server.addThing(basicLedDesc);
srvThing = servientDesc;
ThingInterface serverInterface = server.addThing(srvThing);
attachBasicHandlers(basicLed);
attachFancyHandlers(fancyLed);
addServientInterfaceHandlers(serverInterface);
}
public static void main(String[] args) throws Exception {
LedDemoLauncher launcher = new LedDemoLauncher();
launcher.start();
launcher.runAutostart();
}
public void runAutostart() throws IOException {
Files.walk(Paths.get("./autorun"))
.filter(Files::isRegularFile)
.map(Path::toFile)
.forEach(file -> {
try {
jsrt.runFile(file);
} catch (FileNotFoundException | ScriptException e) {
log.error("error running autostart file " + file, e);
}
});
}
public void start() throws Exception {
ServientBuilder.start();
}
public void addServientInterfaceHandlers(ThingInterface serverInterface) throws IOException {
serverInterface.setProperty("numberOfThings", server.getThings().size());
serverInterface.setProperty("securityEnabled", false);
serverInterface.onUpdate("securityEnabled", (nV) -> {
final Boolean protectionEnabled = ContentHelper.ensureClass(nV, Boolean.class);
server.getThings().stream()
.filter((thing1 -> !thing1.equals(srvThing)))
.forEach(thing -> {
log.info(" setting security enablement for {} to {}", thing.getName(), protectionEnabled);
thing.setProtection(protectionEnabled);
server.rebindSec(thing.getName(), protectionEnabled); //overwriting handlers, very inefficient
});
});
serverInterface.onInvoke("createThing", (data) -> {
final LinkedHashMap jsonld = ContentHelper.ensureClass(data, LinkedHashMap.class);
try {
final Thing newThing = ThingDescriptionParser.fromJavaMap(jsonld);
server.addThing(newThing);
serverInterface.setProperty("numberOfThings", server.getThings().size());
return newThing.getMetadata();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
serverInterface.onInvoke("addHandlerScript", (data) -> {
final String script = ContentHelper.ensureClass(data, String.class);
try {
jsrt.runScript(script);
} catch (ScriptException e) {
throw new RuntimeException(e);
}
return new Content(new byte[0], MediaType.APPLICATION_JSON);
});
}
public void attachBasicHandlers(final ThingInterface led) {
DemoLedAdapter realLed = new DemoLedAdapter();
Snake snake = new Snake(realLed);
//init block
led.setProperty("rgbValueRed", realLed.getRed() & 0xFF);
led.setProperty("rgbValueGreen", realLed.getGreen() & 0xFF);
led.setProperty("rgbValueBlue", realLed.getBlue() & 0xFF);
led.setProperty("brightness", realLed.getBrightnessPercent());
led.onUpdate("rgbValueBlue", (input) -> {
Integer value = ContentHelper.ensureClass(input, Integer.class);
log.info("setting blue value to " + value);
realLed.setBlue((byte) value.intValue());
});
led.onUpdate("rgbValueRed", (input) -> {
Integer value = ContentHelper.ensureClass(input, Integer.class);
log.info("setting red value to " + value);
realLed.setRed((byte) value.intValue());
});
led.onUpdate("rgbValueGreen", (input) -> {
Integer value = ContentHelper.ensureClass(input, Integer.class);
log.info("setting green value to " + value);
realLed.setGreen((byte) value.intValue());
});
led.onUpdate("brightness", (input) -> {
Integer value = ContentHelper.ensureClass(input, Integer.class);
log.info("setting brightness to " + value);
realLed.setBrightnessPercent(value.byteValue());
});
led.onActionInvoke("startSnake", (input) -> {
snake.start();
led.setProperty("snakes", snake.count());
return null;
});
led.onActionInvoke("stopSnake", (input) -> {
snake.stop();
led.setProperty("snakes", snake.count());
return null;
});
// init 0
led.setProperty("snakes", 0);
}
public void attachFancyHandlers(final ThingInterface fancyLed) {
ThingInterface basicLed = server.getThing("basicLed");
fancyLed.onUpdate("colorTemperature", (input) -> {
ThingInterface led = server.getThing("basicLed");
Integer colorTemperature = ContentHelper.ensureClass(input, Integer.class);
log.info("setting color temperature to " + colorTemperature + " K");
int red= 255;
int green = 255;
int blue = 255;
int ct_scaled = colorTemperature / 100;
if (ct_scaled > 66) {
double fred = ct_scaled - 60;
fred = 329.698727446 * Math.pow(fred, -0.1332047592);
red = DemoLedAdapter.doubletoByte(fred);
double fgreen = ct_scaled - 60;
fgreen = 288.1221695283 * Math.pow(fgreen, -0.0755148492);
green = DemoLedAdapter.doubletoByte(fgreen);
} else {
double fgreen = ct_scaled;
fgreen = 99.4708025861 * Math.log(fgreen) - 161.1195681661;
green = DemoLedAdapter.doubletoByte(fgreen);
if(ct_scaled > 19) {
double fblue = ct_scaled - 10;
fblue = 138.5177312231 * Math.log(fblue) - 305.0447927307;
blue = DemoLedAdapter.doubletoByte(fblue);
}
}
log.info("color temperature equals (" + red + "," + green + "," + blue +")");
led.setProperty("rgbValueGreen",green);
led.setProperty("rgbValueRed", red);
led.setProperty("rgbValueBlue", blue);
});
fancyLed.onInvoke("fadeIn", (input) -> {
ThingInterface led = server.getThing("basicLed");
Integer duration = ContentHelper.ensureClass(input, Integer.class);
log.info("fading in over {}s", duration);
Runnable execution = () -> {
int steps = duration * 1000 / STEPLENGTH;
int delta = Math.max(100 / steps, 1);
int brightness = 0;
led.setProperty("brightness", brightness);
while (brightness < 100) {
led.setProperty("brightness", brightness);
try {
Thread.sleep(STEPLENGTH);
} catch (InterruptedException e) {
break;
}
brightness += delta;
}
};
//TODO assign resource for thread (outside)
new Thread(execution).start();
return new Content("".getBytes(), MediaType.APPLICATION_JSON);
});
fancyLed.onInvoke("fadeOut", (input) -> {
ThingInterface led = server.getThing("basicLed");
Integer duration = ContentHelper.ensureClass(input, Integer.class);
Runnable execution = () -> {
int steps = duration * 1000 / STEPLENGTH;
int delta = Math.max(100 / steps,1);
int brightness = 100;
led.setProperty("brightness", brightness);
while(brightness > 0) {
led.setProperty("brightness", brightness);
try {
Thread.sleep(STEPLENGTH);
} catch (InterruptedException e) {
break;
}
brightness -= delta;
}
};
new Thread(execution).start();
return new Content("".getBytes(), MediaType.APPLICATION_JSON);
});
fancyLed.onInvoke("ledOnOff", (input) -> {
ThingInterface led = server.getThing("basicLed");
Boolean target = ContentHelper.ensureClass(input, Boolean.class);
if(target) {
led.setProperty("rgbValueGreen",255);
led.setProperty("rgbValueRed",255);
led.setProperty("rgbValueBlue", 255);
led.setProperty("brightness", 100);
} else {
led.setProperty("brightness", 0);
led.setProperty("rgbValueGreen",0);
led.setProperty("rgbValueRed",0);
led.setProperty("rgbValueBlue", 0);
}
return new Content("".getBytes(), MediaType.APPLICATION_JSON);
});
fancyLed.onInvoke("trafficLight", (input) -> {
ThingInterface led = server.getThing("basicLed");
Boolean go = ContentHelper.ensureClass(input, Boolean.class);
log.info("trafic light changing state to {}",(go)? "green": "red" );
if(go) {
led.setProperty("rgbValueGreen",255);
led.setProperty("rgbValueRed", 0);
led.setProperty("rgbValueBlue", 0);
} else {
led.setProperty("rgbValueGreen",0);
led.setProperty("rgbValueRed",255);
led.setProperty("rgbValueBlue", 0);
}
return new Content("".getBytes(), MediaType.APPLICATION_JSON);
} );
}
}
|
fix issued with on existing autorun folder
|
src/main/java/de/thingweb/launcher/LedDemoLauncher.java
|
fix issued with on existing autorun folder
|
|
Java
|
mit
|
97edc5bf28050f6e703b3b87e88cda887c3d8790
| 0
|
ruan3/OpenLive_Android_text
|
package io.agora.contract.utils;
/**
* 作者:尚硅谷-杨光福 on 2016/7/22 09:21
* 微信:yangguangfu520
* QQ号:541433511
* 作用:常量类,配置网络地址
*/
public class Constants {
/**
* 网络视频的联网地址
*/
public static final String NET_URL = "http://api.m.mtime.cn/PageSubArea/TrailerList.api";
/**
* 搜索的路径
*/
public static final String SEARCH_URL = "http://hot.news.cntv.cn/index.php?controller=list&action=searchList&sort=date&n=20&wd=";
/**
* 网络音乐
*/
public static final String ALL_RES_URL = "http://s.budejie.com/topic/list/jingxuan/1/budejie-android-6.2.8/0-20.json?market=baidu&udid=863425026599592&appname=baisibudejie&os=4.2.2&client=android&visiting=&mac=98%3A6c%3Af5%3A4b%3A72%3A6d&ver=6.2.8";
//
public static final String ALL_RES_ONE = "http://s.budejie.com/topic/list/jingxuan/1/budejie-android-6.2.8/";
public static final String All_res_two = ".json?market=baidu&udid=863425026599592&appname=baisibudejie&os=4.2.2&client=android&visiting=&mac=98%3A6c%3Af5%3A4b%3A72%3A6d&ver=6.2.8";
public static final String TYPE_COMMENT = "type_comment";
public static final String TYPE_URL = "type_url";
public static final String COMMENT_TITLE = "comment_title";
public static final String COMMENT_ORGIN = "comment_orgin";
public static final String TEXT_CONTENT = "text_content";
public static final String DURATION_VIDEO = "duration_video";
public static final String PLAY_TIMES = "play_times";
public static final String VIDEO_THUMBS = "video_thumbs";
public static final String CONTENT_ID = "cotent_id";
public static final String liveRoomID = "liveRoomId";//直播房间的id
}
|
app/src/main/java/io/agora/contract/utils/Constants.java
|
package io.agora.contract.utils;
/**
* 作者:尚硅谷-杨光福 on 2016/7/22 09:21
* 微信:yangguangfu520
* QQ号:541433511
* 作用:常量类,配置网络地址
*/
public class Constants {
/**
* 网络视频的联网地址
*/
public static final String NET_URL = "http://api.m.mtime.cn/PageSubArea/TrailerList.api";
/**
* 搜索的路径
*/
public static final String SEARCH_URL = "http://hot.news.cntv.cn/index.php?controller=list&action=searchList&sort=date&n=20&wd=";
/**
* 网络音乐
*/
public static final String ALL_RES_URL = "http://s.budejie.com/topic/list/jingxuan/1/budejie-android-6.2.8/0-20.json?market=baidu&udid=863425026599592&appname=baisibudejie&os=4.2.2&client=android&visiting=&mac=98%3A6c%3Af5%3A4b%3A72%3A6d&ver=6.2.8";
//
public static final String ALL_RES_ONE = "http://s.budejie.com/topic/list/jingxuan/1/budejie-android-6.2.8/";
public static final String All_res_two = ".json?market=baidu&udid=863425026599592&appname=baisibudejie&os=4.2.2&client=android&visiting=&mac=98%3A6c%3Af5%3A4b%3A72%3A6d&ver=6.2.8";
public static final String TYPE_COMMENT = "type_comment";
public static final String TYPE_URL = "type_url";
public static final String COMMENT_TITLE = "comment_title";
public static final String COMMENT_ORGIN = "comment_orgin";
public static final String TEXT_CONTENT = "text_content";
public static final String DURATION_VIDEO = "duration_video";
public static final String PLAY_TIMES = "play_times";
public static final String VIDEO_THUMBS = "video_thumbs";
public static final String CONTENT_ID = "cotent_id";
}
|
完成了评论界面的开发,完成了应用的更新,完成了混淆和签名apk
|
app/src/main/java/io/agora/contract/utils/Constants.java
|
完成了评论界面的开发,完成了应用的更新,完成了混淆和签名apk
|
|
Java
|
mpl-2.0
|
dd40b172b99cb7507c1dd0f23778693fa8169a70
| 0
|
jentfoo/ambush,threadly/ambush
|
package org.threadly.load;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.threadly.concurrent.PriorityScheduler;
import org.threadly.concurrent.SubmitterExecutor;
import org.threadly.concurrent.TaskPriority;
import org.threadly.concurrent.future.ExecuteOnGetFutureTask;
import org.threadly.concurrent.future.FutureUtils;
import org.threadly.concurrent.future.ImmediateResultListenableFuture;
import org.threadly.concurrent.future.ListenableFuture;
import org.threadly.concurrent.future.SettableListenableFuture;
import org.threadly.concurrent.wrapper.limiter.RateLimiterExecutor;
import org.threadly.util.ArgumentVerifier;
import org.threadly.util.ExceptionUtils;
/**
* <p>This class handles the execution of a completely generated execution script.</p>
*
* @author jent - Mike Jensen
*/
public class ExecutableScript {
private static final int MAXIMUM_PRESTART_THREAD_COUNT = 1000;
protected final int neededThreadQty;
protected final ExecutionItem startExecutionItem;
protected final ScriptAssistant scriptAssistant;
/**
* Constructs a new {@link ExecutableScript}. If the minimum threads needed don't match the
* execution graph provided, it may restrict load, or never complete.
*
* Execution will not proceed to the next step until the previous step has fully completed.
*
* @param neededThreadQty Minimum number of threads to execute provided steps
* @param startExecutionItem Execution item which represents the script
*/
public ExecutableScript(int neededThreadQty, ExecutionItem startExecutionItem) {
if (! startExecutionItem.getChildItems().hasChildren()) {
throw new IllegalArgumentException("Can not construct script with no steps");
}
ArgumentVerifier.assertGreaterThanZero(neededThreadQty, "neededThreadQty");
this.neededThreadQty = neededThreadQty;
this.startExecutionItem = startExecutionItem;
scriptAssistant = new ScriptAssistant();
}
/**
* Returns how many threads will be started when the script is executed.
*
* @return Number of threads needed to run script as provided
*/
public int getThreadQtyNeeded() {
return neededThreadQty;
}
/**
* Starts the execution of the script. It will traverse through the execution graph an execute
* things as previously defined by using the builder.
*
* This returns a collection of futures. If an execution step was executed, the future will
* return a {@link StepResult}. That {@link StepResult} will indicate either a successful or
* failure in execution. If a failure does occur then future test steps will NOT be executed.
* If a step was never executed due to a failure, those futures will be resolved in an error
* (thus calls to {@link ListenableFuture#get()} will throw a
* {@link java.util.concurrent.ExecutionException}). You can use
* {@link StepResultCollectionUtils#getFailedResult(java.util.Collection)} to see if any steps failed.
* This will block till all steps have completed (or a failed test step occurred). If
* {@link StepResultCollectionUtils#getFailedResult(java.util.Collection)} returns null, then the test
* completed without error.
*
* @return A collection of futures which will represent each execution step
*/
public List<ListenableFuture<StepResult>> startScript() {
// copy result list to handle generics madness
final ArrayList<ListenableFuture<StepResult>> result = new ArrayList<ListenableFuture<StepResult>>(0);
startExecutionItem.prepareForRun();
result.addAll(startExecutionItem.getFutures());
result.trimToSize();
CharsDeduplicator.clearCache();
scriptAssistant.start(neededThreadQty + 1, result);
// perform a gc before starting execution so that we can run as smooth as possible
System.gc();
// TODO - move this to a regular class?
scriptAssistant.scheduler.get().execute(new Runnable() {
@Override
public void run() {
startExecutionItem.itemReadyForExecution(scriptAssistant);
// this call will block till the step is done, thus preventing execution of the next step
try {
if (StepResultCollectionUtils.getFailedResult(result) != null) {
FutureUtils.cancelIncompleteFutures(scriptAssistant.getGlobalRunningFutureSet(), true);
return;
}
} catch (InterruptedException e) {
// let thread exit
return;
} finally {
startExecutionItem.runComplete();
}
}
});
return result;
}
/**
* <p>Small class for managing access and needs from running script steps.</p>
*
* @author jent - Mike Jensen
*/
private static class ScriptAssistant implements ExecutionItem.ExecutionAssistant {
private final AtomicBoolean running;
private final AtomicReference<PriorityScheduler> scheduler;
private final AtomicReference<List<ListenableFuture<StepResult>>> futures;
private final AtomicBoolean markedFailure;
private final ArrayList<Runnable> failureListeners;
private volatile ListenableFuture<?> completionFuture;
private volatile SubmitterExecutor limiter;
private ScriptAssistant(ScriptAssistant scriptAssistant) {
running = scriptAssistant.running;
scheduler = scriptAssistant.scheduler;
futures = scriptAssistant.futures;
markedFailure = scriptAssistant.markedFailure;
failureListeners = scriptAssistant.failureListeners;
limiter = scriptAssistant.limiter;
completionFuture = scriptAssistant.completionFuture;
/* with the way FutureUtils works, the ListenableFuture made here wont be able to be
* garbage collected, even though we don't have a reference to it. Thus ensuring we
* cleanup our running references.
*/
completionFuture.addListener(new Runnable() {
@Override
public void run() {
limiter = null;
}
});
}
public ScriptAssistant() {
running = new AtomicBoolean(false);
scheduler = new AtomicReference<PriorityScheduler>(null);
futures = new AtomicReference<List<ListenableFuture<StepResult>>>(null);
markedFailure = new AtomicBoolean(false);
failureListeners = new ArrayList<Runnable>(1);
limiter = null;
}
@Override
public void registerFailureNotification(Runnable listener) {
synchronized (failureListeners) {
if (markedFailure.get()) {
try {
listener.run();
} catch (Throwable t) {
ExceptionUtils.handleException(t);
}
} else {
failureListeners.add(listener);
}
}
}
@Override
public void markGlobalFailure() {
if (! markedFailure.get() && markedFailure.compareAndSet(false, true)) {
synchronized (failureListeners) {
for (Runnable r : failureListeners) {
try {
r.run();
} catch (Throwable t) {
ExceptionUtils.handleException(t);
}
}
failureListeners.clear();
}
List<ListenableFuture<StepResult>> futures = this.futures.get();
if (futures != null) {
// try to short cut any steps we can
// Sadly this is a duplicate from other cancels, but since we are not garunteed to be
// able to cancel here, we still need those points
FutureUtils.cancelIncompleteFutures(futures, true);
}
}
}
@Override
public boolean getMarkedGlobalFailure() {
return markedFailure.get();
}
public void start(int threadPoolSize, List<ListenableFuture<StepResult>> futures) {
if (! running.compareAndSet(false, true)) {
throw new IllegalStateException("Already running");
}
PriorityScheduler ps;
if (threadPoolSize > MAXIMUM_PRESTART_THREAD_COUNT) {
ps = new PriorityScheduler(1000);
// just prestart the maximum, then allow the pool to grow beyond that
// if rate limiting is used, our actual needed thread count may be lower than this number
ps.prestartAllThreads();
ps.setPoolSize(threadPoolSize);
} else {
ps = new PriorityScheduler(threadPoolSize);
ps.prestartAllThreads();
}
scheduler.set(ps);
this.futures.set(Collections.unmodifiableList(futures));
/* with the way FutureUtils works, the ListenableFuture made here wont be able to be
* garbage collected, even though we don't have a reference to it. Thus ensuring we
* cleanup our running references.
*/
completionFuture = FutureUtils.makeCompleteFuture(futures);
completionFuture.addListener(new Runnable() {
@Override
public void run() {
scheduler.set(null);
limiter = null;
running.set(false);
}
});
synchronized (failureListeners) {
failureListeners.trimToSize();
}
}
@Override
public List<ListenableFuture<StepResult>> getGlobalRunningFutureSet() {
return futures.get();
}
@Override
public void executeAsyncMaintenanceTaskIfStillRunning(Runnable task) {
PriorityScheduler ps = scheduler.get();
if (ps != null) {
ps.execute(task, TaskPriority.Starvable);
}
}
@Override
public ListenableFuture<?> executeIfStillRunning(ExecutionItem item, boolean forceAsync) {
// the existence of the scheduler (and possibly limiter) indicate still running
SubmitterExecutor limiter = this.limiter;
if (limiter != null && ! item.isChainExecutor()) {
return limiter.submit(wrapInRunnable(item));
} else {
PriorityScheduler scheduler = this.scheduler.get();
if (scheduler != null) {
if (forceAsync) {
ExecuteOnGetFutureTask<?> result = new ExecuteOnGetFutureTask<Void>(wrapInRunnable(item));
scheduler.execute(result);
return result;
} else {
item.itemReadyForExecution(this);
}
}
}
return ImmediateResultListenableFuture.NULL_RESULT;
}
private Runnable wrapInRunnable(final ExecutionItem item) {
return new Runnable() {
@Override
public void run() {
item.itemReadyForExecution(ScriptAssistant.this);
}
};
}
@Override
public void setStepPerSecondLimit(double newLimit) {
if (newLimit <= 0) {
limiter = null;
} else {
PriorityScheduler scheduler = this.scheduler.get();
if (scheduler != null) {
limiter = new RateLimiterExecutor(scheduler, newLimit);
}
}
}
@Override
public ScriptAssistant makeCopy() {
return new ScriptAssistant(this);
}
}
/**
* <p>Interface for chain item, all items provided for execution must implement this interface.
* This will require test steps to be wrapped in a class which provides this functionality.</p>
*
* @author jent - Mike Jensen
*/
protected interface ExecutionItem {
/**
* Set a handler for when {@link #itemReadyForExecution(ExecutionAssistant)} is invoked. If a handler
* is set on a step, it is expected to defer to that handler, and NOT perform any further
* action.
*
* @param handler Handler to defer to, or {@code null} to unset handler
*/
public void setStartHandler(StepStartHandler handler);
/**
* Called to allow the {@link ExecutionItem} do any cleanup, or other operations needed to
* ensure a smooth invocation of {@link #itemReadyForExecution(ExecutionAssistant)}.
*/
public void prepareForRun();
public void runComplete();
/**
* Indicates the item is ready for execution. If a {@link StepStartHandler} is set, this
* invocation should defer to that. If it is not set, then the items execution should start.
* This may execute async on the provided {@link ExecutionAssistant}, but returned futures
* from {@link #getFutures()} should not complete until the chain item completes.
*
* @param assistant {@link ExecutionAssistant} which is performing the execution
*/
public void itemReadyForExecution(ExecutionAssistant assistant);
/**
* Check if this execution item directly applies changes to the provided
* {@link ExecutionAssistant}.
*
* @return {@code true} if the step manipulates the assistant
*/
public boolean manipulatesExecutionAssistant();
/**
* Check to see if this {@link ExecutionItem} is responsible for executing other items. A
* {@code true} here would indicate this is not a real step, but rather a point in the chain
* needed for the graph structure.
*
* @return {@code true} if synthetic step for chain execution
*/
public boolean isChainExecutor();
/**
* Returns the collection of futures which represent this test. There should be one future
* per test step. These futures should complete as their respective test steps complete.
*
* @return Collection of futures that provide results from their test steps
*/
public List<? extends SettableListenableFuture<StepResult>> getFutures();
/**
* Produces a copy of the item so that it can be run in another execution chain.
*
* @return A copy of the test item
*/
public ExecutionItem makeCopy();
/**
* Get information about if this {@link ExecutionItem} has child items it runs or not. This
* can be used to understand the graph structure for execution.
*
* @return A implementation of {@link ChildItems} to understand child execution
*/
// TODO - I don't like how we are constructing objects for this, can we avoid these calls?
public ChildItems getChildItems();
/**
* <p>Class which represents child items which may be executed by this instance of an
* {@link ExecutionItem}.</p>
*
* @author jent - Mike Jensen
*/
public interface ChildItems extends Iterable<ExecutionItem> {
/**
* Check to know if this item runs child items sequentially, waiting till one finishes
* before starting the next one.
*
* @return {@code true} if child items are run sequentially
*/
public boolean itemsRunSequential();
/**
* Check to see if this execution item runs other items.
*
* @return {@code true} if this {@link ExecutionItem} runs multiple {@link ExecutionItem}'s
*/
public boolean hasChildren();
/**
* Get an iterator which will iterate over the executable items. No modifications should be
* done through this iterator.
*
* @return Iterator of items that will be executed when this item is executed
*/
@Override
public Iterator<ExecutionItem> iterator();
}
/**
* <p>Class passed to the test item at the start of execution. This can provide information
* and facilities it can use to perform it's execution.</p>
*
* @author jent - Mike Jensen
*/
public interface ExecutionAssistant {
/**
* This farms off tasks on to another thread for execution. This may not execute if the script
* has already stopped (likely from an error or failed step). In those cases the task's future
* was already canceled so execution should not be needed.
*
* @param item ExecutionItem to be executed
* @param forceAsync {@code false} to potentially allow execution inside calling thread
* @return Future that will complete when runnable has finished running
*/
public ListenableFuture<?> executeIfStillRunning(ExecutionItem item, boolean forceAsync);
/**
* Call to get a asynchronously execute a maintenance task. Typically
* {@link #executeIfStillRunning(ExecutionItem, boolean)} should be the go-to execution point,
* but for internal tasks this can be used as well.
*
* @param task Task to be executed
*/
public void executeAsyncMaintenanceTaskIfStillRunning(Runnable task);
/**
* Changes what the limit is for how many steps per second are allowed to execute. Delays
* in step execution are NOT factored in step run time. Provide {@code 0} to set no limit
* and allow step execution to run as fast as possible.
*
* @param newLimit Limit of steps run per second
*/
public void setStepPerSecondLimit(double newLimit);
/**
* Returns the list of futures for the current test script run. If not currently running this
* will be null.
*
* @return List of futures that will complete for the current execution
*/
public List<ListenableFuture<StepResult>> getGlobalRunningFutureSet();
/**
* Copies this assistant. The copied assistant will be backed by the same scheduler and
* futures. However things which are chain sensitive (like the execution limit) will be
* copied in their initial state, but changes will not impact previous copies.
*
* @return A new assistant instance
*/
public ExecutionAssistant makeCopy();
/**
* Register a listener to be invoked if a failure occurs. This listener will be invoked
* when any steps within the script invoke {@link #markGlobalFailure()}.
*
* @param listener Listener to be invoked on failure
*/
public void registerFailureNotification(Runnable listener);
/**
* Mark the execution as failure. This will invoke listeners registered by
* {@link #registerFailureNotification(Runnable)}.
*/
public void markGlobalFailure();
/**
* Checks to see if {@link #markGlobalFailure()} has been invoked or not.
*
* @return {@code true} if the script has been marked as failure
*/
public boolean getMarkedGlobalFailure();
}
/**
* <p>Interface to be invoked if set on a step at start. This can be used for multiple
* reasons, one may to just get an indication that a step is ready to execute. Another may be
* to set a pre-run condition. Meaning that this could prevent step execution, and just be
* invoked to indicate that a step is ready to execute.</p>
*
* @author jent - Mike Jensen
*/
public interface StepStartHandler {
/**
* Invoked by the {@link ExecutionItem} when
* {@link ExecutionItem#itemReadyForExecution(ExecutionAssistant)} is invoked.
*
* @param step Step which is being invoked
* @param assistant Assistant the step is being invoked with
*/
public void readyToRun(ExecutionItem step, ExecutionAssistant assistant);
}
}
}
|
src/main/java/org/threadly/load/ExecutableScript.java
|
package org.threadly.load;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.threadly.concurrent.PriorityScheduler;
import org.threadly.concurrent.SubmitterExecutor;
import org.threadly.concurrent.TaskPriority;
import org.threadly.concurrent.future.ExecuteOnGetFutureTask;
import org.threadly.concurrent.future.FutureUtils;
import org.threadly.concurrent.future.ImmediateResultListenableFuture;
import org.threadly.concurrent.future.ListenableFuture;
import org.threadly.concurrent.future.SettableListenableFuture;
import org.threadly.concurrent.wrapper.limiter.RateLimiterExecutor;
import org.threadly.util.ArgumentVerifier;
import org.threadly.util.ExceptionUtils;
/**
* <p>This class handles the execution of a completely generated execution script.</p>
*
* @author jent - Mike Jensen
*/
public class ExecutableScript {
private static final int MAXIMUM_PRESTART_THREAD_COUNT = 1000;
protected final int neededThreadQty;
protected final ExecutionItem startExecutionItem;
protected final ScriptAssistant scriptAssistant;
/**
* Constructs a new {@link ExecutableScript}. If the minimum threads needed don't match the
* execution graph provided, it may restrict load, or never complete.
*
* Execution will not proceed to the next step until the previous step has fully completed.
*
* @param neededThreadQty Minimum number of threads to execute provided steps
* @param startExecutionItem Execution item which represents the script
*/
public ExecutableScript(int neededThreadQty, ExecutionItem startExecutionItem) {
if (! startExecutionItem.getChildItems().hasChildren()) {
throw new IllegalArgumentException("Can not construct script with no steps");
}
ArgumentVerifier.assertGreaterThanZero(neededThreadQty, "neededThreadQty");
this.neededThreadQty = neededThreadQty;
this.startExecutionItem = startExecutionItem;
scriptAssistant = new ScriptAssistant();
}
/**
* Returns how many threads will be started when the script is executed.
*
* @return Number of threads needed to run script as provided
*/
public int getThreadQtyNeeded() {
return neededThreadQty;
}
/**
* Starts the execution of the script. It will traverse through the execution graph an execute
* things as previously defined by using the builder.
*
* This returns a collection of futures. If an execution step was executed, the future will
* return a {@link StepResult}. That {@link StepResult} will indicate either a successful or
* failure in execution. If a failure does occur then future test steps will NOT be executed.
* If a step was never executed due to a failure, those futures will be resolved in an error
* (thus calls to {@link ListenableFuture#get()} will throw a
* {@link java.util.concurrent.ExecutionException}). You can use
* {@link StepResultCollectionUtils#getFailedResult(java.util.Collection)} to see if any steps failed.
* This will block till all steps have completed (or a failed test step occurred). If
* {@link StepResultCollectionUtils#getFailedResult(java.util.Collection)} returns null, then the test
* completed without error.
*
* @return A collection of futures which will represent each execution step
*/
public List<ListenableFuture<StepResult>> startScript() {
// copy result list to handle generics madness
final ArrayList<ListenableFuture<StepResult>> result = new ArrayList<ListenableFuture<StepResult>>(0);
startExecutionItem.prepareForRun();
result.addAll(startExecutionItem.getFutures());
result.trimToSize();
CharsDeduplicator.clearCache();
scriptAssistant.start(neededThreadQty + 1, result);
// perform a gc before starting execution so that we can run as smooth as possible
System.gc();
// TODO - move this to a regular class?
scriptAssistant.scheduler.get().execute(new Runnable() {
@Override
public void run() {
startExecutionItem.itemReadyForExecution(scriptAssistant);
// this call will block till the step is done, thus preventing execution of the next step
try {
if (StepResultCollectionUtils.getFailedResult(result) != null) {
FutureUtils.cancelIncompleteFutures(scriptAssistant.getGlobalRunningFutureSet(), true);
return;
}
} catch (InterruptedException e) {
// let thread exit
return;
} finally {
startExecutionItem.runComplete();
}
}
});
return result;
}
/**
* <p>Small class for managing access and needs from running script steps.</p>
*
* @author jent - Mike Jensen
*/
private static class ScriptAssistant implements ExecutionItem.ExecutionAssistant {
private final AtomicBoolean running;
private final AtomicReference<PriorityScheduler> scheduler;
private final AtomicReference<List<ListenableFuture<StepResult>>> futures;
private final AtomicBoolean markedFailure;
private final ArrayList<Runnable> failureListeners;
private volatile ListenableFuture<?> completionFuture;
private volatile SubmitterExecutor limiter;
private ScriptAssistant(ScriptAssistant scriptAssistant) {
running = scriptAssistant.running;
scheduler = scriptAssistant.scheduler;
futures = scriptAssistant.futures;
markedFailure = scriptAssistant.markedFailure;
failureListeners = scriptAssistant.failureListeners;
limiter = scriptAssistant.limiter;
completionFuture = scriptAssistant.completionFuture;
/* with the way FutureUtils works, the ListenableFuture made here wont be able to be
* garbage collected, even though we don't have a reference to it. Thus ensuring we
* cleanup our running references.
*/
completionFuture.addListener(new Runnable() {
@Override
public void run() {
limiter = null;
}
});
}
public ScriptAssistant() {
running = new AtomicBoolean(false);
scheduler = new AtomicReference<PriorityScheduler>(null);
futures = new AtomicReference<List<ListenableFuture<StepResult>>>(null);
markedFailure = new AtomicBoolean(false);
failureListeners = new ArrayList<Runnable>(1);
limiter = null;
}
@Override
public void registerFailureNotification(Runnable listener) {
synchronized (failureListeners) {
if (markedFailure.get()) {
ExceptionUtils.runRunnable(listener);
} else {
failureListeners.add(listener);
}
}
}
@Override
public void markGlobalFailure() {
if (! markedFailure.get() && markedFailure.compareAndSet(false, true)) {
synchronized (failureListeners) {
for (Runnable r : failureListeners) {
ExceptionUtils.runRunnable(r);
}
failureListeners.clear();
}
List<ListenableFuture<StepResult>> futures = this.futures.get();
if (futures != null) {
// try to short cut any steps we can
// Sadly this is a duplicate from other cancels, but since we are not garunteed to be
// able to cancel here, we still need those points
FutureUtils.cancelIncompleteFutures(futures, true);
}
}
}
@Override
public boolean getMarkedGlobalFailure() {
return markedFailure.get();
}
public void start(int threadPoolSize, List<ListenableFuture<StepResult>> futures) {
if (! running.compareAndSet(false, true)) {
throw new IllegalStateException("Already running");
}
PriorityScheduler ps;
if (threadPoolSize > MAXIMUM_PRESTART_THREAD_COUNT) {
ps = new PriorityScheduler(1000);
// just prestart the maximum, then allow the pool to grow beyond that
// if rate limiting is used, our actual needed thread count may be lower than this number
ps.prestartAllThreads();
ps.setPoolSize(threadPoolSize);
} else {
ps = new PriorityScheduler(threadPoolSize);
ps.prestartAllThreads();
}
scheduler.set(ps);
this.futures.set(Collections.unmodifiableList(futures));
/* with the way FutureUtils works, the ListenableFuture made here wont be able to be
* garbage collected, even though we don't have a reference to it. Thus ensuring we
* cleanup our running references.
*/
completionFuture = FutureUtils.makeCompleteFuture(futures);
completionFuture.addListener(new Runnable() {
@Override
public void run() {
scheduler.set(null);
limiter = null;
running.set(false);
}
});
synchronized (failureListeners) {
failureListeners.trimToSize();
}
}
@Override
public List<ListenableFuture<StepResult>> getGlobalRunningFutureSet() {
return futures.get();
}
@Override
public void executeAsyncMaintenanceTaskIfStillRunning(Runnable task) {
PriorityScheduler ps = scheduler.get();
if (ps != null) {
ps.execute(task, TaskPriority.Starvable);
}
}
@Override
public ListenableFuture<?> executeIfStillRunning(ExecutionItem item, boolean forceAsync) {
// the existence of the scheduler (and possibly limiter) indicate still running
SubmitterExecutor limiter = this.limiter;
if (limiter != null && ! item.isChainExecutor()) {
return limiter.submit(wrapInRunnable(item));
} else {
PriorityScheduler scheduler = this.scheduler.get();
if (scheduler != null) {
if (forceAsync) {
ExecuteOnGetFutureTask<?> result = new ExecuteOnGetFutureTask<Void>(wrapInRunnable(item));
scheduler.execute(result);
return result;
} else {
item.itemReadyForExecution(this);
}
}
}
return ImmediateResultListenableFuture.NULL_RESULT;
}
private Runnable wrapInRunnable(final ExecutionItem item) {
return new Runnable() {
@Override
public void run() {
item.itemReadyForExecution(ScriptAssistant.this);
}
};
}
@Override
public void setStepPerSecondLimit(double newLimit) {
if (newLimit <= 0) {
limiter = null;
} else {
PriorityScheduler scheduler = this.scheduler.get();
if (scheduler != null) {
limiter = new RateLimiterExecutor(scheduler, newLimit);
}
}
}
@Override
public ScriptAssistant makeCopy() {
return new ScriptAssistant(this);
}
}
/**
* <p>Interface for chain item, all items provided for execution must implement this interface.
* This will require test steps to be wrapped in a class which provides this functionality.</p>
*
* @author jent - Mike Jensen
*/
protected interface ExecutionItem {
/**
* Set a handler for when {@link #itemReadyForExecution(ExecutionAssistant)} is invoked. If a handler
* is set on a step, it is expected to defer to that handler, and NOT perform any further
* action.
*
* @param handler Handler to defer to, or {@code null} to unset handler
*/
public void setStartHandler(StepStartHandler handler);
/**
* Called to allow the {@link ExecutionItem} do any cleanup, or other operations needed to
* ensure a smooth invocation of {@link #itemReadyForExecution(ExecutionAssistant)}.
*/
public void prepareForRun();
public void runComplete();
/**
* Indicates the item is ready for execution. If a {@link StepStartHandler} is set, this
* invocation should defer to that. If it is not set, then the items execution should start.
* This may execute async on the provided {@link ExecutionAssistant}, but returned futures
* from {@link #getFutures()} should not complete until the chain item completes.
*
* @param assistant {@link ExecutionAssistant} which is performing the execution
*/
public void itemReadyForExecution(ExecutionAssistant assistant);
/**
* Check if this execution item directly applies changes to the provided
* {@link ExecutionAssistant}.
*
* @return {@code true} if the step manipulates the assistant
*/
public boolean manipulatesExecutionAssistant();
/**
* Check to see if this {@link ExecutionItem} is responsible for executing other items. A
* {@code true} here would indicate this is not a real step, but rather a point in the chain
* needed for the graph structure.
*
* @return {@code true} if synthetic step for chain execution
*/
public boolean isChainExecutor();
/**
* Returns the collection of futures which represent this test. There should be one future
* per test step. These futures should complete as their respective test steps complete.
*
* @return Collection of futures that provide results from their test steps
*/
public List<? extends SettableListenableFuture<StepResult>> getFutures();
/**
* Produces a copy of the item so that it can be run in another execution chain.
*
* @return A copy of the test item
*/
public ExecutionItem makeCopy();
/**
* Get information about if this {@link ExecutionItem} has child items it runs or not. This
* can be used to understand the graph structure for execution.
*
* @return A implementation of {@link ChildItems} to understand child execution
*/
// TODO - I don't like how we are constructing objects for this, can we avoid these calls?
public ChildItems getChildItems();
/**
* <p>Class which represents child items which may be executed by this instance of an
* {@link ExecutionItem}.</p>
*
* @author jent - Mike Jensen
*/
public interface ChildItems extends Iterable<ExecutionItem> {
/**
* Check to know if this item runs child items sequentially, waiting till one finishes
* before starting the next one.
*
* @return {@code true} if child items are run sequentially
*/
public boolean itemsRunSequential();
/**
* Check to see if this execution item runs other items.
*
* @return {@code true} if this {@link ExecutionItem} runs multiple {@link ExecutionItem}'s
*/
public boolean hasChildren();
/**
* Get an iterator which will iterate over the executable items. No modifications should be
* done through this iterator.
*
* @return Iterator of items that will be executed when this item is executed
*/
@Override
public Iterator<ExecutionItem> iterator();
}
/**
* <p>Class passed to the test item at the start of execution. This can provide information
* and facilities it can use to perform it's execution.</p>
*
* @author jent - Mike Jensen
*/
public interface ExecutionAssistant {
/**
* This farms off tasks on to another thread for execution. This may not execute if the script
* has already stopped (likely from an error or failed step). In those cases the task's future
* was already canceled so execution should not be needed.
*
* @param item ExecutionItem to be executed
* @param forceAsync {@code false} to potentially allow execution inside calling thread
* @return Future that will complete when runnable has finished running
*/
public ListenableFuture<?> executeIfStillRunning(ExecutionItem item, boolean forceAsync);
/**
* Call to get a asynchronously execute a maintenance task. Typically
* {@link #executeIfStillRunning(ExecutionItem, boolean)} should be the go-to execution point,
* but for internal tasks this can be used as well.
*
* @param task Task to be executed
*/
public void executeAsyncMaintenanceTaskIfStillRunning(Runnable task);
/**
* Changes what the limit is for how many steps per second are allowed to execute. Delays
* in step execution are NOT factored in step run time. Provide {@code 0} to set no limit
* and allow step execution to run as fast as possible.
*
* @param newLimit Limit of steps run per second
*/
public void setStepPerSecondLimit(double newLimit);
/**
* Returns the list of futures for the current test script run. If not currently running this
* will be null.
*
* @return List of futures that will complete for the current execution
*/
public List<ListenableFuture<StepResult>> getGlobalRunningFutureSet();
/**
* Copies this assistant. The copied assistant will be backed by the same scheduler and
* futures. However things which are chain sensitive (like the execution limit) will be
* copied in their initial state, but changes will not impact previous copies.
*
* @return A new assistant instance
*/
public ExecutionAssistant makeCopy();
/**
* Register a listener to be invoked if a failure occurs. This listener will be invoked
* when any steps within the script invoke {@link #markGlobalFailure()}.
*
* @param listener Listener to be invoked on failure
*/
public void registerFailureNotification(Runnable listener);
/**
* Mark the execution as failure. This will invoke listeners registered by
* {@link #registerFailureNotification(Runnable)}.
*/
public void markGlobalFailure();
/**
* Checks to see if {@link #markGlobalFailure()} has been invoked or not.
*
* @return {@code true} if the script has been marked as failure
*/
public boolean getMarkedGlobalFailure();
}
/**
* <p>Interface to be invoked if set on a step at start. This can be used for multiple
* reasons, one may to just get an indication that a step is ready to execute. Another may be
* to set a pre-run condition. Meaning that this could prevent step execution, and just be
* invoked to indicate that a step is ready to execute.</p>
*
* @author jent - Mike Jensen
*/
public interface StepStartHandler {
/**
* Invoked by the {@link ExecutionItem} when
* {@link ExecutionItem#itemReadyForExecution(ExecutionAssistant)} is invoked.
*
* @param step Step which is being invoked
* @param assistant Assistant the step is being invoked with
*/
public void readyToRun(ExecutionItem step, ExecutionAssistant assistant);
}
}
}
|
Update off deprecated ExceptionUtils api
|
src/main/java/org/threadly/load/ExecutableScript.java
|
Update off deprecated ExceptionUtils api
|
|
Java
|
agpl-3.0
|
1edaba865b1ac89e6a8f7551d294b9dd209c49c0
| 0
|
PeterWithers/temp-to-delete1,PeterWithers/temp-to-delete1,KinshipSoftware/KinOathKinshipArchiver,KinshipSoftware/KinOathKinshipArchiver
|
package nl.mpi.kinnate.ui.menu;
import javax.swing.JMenuBar;
import nl.mpi.kinnate.ui.window.AbstractDiagramManager;
/**
* Document : MainMenuBar
* Created on : Dec 6, 2011, 7:26:07 PM
* Author : Peter Withers
*/
public class MainMenuBar extends JMenuBar {
public MainMenuBar(AbstractDiagramManager abstractDiagramManager) {
this.add(new FileMenu(abstractDiagramManager));
this.add(new EditMenu(abstractDiagramManager));
this.add(new DiagramOptionsMenu(abstractDiagramManager));
this.add(new KinTermsMenu(abstractDiagramManager));
this.add(new ArchiveMenu(abstractDiagramManager));
this.add(new DiagramPanelsMenu(abstractDiagramManager));
this.add(new WindowMenu(abstractDiagramManager));
this.add(new HelpMenu(abstractDiagramManager));
}
}
|
desktop/src/main/java/nl/mpi/kinnate/ui/menu/MainMenuBar.java
|
package nl.mpi.kinnate.ui.menu;
import javax.swing.JMenuBar;
import nl.mpi.kinnate.ui.window.AbstractDiagramManager;
/**
* Document : MainMenuBar
* Created on : Dec 6, 2011, 7:26:07 PM
* Author : Peter Withers
*/
public class MainMenuBar extends JMenuBar {
public MainMenuBar(AbstractDiagramManager abstractDiagramManager) {
this.add(new FileMenu(abstractDiagramManager));
this.add(new EditMenu(abstractDiagramManager));
this.add(new DiagramPanelsMenu(abstractDiagramManager));
this.add(new DiagramOptionsMenu(abstractDiagramManager));
this.add(new KinTermsMenu(abstractDiagramManager));
this.add(new ArchiveMenu(abstractDiagramManager));
this.add(new WindowMenu(abstractDiagramManager));
}
}
|
Added sample diagram for the query syntax.
Added the help menu.
Reordered the main menu bar.
|
desktop/src/main/java/nl/mpi/kinnate/ui/menu/MainMenuBar.java
|
Added sample diagram for the query syntax. Added the help menu. Reordered the main menu bar.
|
|
Java
|
apache-2.0
|
d950dc1ae4c4d4327b887949f385c364f2006194
| 0
|
squanchy-dev/squanchy-android,squanchy-dev/squanchy-android,squanchy-dev/squanchy-android
|
package net.squanchy.support.system;
import org.joda.time.DateTime;
import org.joda.time.LocalDateTime;
public class CurrentTime {
public Long currentTimestamp() {
return System.currentTimeMillis();
}
public LocalDateTime currentLocalDateTime() {
return LocalDateTime.now();
}
}
|
app/src/main/java/net/squanchy/support/system/CurrentTime.java
|
package net.squanchy.support.system;
import org.joda.time.DateTime;
import org.joda.time.LocalDateTime;
public class CurrentTime {
public Long currentTimestamp() {
return System.currentTimeMillis();
}
public LocalDateTime currentLocalDateTime() {
return new DateTime(1491487091000L).toLocalDateTime();
}
}
|
Rollbacking change that shouldn’t been commited
|
app/src/main/java/net/squanchy/support/system/CurrentTime.java
|
Rollbacking change that shouldn’t been commited
|
|
Java
|
apache-2.0
|
9ff186bd4faaa784b0ba9bdd8980f9f9d41bd8f8
| 0
|
adrie4mac/commons-codec,mohanaraosv/commons-codec,mohanaraosv/commons-codec,adrie4mac/commons-codec,apache/commons-codec,adrie4mac/commons-codec,mohanaraosv/commons-codec,apache/commons-codec,apache/commons-codec
|
/*
* 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.commons.codec.binary;
import java.util.Arrays;
import org.apache.commons.codec.BinaryDecoder;
import org.apache.commons.codec.BinaryEncoder;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.EncoderException;
/**
* Abstract superclass for Base-N encoders and decoders.
*
* <p>
* This class is thread-safe.
* </p>
*
* @version $Id$
*/
public abstract class BaseNCodec implements BinaryEncoder, BinaryDecoder {
/**
* Holds thread context so classes can be thread-safe.
*
* This class is not itself thread-safe; each thread must allocate its own copy.
*
* @since 1.7
*/
static class Context {
/**
* Place holder for the bytes we're dealing with for our based logic.
* Bitwise operations store and extract the encoding or decoding from this variable.
*/
int ibitWorkArea;
/**
* Place holder for the bytes we're dealing with for our based logic.
* Bitwise operations store and extract the encoding or decoding from this variable.
*/
long lbitWorkArea;
/**
* Buffer for streaming.
*/
byte[] buffer;
/**
* Position where next character should be written in the buffer.
*/
int pos;
/**
* Position where next character should be read from the buffer.
*/
int readPos;
/**
* Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless,
* and must be thrown away.
*/
boolean eof;
/**
* Variable tracks how many characters have been written to the current line. Only used when encoding. We use
* it to make sure each encoded line never goes beyond lineLength (if lineLength > 0).
*/
int currentLinePos;
/**
* Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding. This
* variable helps track that.
*/
int modulus;
Context() {
}
/**
* Returns a String useful for debugging (especially within a debugger.)
*
* @return a String useful for debugging.
*/
@SuppressWarnings("boxing") // OK to ignore boxing here
@Override
public String toString() {
return String.format("%s[buffer=%s, currentLinePos=%s, eof=%s, ibitWorkArea=%s, lbitWorkArea=%s, " +
"modulus=%s, pos=%s, readPos=%s]", this.getClass().getSimpleName(), Arrays.toString(buffer),
currentLinePos, eof, ibitWorkArea, lbitWorkArea, modulus, pos, readPos);
}
}
/**
* EOF
*
* @since 1.7
*/
static final int EOF = -1;
/**
* MIME chunk size per RFC 2045 section 6.8.
*
* <p>
* The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
* equal signs.
* </p>
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
*/
public static final int MIME_CHUNK_SIZE = 76;
/**
* PEM chunk size per RFC 1421 section 4.3.2.4.
*
* <p>
* The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
* equal signs.
* </p>
*
* @see <a href="http://tools.ietf.org/html/rfc1421">RFC 1421 section 4.3.2.4</a>
*/
public static final int PEM_CHUNK_SIZE = 64;
private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2;
/**
* Defines the default buffer size - currently {@value}
* - must be large enough for at least one encoded block+separator
*/
private static final int DEFAULT_BUFFER_SIZE = 8192;
/** Mask used to extract 8 bits, used in decoding bytes */
protected static final int MASK_8BITS = 0xff;
/**
* Byte used to pad output.
*/
protected static final byte PAD_DEFAULT = '='; // Allow static access to default
protected final byte PAD = PAD_DEFAULT; // instance variable just in case it needs to vary later
/** Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32 */
private final int unencodedBlockSize;
/** Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32 */
private final int encodedBlockSize;
/**
* Chunksize for encoding. Not used when decoding.
* A value of zero or less implies no chunking of the encoded data.
* Rounded down to nearest multiple of encodedBlockSize.
*/
protected final int lineLength;
/**
* Size of chunk separator. Not used unless {@link #lineLength} > 0.
*/
private final int chunkSeparatorLength;
/**
* Note <code>lineLength</code> is rounded down to the nearest multiple of {@link #encodedBlockSize}
* If <code>chunkSeparatorLength</code> is zero, then chunking is disabled.
* @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3)
* @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4)
* @param lineLength if > 0, use chunking with a length <code>lineLength</code>
* @param chunkSeparatorLength the chunk separator length, if relevant
*/
protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize,
final int lineLength, final int chunkSeparatorLength) {
this.unencodedBlockSize = unencodedBlockSize;
this.encodedBlockSize = encodedBlockSize;
final boolean useChunking = lineLength > 0 && chunkSeparatorLength > 0;
this.lineLength = useChunking ? (lineLength / encodedBlockSize) * encodedBlockSize : 0;
this.chunkSeparatorLength = chunkSeparatorLength;
}
/**
* Returns true if this object has buffered data for reading.
*
* @param context the context to be used
* @return true if there is data still available for reading.
*/
boolean hasData(final Context context) { // package protected for access from I/O streams
return context.buffer != null;
}
/**
* Returns the amount of buffered data available for reading.
*
* @param context the context to be used
* @return The amount of buffered data available for reading.
*/
int available(final Context context) { // package protected for access from I/O streams
return context.buffer != null ? context.pos - context.readPos : 0;
}
/**
* Get the default buffer size. Can be overridden.
*
* @return {@link #DEFAULT_BUFFER_SIZE}
*/
protected int getDefaultBufferSize() {
return DEFAULT_BUFFER_SIZE;
}
/**
* Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}.
* @param context the context to be used
*/
private byte[] resizeBuffer(final Context context) {
if (context.buffer == null) {
context.buffer = new byte[getDefaultBufferSize()];
context.pos = 0;
context.readPos = 0;
} else {
final byte[] b = new byte[context.buffer.length * DEFAULT_BUFFER_RESIZE_FACTOR];
System.arraycopy(context.buffer, 0, b, 0, context.buffer.length);
context.buffer = b;
}
return context.buffer;
}
/**
* Ensure that the buffer has room for <code>size</code> bytes
*
* @param size minimum spare space required
* @param context the context to be used
*/
protected byte[] ensureBufferSize(final int size, final Context context){
if ((context.buffer == null) || (context.buffer.length < context.pos + size)){
return resizeBuffer(context);
}
return context.buffer;
}
/**
* Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail
* bytes. Returns how many bytes were actually extracted.
* <p>
* Package protected for access from I/O streams.
*
* @param b
* byte[] array to extract the buffered data into.
* @param bPos
* position in byte[] array to start extraction at.
* @param bAvail
* amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
* @param context
* the context to be used
* @return The number of bytes successfully extracted into the provided byte[] array.
*/
int readResults(final byte[] b, final int bPos, final int bAvail, final Context context) {
if (context.buffer != null) {
final int len = Math.min(available(context), bAvail);
System.arraycopy(context.buffer, context.readPos, b, bPos, len);
context.readPos += len;
if (context.readPos >= context.pos) {
context.buffer = null; // so hasData() will return false, and this method can return -1
}
return len;
}
return context.eof ? EOF : 0;
}
/**
* Checks if a byte value is whitespace or not.
* Whitespace is taken to mean: space, tab, CR, LF
* @param byteToCheck
* the byte to check
* @return true if byte is whitespace, false otherwise
*/
protected static boolean isWhiteSpace(final byte byteToCheck) {
switch (byteToCheck) {
case ' ' :
case '\n' :
case '\r' :
case '\t' :
return true;
default :
return false;
}
}
/**
* Encodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of
* the Encoder interface, and will throw an EncoderException if the supplied object is not of type byte[].
*
* @param obj
* Object to encode
* @return An object (of type byte[]) containing the Base-N encoded data which corresponds to the byte[] supplied.
* @throws EncoderException
* if the parameter supplied is not of type byte[]
*/
@Override
public Object encode(final Object obj) throws EncoderException {
if (!(obj instanceof byte[])) {
throw new EncoderException("Parameter supplied to Base-N encode is not a byte[]");
}
return encode((byte[]) obj);
}
/**
* Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet.
* Uses UTF8 encoding.
*
* @param pArray
* a byte array containing binary data
* @return A String containing only Base-N character data
*/
public String encodeToString(final byte[] pArray) {
return StringUtils.newStringUtf8(encode(pArray));
}
/**
* Encodes a byte[] containing binary data, into a String containing characters in the appropriate alphabet.
* Uses UTF8 encoding.
*
* @param pArray a byte array containing binary data
* @return String containing only character data in the appropriate alphabet.
*/
public String encodeAsString(final byte[] pArray){
return StringUtils.newStringUtf8(encode(pArray));
}
/**
* Decodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of
* the Decoder interface, and will throw a DecoderException if the supplied object is not of type byte[] or String.
*
* @param obj
* Object to decode
* @return An object (of type byte[]) containing the binary data which corresponds to the byte[] or String
* supplied.
* @throws DecoderException
* if the parameter supplied is not of type byte[]
*/
@Override
public Object decode(final Object obj) throws DecoderException {
if (obj instanceof byte[]) {
return decode((byte[]) obj);
} else if (obj instanceof String) {
return decode((String) obj);
} else {
throw new DecoderException("Parameter supplied to Base-N decode is not a byte[] or a String");
}
}
/**
* Decodes a String containing characters in the Base-N alphabet.
*
* @param pArray
* A String containing Base-N character data
* @return a byte array containing binary data
*/
public byte[] decode(final String pArray) {
return decode(StringUtils.getBytesUtf8(pArray));
}
/**
* Decodes a byte[] containing characters in the Base-N alphabet.
*
* @param pArray
* A byte array containing Base-N character data
* @return a byte array containing binary data
*/
@Override
public byte[] decode(final byte[] pArray) {
if (pArray == null || pArray.length == 0) {
return pArray;
}
final Context context = new Context();
decode(pArray, 0, pArray.length, context);
decode(pArray, 0, EOF, context); // Notify decoder of EOF.
final byte[] result = new byte[context.pos];
readResults(result, 0, result.length, context);
return result;
}
/**
* Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.
*
* @param pArray
* a byte array containing binary data
* @return A byte array containing only the basen alphabetic character data
*/
@Override
public byte[] encode(final byte[] pArray) {
if (pArray == null || pArray.length == 0) {
return pArray;
}
final Context context = new Context();
encode(pArray, 0, pArray.length, context);
encode(pArray, 0, EOF, context); // Notify encoder of EOF.
final byte[] buf = new byte[context.pos - context.readPos];
readResults(buf, 0, buf.length, context);
return buf;
}
// package protected for access from I/O streams
abstract void encode(byte[] pArray, int i, int length, Context context);
// package protected for access from I/O streams
abstract void decode(byte[] pArray, int i, int length, Context context);
/**
* Returns whether or not the <code>octet</code> is in the current alphabet.
* Does not allow whitespace or pad.
*
* @param value The value to test
*
* @return {@code true} if the value is defined in the current alphabet, {@code false} otherwise.
*/
protected abstract boolean isInAlphabet(byte value);
/**
* Tests a given byte array to see if it contains only valid characters within the alphabet.
* The method optionally treats whitespace and pad as valid.
*
* @param arrayOctet byte array to test
* @param allowWSPad if {@code true}, then whitespace and PAD are also allowed
*
* @return {@code true} if all bytes are valid characters in the alphabet or if the byte array is empty;
* {@code false}, otherwise
*/
public boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad) {
for (int i = 0; i < arrayOctet.length; i++) {
if (!isInAlphabet(arrayOctet[i]) &&
(!allowWSPad || (arrayOctet[i] != PAD) && !isWhiteSpace(arrayOctet[i]))) {
return false;
}
}
return true;
}
/**
* Tests a given String to see if it contains only valid characters within the alphabet.
* The method treats whitespace and PAD as valid.
*
* @param basen String to test
* @return {@code true} if all characters in the String are valid characters in the alphabet or if
* the String is empty; {@code false}, otherwise
* @see #isInAlphabet(byte[], boolean)
*/
public boolean isInAlphabet(final String basen) {
return isInAlphabet(StringUtils.getBytesUtf8(basen), true);
}
/**
* Tests a given byte array to see if it contains any characters within the alphabet or PAD.
*
* Intended for use in checking line-ending arrays
*
* @param arrayOctet
* byte array to test
* @return {@code true} if any byte is a valid character in the alphabet or PAD; {@code false} otherwise
*/
protected boolean containsAlphabetOrPad(final byte[] arrayOctet) {
if (arrayOctet == null) {
return false;
}
for (final byte element : arrayOctet) {
if (PAD == element || isInAlphabet(element)) {
return true;
}
}
return false;
}
/**
* Calculates the amount of space needed to encode the supplied array.
*
* @param pArray byte[] array which will later be encoded
*
* @return amount of space needed to encoded the supplied array.
* Returns a long since a max-len array will require > Integer.MAX_VALUE
*/
public long getEncodedLength(final byte[] pArray) {
// Calculate non-chunked size - rounded up to allow for padding
// cast to long is needed to avoid possibility of overflow
long len = ((pArray.length + unencodedBlockSize-1) / unencodedBlockSize) * (long) encodedBlockSize;
if (lineLength > 0) { // We're using chunking
// Round up to nearest multiple
len += ((len + lineLength-1) / lineLength) * chunkSeparatorLength;
}
return len;
}
}
|
src/main/java/org/apache/commons/codec/binary/BaseNCodec.java
|
/*
* 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.commons.codec.binary;
import java.util.Arrays;
import org.apache.commons.codec.BinaryDecoder;
import org.apache.commons.codec.BinaryEncoder;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.EncoderException;
/**
* Abstract superclass for Base-N encoders and decoders.
*
* <p>
* This class is thread-safe.
* </p>
*
* @version $Id$
*/
public abstract class BaseNCodec implements BinaryEncoder, BinaryDecoder {
/**
* Holds thread context so classes can be thread-safe.
*
* This class is not itself thread-safe; each thread must allocate its own copy.
*
* @since 1.7
*/
static class Context {
/**
* Place holder for the bytes we're dealing with for our based logic.
* Bitwise operations store and extract the encoding or decoding from this variable.
*/
int ibitWorkArea;
/**
* Place holder for the bytes we're dealing with for our based logic.
* Bitwise operations store and extract the encoding or decoding from this variable.
*/
long lbitWorkArea;
/**
* Buffer for streaming.
*/
byte[] buffer;
/**
* Position where next character should be written in the buffer.
*/
int pos;
/**
* Position where next character should be read from the buffer.
*/
int readPos;
/**
* Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless,
* and must be thrown away.
*/
boolean eof;
/**
* Variable tracks how many characters have been written to the current line. Only used when encoding. We use
* it to make sure each encoded line never goes beyond lineLength (if lineLength > 0).
*/
int currentLinePos;
/**
* Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding. This
* variable helps track that.
*/
int modulus;
Context() {
}
/**
* Returns a String useful for debugging (especially within a debugger.)
*
* @return a String useful for debugging.
*/
@SuppressWarnings("boxing") // OK to ignore boxing here
@Override
public String toString() {
return String.format("%s[buffer=%s, currentLinePos=%s, eof=%s, ibitWorkArea=%s, lbitWorkArea=%s, "
+ "modulus=%s, pos=%s, readPos=%s]", this.getClass().getSimpleName(), Arrays.toString(buffer),
currentLinePos, eof, ibitWorkArea, lbitWorkArea, modulus, pos, readPos);
}
}
/**
* EOF
*
* @since 1.7
*/
static final int EOF = -1;
/**
* MIME chunk size per RFC 2045 section 6.8.
*
* <p>
* The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
* equal signs.
* </p>
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
*/
public static final int MIME_CHUNK_SIZE = 76;
/**
* PEM chunk size per RFC 1421 section 4.3.2.4.
*
* <p>
* The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
* equal signs.
* </p>
*
* @see <a href="http://tools.ietf.org/html/rfc1421">RFC 1421 section 4.3.2.4</a>
*/
public static final int PEM_CHUNK_SIZE = 64;
private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2;
/**
* Defines the default buffer size - currently {@value}
* - must be large enough for at least one encoded block+separator
*/
private static final int DEFAULT_BUFFER_SIZE = 8192;
/** Mask used to extract 8 bits, used in decoding bytes */
protected static final int MASK_8BITS = 0xff;
/**
* Byte used to pad output.
*/
protected static final byte PAD_DEFAULT = '='; // Allow static access to default
protected final byte PAD = PAD_DEFAULT; // instance variable just in case it needs to vary later
/** Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32 */
private final int unencodedBlockSize;
/** Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32 */
private final int encodedBlockSize;
/**
* Chunksize for encoding. Not used when decoding.
* A value of zero or less implies no chunking of the encoded data.
* Rounded down to nearest multiple of encodedBlockSize.
*/
protected final int lineLength;
/**
* Size of chunk separator. Not used unless {@link #lineLength} > 0.
*/
private final int chunkSeparatorLength;
/**
* Note <code>lineLength</code> is rounded down to the nearest multiple of {@link #encodedBlockSize}
* If <code>chunkSeparatorLength</code> is zero, then chunking is disabled.
* @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3)
* @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4)
* @param lineLength if > 0, use chunking with a length <code>lineLength</code>
* @param chunkSeparatorLength the chunk separator length, if relevant
*/
protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize,
final int lineLength, final int chunkSeparatorLength) {
this.unencodedBlockSize = unencodedBlockSize;
this.encodedBlockSize = encodedBlockSize;
final boolean useChunking = lineLength > 0 && chunkSeparatorLength > 0;
this.lineLength = useChunking ? (lineLength / encodedBlockSize) * encodedBlockSize : 0;
this.chunkSeparatorLength = chunkSeparatorLength;
}
/**
* Returns true if this object has buffered data for reading.
*
* @param context the context to be used
* @return true if there is data still available for reading.
*/
boolean hasData(final Context context) { // package protected for access from I/O streams
return context.buffer != null;
}
/**
* Returns the amount of buffered data available for reading.
*
* @param context the context to be used
* @return The amount of buffered data available for reading.
*/
int available(final Context context) { // package protected for access from I/O streams
return context.buffer != null ? context.pos - context.readPos : 0;
}
/**
* Get the default buffer size. Can be overridden.
*
* @return {@link #DEFAULT_BUFFER_SIZE}
*/
protected int getDefaultBufferSize() {
return DEFAULT_BUFFER_SIZE;
}
/**
* Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}.
* @param context the context to be used
*/
private byte[] resizeBuffer(final Context context) {
if (context.buffer == null) {
context.buffer = new byte[getDefaultBufferSize()];
context.pos = 0;
context.readPos = 0;
} else {
final byte[] b = new byte[context.buffer.length * DEFAULT_BUFFER_RESIZE_FACTOR];
System.arraycopy(context.buffer, 0, b, 0, context.buffer.length);
context.buffer = b;
}
return context.buffer;
}
/**
* Ensure that the buffer has room for <code>size</code> bytes
*
* @param size minimum spare space required
* @param context the context to be used
*/
protected byte[] ensureBufferSize(final int size, final Context context){
if ((context.buffer == null) || (context.buffer.length < context.pos + size)){
return resizeBuffer(context);
}
return context.buffer;
}
/**
* Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail
* bytes. Returns how many bytes were actually extracted.
* <p>
* Package protected for access from I/O streams.
*
* @param b
* byte[] array to extract the buffered data into.
* @param bPos
* position in byte[] array to start extraction at.
* @param bAvail
* amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
* @param context
* the context to be used
* @return The number of bytes successfully extracted into the provided byte[] array.
*/
int readResults(final byte[] b, final int bPos, final int bAvail, final Context context) {
if (context.buffer != null) {
final int len = Math.min(available(context), bAvail);
System.arraycopy(context.buffer, context.readPos, b, bPos, len);
context.readPos += len;
if (context.readPos >= context.pos) {
context.buffer = null; // so hasData() will return false, and this method can return -1
}
return len;
}
return context.eof ? EOF : 0;
}
/**
* Checks if a byte value is whitespace or not.
* Whitespace is taken to mean: space, tab, CR, LF
* @param byteToCheck
* the byte to check
* @return true if byte is whitespace, false otherwise
*/
protected static boolean isWhiteSpace(final byte byteToCheck) {
switch (byteToCheck) {
case ' ' :
case '\n' :
case '\r' :
case '\t' :
return true;
default :
return false;
}
}
/**
* Encodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of
* the Encoder interface, and will throw an EncoderException if the supplied object is not of type byte[].
*
* @param obj
* Object to encode
* @return An object (of type byte[]) containing the Base-N encoded data which corresponds to the byte[] supplied.
* @throws EncoderException
* if the parameter supplied is not of type byte[]
*/
@Override
public Object encode(final Object obj) throws EncoderException {
if (!(obj instanceof byte[])) {
throw new EncoderException("Parameter supplied to Base-N encode is not a byte[]");
}
return encode((byte[]) obj);
}
/**
* Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet.
* Uses UTF8 encoding.
*
* @param pArray
* a byte array containing binary data
* @return A String containing only Base-N character data
*/
public String encodeToString(final byte[] pArray) {
return StringUtils.newStringUtf8(encode(pArray));
}
/**
* Encodes a byte[] containing binary data, into a String containing characters in the appropriate alphabet.
* Uses UTF8 encoding.
*
* @param pArray a byte array containing binary data
* @return String containing only character data in the appropriate alphabet.
*/
public String encodeAsString(final byte[] pArray){
return StringUtils.newStringUtf8(encode(pArray));
}
/**
* Decodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of
* the Decoder interface, and will throw a DecoderException if the supplied object is not of type byte[] or String.
*
* @param obj
* Object to decode
* @return An object (of type byte[]) containing the binary data which corresponds to the byte[] or String
* supplied.
* @throws DecoderException
* if the parameter supplied is not of type byte[]
*/
@Override
public Object decode(final Object obj) throws DecoderException {
if (obj instanceof byte[]) {
return decode((byte[]) obj);
} else if (obj instanceof String) {
return decode((String) obj);
} else {
throw new DecoderException("Parameter supplied to Base-N decode is not a byte[] or a String");
}
}
/**
* Decodes a String containing characters in the Base-N alphabet.
*
* @param pArray
* A String containing Base-N character data
* @return a byte array containing binary data
*/
public byte[] decode(final String pArray) {
return decode(StringUtils.getBytesUtf8(pArray));
}
/**
* Decodes a byte[] containing characters in the Base-N alphabet.
*
* @param pArray
* A byte array containing Base-N character data
* @return a byte array containing binary data
*/
@Override
public byte[] decode(final byte[] pArray) {
if (pArray == null || pArray.length == 0) {
return pArray;
}
final Context context = new Context();
decode(pArray, 0, pArray.length, context);
decode(pArray, 0, EOF, context); // Notify decoder of EOF.
final byte[] result = new byte[context.pos];
readResults(result, 0, result.length, context);
return result;
}
/**
* Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.
*
* @param pArray
* a byte array containing binary data
* @return A byte array containing only the basen alphabetic character data
*/
@Override
public byte[] encode(final byte[] pArray) {
if (pArray == null || pArray.length == 0) {
return pArray;
}
final Context context = new Context();
encode(pArray, 0, pArray.length, context);
encode(pArray, 0, EOF, context); // Notify encoder of EOF.
final byte[] buf = new byte[context.pos - context.readPos];
readResults(buf, 0, buf.length, context);
return buf;
}
// package protected for access from I/O streams
abstract void encode(byte[] pArray, int i, int length, Context context);
// package protected for access from I/O streams
abstract void decode(byte[] pArray, int i, int length, Context context);
/**
* Returns whether or not the <code>octet</code> is in the current alphabet.
* Does not allow whitespace or pad.
*
* @param value The value to test
*
* @return {@code true} if the value is defined in the current alphabet, {@code false} otherwise.
*/
protected abstract boolean isInAlphabet(byte value);
/**
* Tests a given byte array to see if it contains only valid characters within the alphabet.
* The method optionally treats whitespace and pad as valid.
*
* @param arrayOctet byte array to test
* @param allowWSPad if {@code true}, then whitespace and PAD are also allowed
*
* @return {@code true} if all bytes are valid characters in the alphabet or if the byte array is empty;
* {@code false}, otherwise
*/
public boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad) {
for (int i = 0; i < arrayOctet.length; i++) {
if (!isInAlphabet(arrayOctet[i]) &&
(!allowWSPad || (arrayOctet[i] != PAD) && !isWhiteSpace(arrayOctet[i]))) {
return false;
}
}
return true;
}
/**
* Tests a given String to see if it contains only valid characters within the alphabet.
* The method treats whitespace and PAD as valid.
*
* @param basen String to test
* @return {@code true} if all characters in the String are valid characters in the alphabet or if
* the String is empty; {@code false}, otherwise
* @see #isInAlphabet(byte[], boolean)
*/
public boolean isInAlphabet(final String basen) {
return isInAlphabet(StringUtils.getBytesUtf8(basen), true);
}
/**
* Tests a given byte array to see if it contains any characters within the alphabet or PAD.
*
* Intended for use in checking line-ending arrays
*
* @param arrayOctet
* byte array to test
* @return {@code true} if any byte is a valid character in the alphabet or PAD; {@code false} otherwise
*/
protected boolean containsAlphabetOrPad(final byte[] arrayOctet) {
if (arrayOctet == null) {
return false;
}
for (final byte element : arrayOctet) {
if (PAD == element || isInAlphabet(element)) {
return true;
}
}
return false;
}
/**
* Calculates the amount of space needed to encode the supplied array.
*
* @param pArray byte[] array which will later be encoded
*
* @return amount of space needed to encoded the supplied array.
* Returns a long since a max-len array will require > Integer.MAX_VALUE
*/
public long getEncodedLength(final byte[] pArray) {
// Calculate non-chunked size - rounded up to allow for padding
// cast to long is needed to avoid possibility of overflow
long len = ((pArray.length + unencodedBlockSize-1) / unencodedBlockSize) * (long) encodedBlockSize;
if (lineLength > 0) { // We're using chunking
// Round up to nearest multiple
len += ((len + lineLength-1) / lineLength) * chunkSeparatorLength;
}
return len;
}
}
|
Fix Checkstyle.
git-svn-id: cde5a1597f50f50feab6f72941f6b219c34291a1@1465182 13f79535-47bb-0310-9956-ffa450edef68
|
src/main/java/org/apache/commons/codec/binary/BaseNCodec.java
|
Fix Checkstyle.
|
|
Java
|
apache-2.0
|
d3b7bcc4aadf984311dd53a4df1b5c8e834197bb
| 0
|
bmitc/vaadin,fireflyc/vaadin,bmitc/vaadin,mstahv/framework,sitexa/vaadin,travisfw/vaadin,carrchang/vaadin,shahrzadmn/vaadin,Peppe/vaadin,fireflyc/vaadin,asashour/framework,kironapublic/vaadin,fireflyc/vaadin,cbmeeks/vaadin,mstahv/framework,peterl1084/framework,peterl1084/framework,peterl1084/framework,fireflyc/vaadin,Scarlethue/vaadin,Scarlethue/vaadin,peterl1084/framework,Scarlethue/vaadin,travisfw/vaadin,mstahv/framework,travisfw/vaadin,Legioth/vaadin,Darsstar/framework,asashour/framework,Flamenco/vaadin,shahrzadmn/vaadin,kironapublic/vaadin,udayinfy/vaadin,mittop/vaadin,jdahlstrom/vaadin.react,Peppe/vaadin,asashour/framework,oalles/vaadin,asashour/framework,Legioth/vaadin,Flamenco/vaadin,sitexa/vaadin,jdahlstrom/vaadin.react,jdahlstrom/vaadin.react,Scarlethue/vaadin,udayinfy/vaadin,Flamenco/vaadin,travisfw/vaadin,magi42/vaadin,carrchang/vaadin,jdahlstrom/vaadin.react,sitexa/vaadin,bmitc/vaadin,kironapublic/vaadin,mstahv/framework,peterl1084/framework,oalles/vaadin,Flamenco/vaadin,shahrzadmn/vaadin,carrchang/vaadin,mittop/vaadin,oalles/vaadin,cbmeeks/vaadin,Darsstar/framework,synes/vaadin,magi42/vaadin,shahrzadmn/vaadin,udayinfy/vaadin,synes/vaadin,travisfw/vaadin,bmitc/vaadin,udayinfy/vaadin,jdahlstrom/vaadin.react,kironapublic/vaadin,magi42/vaadin,oalles/vaadin,cbmeeks/vaadin,magi42/vaadin,mittop/vaadin,mittop/vaadin,sitexa/vaadin,Scarlethue/vaadin,Peppe/vaadin,shahrzadmn/vaadin,cbmeeks/vaadin,synes/vaadin,Darsstar/framework,Darsstar/framework,Peppe/vaadin,mstahv/framework,synes/vaadin,fireflyc/vaadin,udayinfy/vaadin,Darsstar/framework,sitexa/vaadin,Legioth/vaadin,synes/vaadin,kironapublic/vaadin,oalles/vaadin,asashour/framework,Legioth/vaadin,Peppe/vaadin,Legioth/vaadin,magi42/vaadin,carrchang/vaadin
|
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.dom.client.Style.Visibility;
import com.google.gwt.dom.client.TableCellElement;
import com.google.gwt.dom.client.TableRowElement;
import com.google.gwt.dom.client.TableSectionElement;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.dom.client.ScrollHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.Container;
import com.vaadin.terminal.gwt.client.Focusable;
import com.vaadin.terminal.gwt.client.MouseEventDetails;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.RenderSpace;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.ui.VScrollTable.VScrollTableBody.VScrollTableRow;
import com.vaadin.terminal.gwt.client.ui.dd.DDUtil;
import com.vaadin.terminal.gwt.client.ui.dd.VAbstractDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VAcceptCallback;
import com.vaadin.terminal.gwt.client.ui.dd.VDragAndDropManager;
import com.vaadin.terminal.gwt.client.ui.dd.VDragEvent;
import com.vaadin.terminal.gwt.client.ui.dd.VHasDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VTransferable;
import com.vaadin.terminal.gwt.client.ui.dd.VerticalDropLocation;
/**
* VScrollTable
*
* VScrollTable is a FlowPanel having two widgets in it: * TableHead component *
* ScrollPanel
*
* TableHead contains table's header and widgets + logic for resizing,
* reordering and hiding columns.
*
* ScrollPanel contains VScrollTableBody object which handles content. To save
* some bandwidth and to improve clients responsiveness with loads of data, in
* VScrollTableBody all rows are not necessary rendered. There are "spacers" in
* VScrollTableBody to use the exact same space as non-rendered rows would use.
* This way we can use seamlessly traditional scrollbars and scrolling to fetch
* more rows instead of "paging".
*
* In VScrollTable we listen to scroll events. On horizontal scrolling we also
* update TableHeads scroll position which has its scrollbars hidden. On
* vertical scroll events we will check if we are reaching the end of area where
* we have rows rendered and
*
* TODO implement unregistering for child components in Cells
*/
public class VScrollTable extends FlowPanel implements Table, ScrollHandler,
VHasDropHandler, KeyPressHandler, KeyDownHandler, FocusHandler,
BlurHandler, Focusable {
public static final String CLASSNAME = "v-table";
public static final String CLASSNAME_SELECTION_FOCUS = CLASSNAME + "-focus";
public static final String ITEM_CLICK_EVENT_ID = "itemClick";
public static final String HEADER_CLICK_EVENT_ID = "handleHeaderClick";
public static final String FOOTER_CLICK_EVENT_ID = "handleFooterClick";
public static final String COLUMN_RESIZE_EVENT_ID = "columnResize";
private static final double CACHE_RATE_DEFAULT = 2;
/**
* The default multi select mode where simple left clicks only selects one
* item, CTRL+left click selects multiple items and SHIFT-left click selects
* a range of items.
*/
private static final int MULTISELECT_MODE_DEFAULT = 0;
/**
* multiple of pagelength which component will cache when requesting more
* rows
*/
private double cache_rate = CACHE_RATE_DEFAULT;
/**
* fraction of pageLenght which can be scrolled without making new request
*/
private double cache_react_rate = 0.75 * cache_rate;
public static final char ALIGN_CENTER = 'c';
public static final char ALIGN_LEFT = 'b';
public static final char ALIGN_RIGHT = 'e';
private int firstRowInViewPort = 0;
private int pageLength = 15;
private int lastRequestedFirstvisible = 0; // to detect "serverside scroll"
protected boolean showRowHeaders = false;
private String[] columnOrder;
protected ApplicationConnection client;
protected String paintableId;
private boolean immediate;
private boolean nullSelectionAllowed = true;
private int selectMode = Table.SELECT_MODE_NONE;
private final HashSet<String> selectedRowKeys = new HashSet<String>();
/*
* These are used when jumping between pages when pressing Home and End
*/
private boolean selectLastItemInNextRender = false;
private boolean selectFirstItemInNextRender = false;
private boolean focusFirstItemInNextRender = false;
private boolean focusLastItemInNextRender = false;
/*
* The currently focused row
*/
private VScrollTableRow focusedRow;
/*
* Helper to store selection range start in when using the keyboard
*/
private VScrollTableRow selectionRangeStart;
/*
* Flag for notifying when the selection has changed and should be sent to
* the server
*/
private boolean selectionChanged = false;
/*
* The speed (in pixels) which the scrolling scrolls vertically/horizontally
*/
private int scrollingVelocity = 10;
private Timer scrollingVelocityTimer = null;;
/**
* Represents a select range of rows
*/
private class SelectionRange {
/**
* The starting key of the range
*/
private int startRowKey;
/**
* The ending key of the range
*/
private int endRowKey;
/**
* Constuctor.
*
* @param startRowKey
* The range start. Must be less than endRowKey
* @param endRowKey
* The range end. Must be bigger than startRowKey
*/
public SelectionRange(int startRowKey, int endRowKey) {
this.startRowKey = startRowKey;
this.endRowKey = endRowKey;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return startRowKey + "-" + endRowKey;
}
public boolean inRange(int key) {
return key >= startRowKey && key <= endRowKey;
}
public int getStartKey() {
return startRowKey;
}
public int getEndKey() {
return endRowKey;
}
};
private final HashSet<SelectionRange> selectedRowRanges = new HashSet<SelectionRange>();
private boolean initializedAndAttached = false;
/**
* Flag to indicate if a column width recalculation is needed due update.
*/
private boolean headerChangedDuringUpdate = false;
private final TableHead tHead = new TableHead();
private final TableFooter tFoot = new TableFooter();
private final FocusableScrollPanel scrollBodyPanel = new FocusableScrollPanel();
private int totalRows;
private Set<String> collapsedColumns;
private final RowRequestHandler rowRequestHandler;
private VScrollTableBody scrollBody;
private int firstvisible = 0;
private boolean sortAscending;
private String sortColumn;
private boolean columnReordering;
/**
* This map contains captions and icon urls for actions like: * "33_c" ->
* "Edit" * "33_i" -> "http://dom.com/edit.png"
*/
private final HashMap<Object, String> actionMap = new HashMap<Object, String>();
private String[] visibleColOrder;
private boolean initialContentReceived = false;
private Element scrollPositionElement;
private boolean enabled;
private boolean showColHeaders;
private boolean showColFooters;
/** flag to indicate that table body has changed */
private boolean isNewBody = true;
/*
* Read from the "recalcWidths" -attribute. When it is true, the table will
* recalculate the widths for columns - desirable in some cases. For #1983,
* marked experimental.
*/
boolean recalcWidths = false;
private final ArrayList<Panel> lazyUnregistryBag = new ArrayList<Panel>();
private String height;
private String width = "";
private boolean rendering = false;
private boolean hasFocus = false;
private int dragmode;
private int multiselectmode;
private int tabIndex;
public VScrollTable() {
scrollBodyPanel.setStyleName(CLASSNAME + "-body-wrapper");
/*
* Firefox auto-repeat works correctly only if we use a key press
* handler, other browsers handle it correctly when using a key down
* handler
*/
if (BrowserInfo.get().isGecko()) {
scrollBodyPanel.addKeyPressHandler(this);
} else {
scrollBodyPanel.addKeyDownHandler(this);
}
scrollBodyPanel.addFocusHandler(this);
scrollBodyPanel.addBlurHandler(this);
scrollBodyPanel.addScrollHandler(this);
scrollBodyPanel.setStyleName(CLASSNAME + "-body");
setStyleName(CLASSNAME);
add(tHead);
add(scrollBodyPanel);
add(tFoot);
rowRequestHandler = new RowRequestHandler();
/*
* We need to use the sinkEvents method to catch the keyUp events so we
* can cache a single shift. KeyUpHandler cannot do this.
*/
sinkEvents(Event.ONKEYUP);
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt.user
* .client.Event)
*/
@Override
public void onBrowserEvent(Event event) {
if (event.getTypeInt() == Event.ONKEYUP) {
if (event.getKeyCode() == KeyCodes.KEY_SHIFT) {
sendSelectedRows();
selectionRangeStart = null;
} else if ((event.getKeyCode() == getNavigationUpKey()
|| event.getKeyCode() == getNavigationDownKey()
|| event.getKeyCode() == getNavigationPageUpKey() || event
.getKeyCode() == getNavigationPageDownKey())
&& !event.getShiftKey()) {
sendSelectedRows();
if (scrollingVelocityTimer != null) {
scrollingVelocityTimer.cancel();
scrollingVelocityTimer = null;
scrollingVelocity = 10;
}
}
}
}
/**
* Fires a column resize event which sends the resize information to the
* server.
*
* @param columnId
* The columnId of the column which was resized
* @param originalWidth
* The width in pixels of the column before the resize event
* @param newWidth
* The width in pixels of the column after the resize event
*/
private void fireColumnResizeEvent(String columnId, int originalWidth,
int newWidth) {
client.updateVariable(paintableId, "columnResizeEventColumn", columnId,
false);
client.updateVariable(paintableId, "columnResizeEventPrev",
originalWidth, false);
client.updateVariable(paintableId, "columnResizeEventCurr", newWidth,
immediate);
}
/**
* Moves the focus one step down
*
* @return Returns true if succeeded
*/
private boolean moveFocusDown() {
return moveFocusDown(0);
}
/**
* Moves the focus down by 1+offset rows
*
* @return Returns true if succeeded, else false if the selection could not
* be move downwards
*/
private boolean moveFocusDown(int offset) {
if (isSelectable()) {
if (focusedRow == null && scrollBody.iterator().hasNext()) {
return setRowFocus((VScrollTableRow) scrollBody.iterator()
.next());
} else {
VScrollTableRow next = getNextRow(focusedRow, offset);
if (next != null) {
return setRowFocus(next);
}
}
}
return false;
}
/**
* Moves the selection one step up
*
* @return Returns true if succeeded
*/
private boolean moveFocusUp() {
return moveFocusUp(0);
}
/**
* Moves the focus row upwards
*
* @return Returns true if succeeded, else false if the selection could not
* be move upwards
*
*/
private boolean moveFocusUp(int offset) {
if (isSelectable()) {
if (focusedRow == null && scrollBody.iterator().hasNext()) {
return setRowFocus((VScrollTableRow) scrollBody.iterator()
.next());
} else {
VScrollTableRow prev = getPreviousRow(focusedRow, offset);
if (prev != null) {
return setRowFocus(prev);
}
}
}
return false;
}
/**
* Selects a row where the current selection head is
*
* @param ctrlSelect
* Is the selection a ctrl+selection
* @param shiftSelect
* Is the selection a shift+selection
* @return Returns truw
*/
private void selectFocusedRow(boolean ctrlSelect, boolean shiftSelect) {
if (focusedRow != null) {
// Arrows moves the selection and clears previous selections
if (isSelectable() && !ctrlSelect && !shiftSelect) {
deselectAll();
focusedRow.toggleSelection();
selectionRangeStart = focusedRow;
}
// Ctrl+arrows moves selection head
else if (isSelectable() && ctrlSelect && !shiftSelect) {
selectionRangeStart = focusedRow;
// No selection, only selection head is moved
}
// Shift+arrows selection selects a range
else if (selectMode == SELECT_MODE_MULTI && !ctrlSelect
&& shiftSelect) {
focusedRow.toggleShiftSelection(shiftSelect);
}
}
}
/**
* Sends the selection to the server if changed since the last update/visit.
*/
protected void sendSelectedRows() {
// Don't send anything if selection has not changed
if (!selectionChanged) {
return;
}
// Reset selection changed flag
selectionChanged = false;
// Note: changing the immediateness of this might require changes to
// "clickEvent" immediateness also.
if (multiselectmode == MULTISELECT_MODE_DEFAULT) {
// Convert ranges to a set of strings
Set<String> ranges = new HashSet<String>();
for (SelectionRange range : selectedRowRanges) {
ranges.add(range.toString());
}
// Send the selected row ranges
client.updateVariable(paintableId, "selectedRanges",
ranges.toArray(new String[selectedRowRanges.size()]), false);
}
// Send the selected rows
client.updateVariable(paintableId, "selected",
selectedRowKeys.toArray(new String[selectedRowKeys.size()]),
immediate);
}
/**
* Get the key that moves the selection head upwards. By default it is the
* up arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationUpKey() {
return KeyCodes.KEY_UP;
}
/**
* Get the key that moves the selection head downwards. By default it is the
* down arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationDownKey() {
return KeyCodes.KEY_DOWN;
}
/**
* Get the key that scrolls to the left in the table. By default it is the
* left arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationLeftKey() {
return KeyCodes.KEY_LEFT;
}
/**
* Get the key that scroll to the right on the table. By default it is the
* right arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationRightKey() {
return KeyCodes.KEY_RIGHT;
}
/**
* Get the key that selects an item in the table. By default it is the space
* bar key but by overriding this you can change the key to whatever you
* want.
*
* @return
*/
protected int getNavigationSelectKey() {
return 32;
}
/**
* Get the key the moves the selection one page up in the table. By default
* this is the Page Up key but by overriding this you can change the key to
* whatever you want.
*
* @return
*/
protected int getNavigationPageUpKey() {
return KeyCodes.KEY_PAGEUP;
}
/**
* Get the key the moves the selection one page down in the table. By
* default this is the Page Down key but by overriding this you can change
* the key to whatever you want.
*
* @return
*/
protected int getNavigationPageDownKey() {
return KeyCodes.KEY_PAGEDOWN;
}
/**
* Get the key the moves the selection to the beginning of the table. By
* default this is the Home key but by overriding this you can change the
* key to whatever you want.
*
* @return
*/
protected int getNavigationStartKey() {
return KeyCodes.KEY_HOME;
}
/**
* Get the key the moves the selection to the end of the table. By default
* this is the End key but by overriding this you can change the key to
* whatever you want.
*
* @return
*/
protected int getNavigationEndKey() {
return KeyCodes.KEY_END;
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.terminal.gwt.client.Paintable#updateFromUIDL(com.vaadin.terminal
* .gwt.client.UIDL, com.vaadin.terminal.gwt.client.ApplicationConnection)
*/
@SuppressWarnings("unchecked")
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
rendering = true;
/*
* We need to do this before updateComponent since updateComponent calls
* this.setHeight() which will calculate a new body height depending on
* the space available.
*/
if (uidl.hasAttribute("colfooters")) {
showColFooters = uidl.getBooleanAttribute("colfooters");
}
tFoot.setVisible(showColFooters);
if (client.updateComponent(this, uidl, true)) {
rendering = false;
return;
}
// we may have pending cache row fetch, cancel it. See #2136
rowRequestHandler.cancel();
enabled = !uidl.hasAttribute("disabled");
this.client = client;
paintableId = uidl.getStringAttribute("id");
immediate = uidl.getBooleanAttribute("immediate");
final int newTotalRows = uidl.getIntAttribute("totalrows");
if (newTotalRows != totalRows) {
if (scrollBody != null) {
if (totalRows == 0) {
tHead.clear();
tFoot.clear();
}
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
totalRows = newTotalRows;
}
dragmode = uidl.hasAttribute("dragmode") ? uidl
.getIntAttribute("dragmode") : 0;
tabIndex = uidl.hasAttribute("tabindex") ? uidl
.getIntAttribute("tabindex") : 0;
multiselectmode = uidl.hasAttribute("multiselectmode") ? uidl
.getIntAttribute("multiselectmode") : MULTISELECT_MODE_DEFAULT;
setCacheRate(uidl.hasAttribute("cr") ? uidl.getDoubleAttribute("cr")
: CACHE_RATE_DEFAULT);
recalcWidths = uidl.hasAttribute("recalcWidths");
if (recalcWidths) {
tHead.clear();
tFoot.clear();
}
if (uidl.hasAttribute("pagelength")) {
pageLength = uidl.getIntAttribute("pagelength");
} else {
// pagelenght is "0" meaning scrolling is turned off
pageLength = totalRows;
}
firstvisible = uidl.hasVariable("firstvisible") ? uidl
.getIntVariable("firstvisible") : 0;
if (firstvisible != lastRequestedFirstvisible && scrollBody != null) {
// received 'surprising' firstvisible from server: scroll there
firstRowInViewPort = firstvisible;
scrollBodyPanel.setScrollPosition((int) (firstvisible * scrollBody
.getRowHeight()));
}
showRowHeaders = uidl.getBooleanAttribute("rowheaders");
showColHeaders = uidl.getBooleanAttribute("colheaders");
nullSelectionAllowed = uidl.hasAttribute("nsa") ? uidl
.getBooleanAttribute("nsa") : true;
if (uidl.hasVariable("sortascending")) {
sortAscending = uidl.getBooleanVariable("sortascending");
sortColumn = uidl.getStringVariable("sortcolumn");
}
if (uidl.hasVariable("selected")) {
final Set<String> selectedKeys = uidl
.getStringArrayVariableAsSet("selected");
if (scrollBody != null) {
Iterator<Widget> iterator = scrollBody.iterator();
while (iterator.hasNext()) {
VScrollTableRow row = (VScrollTableRow) iterator.next();
boolean selected = selectedKeys.contains(row.getKey());
if (selected != row.isSelected()) {
row.toggleSelection();
}
}
}
}
if (uidl.hasAttribute("selectmode")) {
if (uidl.getBooleanAttribute("readonly")) {
selectMode = Table.SELECT_MODE_NONE;
} else if (uidl.getStringAttribute("selectmode").equals("multi")) {
selectMode = Table.SELECT_MODE_MULTI;
} else if (uidl.getStringAttribute("selectmode").equals("single")) {
selectMode = Table.SELECT_MODE_SINGLE;
} else {
selectMode = Table.SELECT_MODE_NONE;
}
}
if (uidl.hasVariable("columnorder")) {
columnReordering = true;
columnOrder = uidl.getStringArrayVariable("columnorder");
} else {
columnReordering = false;
columnOrder = null;
}
if (uidl.hasVariable("collapsedcolumns")) {
tHead.setColumnCollapsingAllowed(true);
collapsedColumns = uidl
.getStringArrayVariableAsSet("collapsedcolumns");
} else {
tHead.setColumnCollapsingAllowed(false);
}
UIDL rowData = null;
UIDL ac = null;
for (final Iterator it = uidl.getChildIterator(); it.hasNext();) {
final UIDL c = (UIDL) it.next();
if (c.getTag().equals("rows")) {
rowData = c;
} else if (c.getTag().equals("actions")) {
updateActionMap(c);
} else if (c.getTag().equals("visiblecolumns")) {
tHead.updateCellsFromUIDL(c);
tFoot.updateCellsFromUIDL(c);
} else if (c.getTag().equals("-ac")) {
ac = c;
}
}
if (ac == null) {
if (dropHandler != null) {
// remove dropHandler if not present anymore
dropHandler = null;
}
} else {
if (dropHandler == null) {
dropHandler = new VScrollTableDropHandler();
}
dropHandler.updateAcceptRules(ac);
}
updateHeader(uidl.getStringArrayAttribute("vcolorder"));
updateFooter(uidl.getStringArrayAttribute("vcolorder"));
if (!recalcWidths && initializedAndAttached) {
updateBody(rowData, uidl.getIntAttribute("firstrow"),
uidl.getIntAttribute("rows"));
if (headerChangedDuringUpdate) {
lazyAdjustColumnWidths.schedule(1);
} else {
// webkits may still bug with their disturbing scrollbar bug,
// See #3457
// run overflow fix for scrollable area
DeferredCommand.addCommand(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel
.getElement());
}
});
}
} else {
if (scrollBody != null) {
scrollBody.removeFromParent();
lazyUnregistryBag.add(scrollBody);
}
scrollBody = createScrollBody();
scrollBody.renderInitialRows(rowData,
uidl.getIntAttribute("firstrow"),
uidl.getIntAttribute("rows"));
scrollBodyPanel.add(scrollBody);
initialContentReceived = true;
if (isAttached()) {
sizeInit();
}
scrollBody.restoreRowVisibility();
}
if (selectMode == Table.SELECT_MODE_NONE) {
scrollBody.addStyleName(CLASSNAME + "-body-noselection");
} else {
scrollBody.removeStyleName(CLASSNAME + "-body-noselection");
}
hideScrollPositionAnnotation();
purgeUnregistryBag();
// selection is no in sync with server, avoid excessive server visits by
// clearing to flag used during the normal operation
selectionChanged = false;
// This is called when the Home button has been pressed and the pages
// changes
if (selectFirstItemInNextRender) {
selectFirstRenderedRow(false);
selectFirstItemInNextRender = false;
}
if (focusFirstItemInNextRender) {
selectFirstRenderedRow(true);
focusFirstItemInNextRender = false;
}
// This is called when the End button has been pressed and the pages
// changes
if (selectLastItemInNextRender) {
selectLastRenderedRow(false);
selectLastItemInNextRender = false;
}
if (focusLastItemInNextRender) {
selectLastRenderedRow(true);
focusLastItemInNextRender = false;
}
if (focusedRow != null) {
if (!focusedRow.isAttached()) {
// focused row has orphaned, can't focus
focusedRow = null;
if (SELECT_MODE_SINGLE == selectMode
&& selectedRowKeys.size() > 0) {
// try to focusa row currently selected and in viewport
String selectedRowKey = selectedRowKeys.iterator().next();
if (selectedRowKey != null) {
setRowFocus(getRenderedRowByKey(selectedRowKey));
}
}
// TODO what should happen in multiselect mode?
} else {
setRowFocus(getRenderedRowByKey(focusedRow.getKey()));
}
}
setProperTabIndex();
rendering = false;
headerChangedDuringUpdate = false;
// Ensure that the focus has not scrolled outside the viewport
if (focusedRow != null) {
ensureRowIsVisible(focusedRow);
}
}
protected VScrollTableBody createScrollBody() {
return new VScrollTableBody();
}
/**
* Selects the last rendered row in the table
*
* @param focusOnly
* Should the focus only be moved to the last row
*/
private void selectLastRenderedRow(boolean focusOnly) {
VScrollTableRow row = null;
Iterator<Widget> it = scrollBody.iterator();
while (it.hasNext()) {
row = (VScrollTableRow) it.next();
}
if (row != null) {
setRowFocus(row);
if (!focusOnly) {
deselectAll();
selectFocusedRow(false, false);
sendSelectedRows();
}
}
}
/**
* Selects the first rendered row
*
* @param focusOnly
* Should the focus only be moved to the first row
*/
private void selectFirstRenderedRow(boolean focusOnly) {
setRowFocus((VScrollTableRow) scrollBody.iterator().next());
if (!focusOnly) {
deselectAll();
selectFocusedRow(false, false);
sendSelectedRows();
}
}
private void setCacheRate(double d) {
if (cache_rate != d) {
cache_rate = d;
cache_react_rate = 0.75 * d;
}
}
/**
* Unregisters Paintables in "trashed" HasWidgets (IScrollTableBodys or
* IScrollTableRows). This is done lazily as Table must survive from
* "subtreecaching" logic.
*/
private void purgeUnregistryBag() {
for (Iterator<Panel> iterator = lazyUnregistryBag.iterator(); iterator
.hasNext();) {
client.unregisterChildPaintables(iterator.next());
}
lazyUnregistryBag.clear();
}
private void updateActionMap(UIDL c) {
final Iterator<?> it = c.getChildIterator();
while (it.hasNext()) {
final UIDL action = (UIDL) it.next();
final String key = action.getStringAttribute("key");
final String caption = action.getStringAttribute("caption");
actionMap.put(key + "_c", caption);
if (action.hasAttribute("icon")) {
// TODO need some uri handling ??
actionMap.put(key + "_i", client.translateVaadinUri(action
.getStringAttribute("icon")));
}
}
}
public String getActionCaption(String actionKey) {
return actionMap.get(actionKey + "_c");
}
public String getActionIcon(String actionKey) {
return actionMap.get(actionKey + "_i");
}
private void updateHeader(String[] strings) {
if (strings == null) {
return;
}
int visibleCols = strings.length;
int colIndex = 0;
if (showRowHeaders) {
tHead.enableColumn("0", colIndex);
visibleCols++;
visibleColOrder = new String[visibleCols];
visibleColOrder[colIndex] = "0";
colIndex++;
} else {
visibleColOrder = new String[visibleCols];
tHead.removeCell("0");
}
int i;
for (i = 0; i < strings.length; i++) {
final String cid = strings[i];
visibleColOrder[colIndex] = cid;
tHead.enableColumn(cid, colIndex);
colIndex++;
}
tHead.setVisible(showColHeaders);
setContainerHeight();
}
/**
* Updates footers.
* <p>
* Update headers whould be called before this method is called!
* </p>
*
* @param strings
*/
private void updateFooter(String[] strings) {
if (strings == null) {
return;
}
// Add dummy column if row headers are present
int colIndex = 0;
if (showRowHeaders) {
tFoot.enableColumn("0", colIndex);
colIndex++;
} else {
tFoot.removeCell("0");
}
int i;
for (i = 0; i < strings.length; i++) {
final String cid = strings[i];
tFoot.enableColumn(cid, colIndex);
colIndex++;
}
tFoot.setVisible(showColFooters);
}
/**
* @param uidl
* which contains row data
* @param firstRow
* first row in data set
* @param reqRows
* amount of rows in data set
*/
private void updateBody(UIDL uidl, int firstRow, int reqRows) {
if (uidl == null || reqRows < 1) {
// container is empty, remove possibly existing rows
if (firstRow < 0) {
while (scrollBody.getLastRendered() > scrollBody.firstRendered) {
scrollBody.unlinkRow(false);
}
scrollBody.unlinkRow(false);
}
return;
}
scrollBody.renderRows(uidl, firstRow, reqRows);
final int optimalFirstRow = (int) (firstRowInViewPort - pageLength
* cache_rate);
boolean cont = true;
while (cont && scrollBody.getLastRendered() > optimalFirstRow
&& scrollBody.getFirstRendered() < optimalFirstRow) {
// removing row from start
cont = scrollBody.unlinkRow(true);
}
final int optimalLastRow = (int) (firstRowInViewPort + pageLength + pageLength
* cache_rate);
cont = true;
while (cont && scrollBody.getLastRendered() > optimalLastRow) {
// removing row from the end
cont = scrollBody.unlinkRow(false);
}
scrollBody.fixSpacers();
scrollBody.restoreRowVisibility();
}
/**
* Gives correct column index for given column key ("cid" in UIDL).
*
* @param colKey
* @return column index of visible columns, -1 if column not visible
*/
private int getColIndexByKey(String colKey) {
// return 0 if asked for rowHeaders
if ("0".equals(colKey)) {
return 0;
}
for (int i = 0; i < visibleColOrder.length; i++) {
if (visibleColOrder[i].equals(colKey)) {
return i;
}
}
return -1;
}
protected boolean isSelectable() {
return selectMode > Table.SELECT_MODE_NONE;
}
private boolean isCollapsedColumn(String colKey) {
if (collapsedColumns == null) {
return false;
}
if (collapsedColumns.contains(colKey)) {
return true;
}
return false;
}
private String getColKeyByIndex(int index) {
return tHead.getHeaderCell(index).getColKey();
}
private void setColWidth(int colIndex, int w, boolean isDefinedWidth) {
// Set header column width
final HeaderCell hcell = tHead.getHeaderCell(colIndex);
hcell.setWidth(w, isDefinedWidth);
// Set body column width
scrollBody.setColWidth(colIndex, w);
// Set footer column width
FooterCell fcell = tFoot.getFooterCell(colIndex);
fcell.setWidth(w, isDefinedWidth);
}
private int getColWidth(String colKey) {
return tHead.getHeaderCell(colKey).getWidth();
}
/**
* Get a rendered row by its key
*
* @param key
* The key to search with
* @return
*/
private VScrollTableRow getRenderedRowByKey(String key) {
if (scrollBody != null) {
final Iterator<Widget> it = scrollBody.iterator();
VScrollTableRow r = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (r.getKey().equals(key)) {
return r;
}
}
}
return null;
}
/**
* Returns the next row to the given row
*
* @param row
* The row to calculate from
*
* @return The next row or null if no row exists
*/
private VScrollTableRow getNextRow(VScrollTableRow row, int offset) {
final Iterator<Widget> it = scrollBody.iterator();
VScrollTableRow r = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (r == row) {
r = null;
while (offset >= 0 && it.hasNext()) {
r = (VScrollTableRow) it.next();
offset--;
}
return r;
}
}
return null;
}
/**
* Returns the previous row from the given row
*
* @param row
* The row to calculate from
* @return The previous row or null if no row exists
*/
private VScrollTableRow getPreviousRow(VScrollTableRow row, int offset) {
final Iterator<Widget> it = scrollBody.iterator();
final Iterator<Widget> offsetIt = scrollBody.iterator();
VScrollTableRow r = null;
VScrollTableRow prev = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (offset < 0) {
prev = (VScrollTableRow) offsetIt.next();
}
if (r == row) {
return prev;
}
offset--;
}
return null;
}
protected void reOrderColumn(String columnKey, int newIndex) {
final int oldIndex = getColIndexByKey(columnKey);
// Change header order
tHead.moveCell(oldIndex, newIndex);
// Change body order
scrollBody.moveCol(oldIndex, newIndex);
// Change footer order
tFoot.moveCell(oldIndex, newIndex);
/*
* Build new columnOrder and update it to server Note that columnOrder
* also contains collapsed columns so we cannot directly build it from
* cells vector Loop the old columnOrder and append in order to new
* array unless on moved columnKey. On new index also put the moved key
* i == index on columnOrder, j == index on newOrder
*/
final String oldKeyOnNewIndex = visibleColOrder[newIndex];
if (showRowHeaders) {
newIndex--; // columnOrder don't have rowHeader
}
// add back hidden rows,
for (int i = 0; i < columnOrder.length; i++) {
if (columnOrder[i].equals(oldKeyOnNewIndex)) {
break; // break loop at target
}
if (isCollapsedColumn(columnOrder[i])) {
newIndex++;
}
}
// finally we can build the new columnOrder for server
final String[] newOrder = new String[columnOrder.length];
for (int i = 0, j = 0; j < newOrder.length; i++) {
if (j == newIndex) {
newOrder[j] = columnKey;
j++;
}
if (i == columnOrder.length) {
break;
}
if (columnOrder[i].equals(columnKey)) {
continue;
}
newOrder[j] = columnOrder[i];
j++;
}
columnOrder = newOrder;
// also update visibleColumnOrder
int i = showRowHeaders ? 1 : 0;
for (int j = 0; j < newOrder.length; j++) {
final String cid = newOrder[j];
if (!isCollapsedColumn(cid)) {
visibleColOrder[i++] = cid;
}
}
client.updateVariable(paintableId, "columnorder", columnOrder, false);
}
@Override
protected void onAttach() {
super.onAttach();
if (initialContentReceived) {
sizeInit();
}
}
@Override
protected void onDetach() {
rowRequestHandler.cancel();
super.onDetach();
// ensure that scrollPosElement will be detached
if (scrollPositionElement != null) {
final Element parent = DOM.getParent(scrollPositionElement);
if (parent != null) {
DOM.removeChild(parent, scrollPositionElement);
}
}
}
/**
* Run only once when component is attached and received its initial
* content. This function : * Syncs headers and bodys "natural widths and
* saves the values. * Sets proper width and height * Makes deferred request
* to get some cache rows
*/
private void sizeInit() {
/*
* We will use browsers table rendering algorithm to find proper column
* widths. If content and header take less space than available, we will
* divide extra space relatively to each column which has not width set.
*
* Overflow pixels are added to last column.
*/
Iterator<Widget> headCells = tHead.iterator();
Iterator<Widget> footCells = tFoot.iterator();
int i = 0;
int totalExplicitColumnsWidths = 0;
int total = 0;
float expandRatioDivider = 0;
final int[] widths = new int[tHead.visibleCells.size()];
tHead.enableBrowserIntelligence();
tFoot.enableBrowserIntelligence();
// first loop: collect natural widths
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
final FooterCell fCell = (FooterCell) footCells.next();
int w = hCell.getWidth();
if (hCell.isDefinedWidth()) {
// server has defined column width explicitly
totalExplicitColumnsWidths += w;
} else {
if (hCell.getExpandRatio() > 0) {
expandRatioDivider += hCell.getExpandRatio();
w = 0;
} else {
// get and store greater of header width and column width,
// and
// store it as a minimumn natural col width
int headerWidth = hCell.getNaturalColumnWidth(i);
int footerWidth = fCell.getNaturalColumnWidth(i);
w = headerWidth > footerWidth ? headerWidth : footerWidth;
}
hCell.setNaturalMinimumColumnWidth(w);
fCell.setNaturalMinimumColumnWidth(w);
}
widths[i] = w;
total += w;
i++;
}
tHead.disableBrowserIntelligence();
tFoot.disableBrowserIntelligence();
boolean willHaveScrollbarz = willHaveScrollbars();
// fix "natural" width if width not set
if (width == null || "".equals(width)) {
int w = total;
w += scrollBody.getCellExtraWidth() * visibleColOrder.length;
if (willHaveScrollbarz) {
w += Util.getNativeScrollbarSize();
}
setContentWidth(w);
}
int availW = scrollBody.getAvailableWidth();
if (BrowserInfo.get().isIE()) {
// Hey IE, are you really sure about this?
availW = scrollBody.getAvailableWidth();
}
availW -= scrollBody.getCellExtraWidth() * visibleColOrder.length;
if (willHaveScrollbarz) {
availW -= Util.getNativeScrollbarSize();
}
// TODO refactor this code to be the same as in resize timer
boolean needsReLayout = false;
if (availW > total) {
// natural size is smaller than available space
final int extraSpace = availW - total;
final int totalWidthR = total - totalExplicitColumnsWidths;
needsReLayout = true;
if (expandRatioDivider > 0) {
// visible columns have some active expand ratios, excess
// space is divided according to them
headCells = tHead.iterator();
i = 0;
while (headCells.hasNext()) {
HeaderCell hCell = (HeaderCell) headCells.next();
if (hCell.getExpandRatio() > 0) {
int w = widths[i];
final int newSpace = (int) (extraSpace * (hCell
.getExpandRatio() / expandRatioDivider));
w += newSpace;
widths[i] = w;
}
i++;
}
} else if (totalWidthR > 0) {
// no expand ratios defined, we will share extra space
// relatively to "natural widths" among those without
// explicit width
headCells = tHead.iterator();
i = 0;
while (headCells.hasNext()) {
HeaderCell hCell = (HeaderCell) headCells.next();
if (!hCell.isDefinedWidth()) {
int w = widths[i];
final int newSpace = extraSpace * w / totalWidthR;
w += newSpace;
widths[i] = w;
}
i++;
}
}
} else {
// bodys size will be more than available and scrollbar will appear
}
// last loop: set possibly modified values or reset if new tBody
i = 0;
headCells = tHead.iterator();
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
if (isNewBody || hCell.getWidth() == -1) {
final int w = widths[i];
setColWidth(i, w, false);
}
i++;
}
initializedAndAttached = true;
if (needsReLayout) {
scrollBody.reLayoutComponents();
}
updatePageLength();
/*
* Fix "natural" height if height is not set. This must be after width
* fixing so the components' widths have been adjusted.
*/
if (height == null || "".equals(height)) {
/*
* We must force an update of the row height as this point as it
* might have been (incorrectly) calculated earlier
*/
int bodyHeight;
if (pageLength == totalRows) {
/*
* A hack to support variable height rows when paging is off.
* Generally this is not supported by scrolltable. We want to
* show all rows so the bodyHeight should be equal to the table
* height.
*/
// int bodyHeight = scrollBody.getOffsetHeight();
bodyHeight = scrollBody.getRequiredHeight();
} else {
bodyHeight = (int) Math.round(scrollBody.getRowHeight(true)
* pageLength);
}
boolean needsSpaceForHorizontalSrollbar = (total > availW);
if (needsSpaceForHorizontalSrollbar) {
bodyHeight += Util.getNativeScrollbarSize();
}
scrollBodyPanel.setHeight(bodyHeight + "px");
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
isNewBody = false;
if (firstvisible > 0) {
// Deferred due some Firefox oddities. IE & Safari could survive
// without
DeferredCommand.addCommand(new Command() {
public void execute() {
scrollBodyPanel
.setScrollPosition((int) (firstvisible * scrollBody
.getRowHeight()));
firstRowInViewPort = firstvisible;
}
});
}
if (enabled) {
// Do we need cache rows
if (scrollBody.getLastRendered() + 1 < firstRowInViewPort
+ pageLength + (int) cache_react_rate * pageLength) {
if (totalRows - 1 > scrollBody.getLastRendered()) {
// fetch cache rows
int firstInNewSet = scrollBody.getLastRendered() + 1;
rowRequestHandler.setReqFirstRow(firstInNewSet);
int lastInNewSet = (int) (firstRowInViewPort + pageLength + cache_rate
* pageLength);
if (lastInNewSet > totalRows - 1) {
lastInNewSet = totalRows - 1;
}
rowRequestHandler.setReqRows(lastInNewSet - firstInNewSet
+ 1);
rowRequestHandler.deferRowFetch(1);
}
}
}
/*
* Ensures the column alignments are correct at initial loading. <br/>
* (child components widths are correct)
*/
scrollBody.reLayoutComponents();
DeferredCommand.addCommand(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
});
}
/**
* Note, this method is not official api although declared as protected.
* Extend at you own risk.
*
* @return true if content area will have scrollbars visible.
*/
protected boolean willHaveScrollbars() {
if (!(height != null && !height.equals(""))) {
if (pageLength < totalRows) {
return true;
}
} else {
int fakeheight = (int) Math.round(scrollBody.getRowHeight()
* totalRows);
int availableHeight = scrollBodyPanel.getElement().getPropertyInt(
"clientHeight");
if (fakeheight > availableHeight) {
return true;
}
}
return false;
}
private void announceScrollPosition() {
if (scrollPositionElement == null) {
scrollPositionElement = DOM.createDiv();
scrollPositionElement.setClassName(CLASSNAME + "-scrollposition");
scrollPositionElement.getStyle().setPosition(Position.ABSOLUTE);
scrollPositionElement.getStyle().setDisplay(Display.NONE);
getElement().appendChild(scrollPositionElement);
}
Style style = scrollPositionElement.getStyle();
style.setMarginLeft(getElement().getOffsetWidth() / 2 - 80, Unit.PX);
style.setMarginTop(-scrollBodyPanel.getOffsetHeight(), Unit.PX);
// indexes go from 1-totalRows, as rowheaders in index-mode indicate
int last = (firstRowInViewPort + pageLength);
if (last > totalRows) {
last = totalRows;
}
scrollPositionElement.setInnerHTML("<span>" + (firstRowInViewPort + 1)
+ " – " + (last) + "..." + "</span>");
style.setDisplay(Display.BLOCK);
}
private void hideScrollPositionAnnotation() {
if (scrollPositionElement != null) {
DOM.setStyleAttribute(scrollPositionElement, "display", "none");
}
}
private class RowRequestHandler extends Timer {
private int reqFirstRow = 0;
private int reqRows = 0;
public void deferRowFetch() {
deferRowFetch(250);
}
public void deferRowFetch(int msec) {
if (reqRows > 0 && reqFirstRow < totalRows) {
schedule(msec);
// tell scroll position to user if currently "visible" rows are
// not rendered
if ((firstRowInViewPort + pageLength > scrollBody
.getLastRendered())
|| (firstRowInViewPort < scrollBody.getFirstRendered())) {
announceScrollPosition();
} else {
hideScrollPositionAnnotation();
}
}
}
public void setReqFirstRow(int reqFirstRow) {
if (reqFirstRow < 0) {
reqFirstRow = 0;
} else if (reqFirstRow >= totalRows) {
reqFirstRow = totalRows - 1;
}
this.reqFirstRow = reqFirstRow;
}
public void setReqRows(int reqRows) {
this.reqRows = reqRows;
}
@Override
public void run() {
if (client.hasActiveRequest()) {
// if client connection is busy, don't bother loading it more
schedule(250);
} else {
int firstToBeRendered = scrollBody.firstRendered;
if (reqFirstRow < firstToBeRendered) {
firstToBeRendered = reqFirstRow;
} else if (firstRowInViewPort - (int) (cache_rate * pageLength) > firstToBeRendered) {
firstToBeRendered = firstRowInViewPort
- (int) (cache_rate * pageLength);
if (firstToBeRendered < 0) {
firstToBeRendered = 0;
}
}
int lastToBeRendered = scrollBody.lastRendered;
if (reqFirstRow + reqRows - 1 > lastToBeRendered) {
lastToBeRendered = reqFirstRow + reqRows - 1;
} else if (firstRowInViewPort + pageLength + pageLength
* cache_rate < lastToBeRendered) {
lastToBeRendered = (firstRowInViewPort + pageLength + (int) (pageLength * cache_rate));
if (lastToBeRendered >= totalRows) {
lastToBeRendered = totalRows - 1;
}
// due Safari 3.1 bug (see #2607), verify reqrows, original
// problem unknown, but this should catch the issue
if (reqFirstRow + reqRows - 1 > lastToBeRendered) {
reqRows = lastToBeRendered - reqFirstRow;
}
}
client.updateVariable(paintableId, "firstToBeRendered",
firstToBeRendered, false);
client.updateVariable(paintableId, "lastToBeRendered",
lastToBeRendered, false);
// remember which firstvisible we requested, in case the server
// has
// a differing opinion
lastRequestedFirstvisible = firstRowInViewPort;
client.updateVariable(paintableId, "firstvisible",
firstRowInViewPort, false);
client.updateVariable(paintableId, "reqfirstrow", reqFirstRow,
false);
client.updateVariable(paintableId, "reqrows", reqRows, true);
}
}
public int getReqFirstRow() {
return reqFirstRow;
}
public int getReqRows() {
return reqRows;
}
/**
* Sends request to refresh content at this position.
*/
public void refreshContent() {
int first = (int) (firstRowInViewPort - pageLength * cache_rate);
int reqRows = (int) (2 * pageLength * cache_rate + pageLength);
if (first < 0) {
reqRows = reqRows + first;
first = 0;
}
setReqFirstRow(first);
setReqRows(reqRows);
run();
}
}
public class HeaderCell extends Widget {
Element td = DOM.createTD();
Element captionContainer = DOM.createDiv();
Element colResizeWidget = DOM.createDiv();
Element floatingCopyOfHeaderCell;
private boolean sortable = false;
private final String cid;
private boolean dragging;
private int dragStartX;
private int colIndex;
private int originalWidth;
private boolean isResizing;
private int headerX;
private boolean moved;
private int closestSlot;
private int width = -1;
private int naturalWidth = -1;
private char align = ALIGN_LEFT;
boolean definedWidth = false;
private float expandRatio = 0;
public void setSortable(boolean b) {
sortable = b;
}
public void setNaturalMinimumColumnWidth(int w) {
naturalWidth = w;
}
public HeaderCell(String colId, String headerText) {
cid = colId;
DOM.setElementProperty(colResizeWidget, "className", CLASSNAME
+ "-resizer");
DOM.sinkEvents(colResizeWidget, Event.MOUSEEVENTS);
setText(headerText);
DOM.appendChild(td, colResizeWidget);
DOM.setElementProperty(captionContainer, "className", CLASSNAME
+ "-caption-container");
// ensure no clipping initially (problem on column additions)
DOM.setStyleAttribute(captionContainer, "overflow", "visible");
DOM.sinkEvents(captionContainer, Event.MOUSEEVENTS);
DOM.appendChild(td, captionContainer);
DOM.sinkEvents(td, Event.MOUSEEVENTS);
setElement(td);
}
public void setWidth(int w, boolean ensureDefinedWidth) {
if (ensureDefinedWidth) {
definedWidth = true;
// on column resize expand ratio becomes zero
expandRatio = 0;
}
if (width == w) {
return;
}
if (width == -1) {
// go to default mode, clip content if necessary
DOM.setStyleAttribute(captionContainer, "overflow", "");
}
width = w;
if (w == -1) {
DOM.setStyleAttribute(captionContainer, "width", "");
setWidth("");
} else {
captionContainer.getStyle().setPropertyPx("width", w);
/*
* if we already have tBody, set the header width properly, if
* not defer it. IE will fail with complex float in table header
* unless TD width is not explicitly set.
*/
if (scrollBody != null) {
int tdWidth = width + scrollBody.getCellExtraWidth();
setWidth(tdWidth + "px");
} else {
DeferredCommand.addCommand(new Command() {
public void execute() {
int tdWidth = width
+ scrollBody.getCellExtraWidth();
setWidth(tdWidth + "px");
}
});
}
}
}
public void setUndefinedWidth() {
definedWidth = false;
setWidth(-1, false);
}
/**
* Detects if width is fixed by developer on server side or resized to
* current width by user.
*
* @return true if defined, false if "natural" width
*/
public boolean isDefinedWidth() {
return definedWidth;
}
public int getWidth() {
return width;
}
public void setText(String headerText) {
DOM.setInnerHTML(captionContainer, headerText);
}
public String getColKey() {
return cid;
}
private void setSorted(boolean sorted) {
if (sorted) {
if (sortAscending) {
this.setStyleName(CLASSNAME + "-header-cell-asc");
} else {
this.setStyleName(CLASSNAME + "-header-cell-desc");
}
} else {
this.setStyleName(CLASSNAME + "-header-cell");
}
}
/**
* Handle column reordering.
*/
@Override
public void onBrowserEvent(Event event) {
if (enabled && event != null) {
if (isResizing
|| event.getEventTarget().cast() == colResizeWidget) {
if (dragging && DOM.eventGetType(event) == Event.ONMOUSEUP) {
// Handle releasing column header on spacer #5318
handleCaptionEvent(event);
} else {
onResizeEvent(event);
}
} else {
handleCaptionEvent(event);
if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
scrollBodyPanel.setFocus(true);
}
event.stopPropagation();
event.preventDefault();
}
}
}
private void createFloatingCopy() {
floatingCopyOfHeaderCell = DOM.createDiv();
DOM.setInnerHTML(floatingCopyOfHeaderCell, DOM.getInnerHTML(td));
floatingCopyOfHeaderCell = DOM
.getChild(floatingCopyOfHeaderCell, 1);
DOM.setElementProperty(floatingCopyOfHeaderCell, "className",
CLASSNAME + "-header-drag");
updateFloatingCopysPosition(DOM.getAbsoluteLeft(td),
DOM.getAbsoluteTop(td));
DOM.appendChild(RootPanel.get().getElement(),
floatingCopyOfHeaderCell);
}
private void updateFloatingCopysPosition(int x, int y) {
x -= DOM.getElementPropertyInt(floatingCopyOfHeaderCell,
"offsetWidth") / 2;
DOM.setStyleAttribute(floatingCopyOfHeaderCell, "left", x + "px");
if (y > 0) {
DOM.setStyleAttribute(floatingCopyOfHeaderCell, "top", (y + 7)
+ "px");
}
}
private void hideFloatingCopy() {
DOM.removeChild(RootPanel.get().getElement(),
floatingCopyOfHeaderCell);
floatingCopyOfHeaderCell = null;
}
/**
* Fires a header click event after the user has clicked a column header
* cell
*
* @param event
* The click event
*/
private void fireHeaderClickedEvent(Event event) {
if (client.hasEventListeners(VScrollTable.this,
HEADER_CLICK_EVENT_ID)) {
MouseEventDetails details = new MouseEventDetails(event);
client.updateVariable(paintableId, "headerClickEvent",
details.toString(), false);
client.updateVariable(paintableId, "headerClickCID", cid, true);
}
}
protected void handleCaptionEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
if (columnReordering) {
dragging = true;
moved = false;
colIndex = getColIndexByKey(cid);
DOM.setCapture(getElement());
headerX = tHead.getAbsoluteLeft();
DOM.eventPreventDefault(event); // prevent selecting text
}
break;
case Event.ONMOUSEUP:
if (columnReordering) {
dragging = false;
DOM.releaseCapture(getElement());
if (moved) {
hideFloatingCopy();
tHead.removeSlotFocus();
if (closestSlot != colIndex
&& closestSlot != (colIndex + 1)) {
if (closestSlot > colIndex) {
reOrderColumn(cid, closestSlot - 1);
} else {
reOrderColumn(cid, closestSlot);
}
}
}
}
if (!moved) {
// mouse event was a click to header -> sort column
if (sortable) {
if (sortColumn.equals(cid)) {
// just toggle order
client.updateVariable(paintableId, "sortascending",
!sortAscending, false);
} else {
// set table scrolled by this column
client.updateVariable(paintableId, "sortcolumn",
cid, false);
}
// get also cache columns at the same request
scrollBodyPanel.setScrollPosition(0);
firstvisible = 0;
rowRequestHandler.setReqFirstRow(0);
rowRequestHandler.setReqRows((int) (2 * pageLength
* cache_rate + pageLength));
rowRequestHandler.deferRowFetch();
}
fireHeaderClickedEvent(event);
break;
}
break;
case Event.ONMOUSEMOVE:
if (dragging) {
if (!moved) {
createFloatingCopy();
moved = true;
}
final int x = DOM.eventGetClientX(event)
+ DOM.getElementPropertyInt(tHead.hTableWrapper,
"scrollLeft");
int slotX = headerX;
closestSlot = colIndex;
int closestDistance = -1;
int start = 0;
if (showRowHeaders) {
start++;
}
final int visibleCellCount = tHead.getVisibleCellCount();
for (int i = start; i <= visibleCellCount; i++) {
if (i > 0) {
final String colKey = getColKeyByIndex(i - 1);
slotX += getColWidth(colKey);
}
final int dist = Math.abs(x - slotX);
if (closestDistance == -1 || dist < closestDistance) {
closestDistance = dist;
closestSlot = i;
}
}
tHead.focusSlot(closestSlot);
updateFloatingCopysPosition(DOM.eventGetClientX(event), -1);
}
break;
default:
break;
}
}
private void onResizeEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
isResizing = true;
DOM.setCapture(getElement());
dragStartX = DOM.eventGetClientX(event);
colIndex = getColIndexByKey(cid);
originalWidth = getWidth();
DOM.eventPreventDefault(event);
break;
case Event.ONMOUSEUP:
isResizing = false;
DOM.releaseCapture(getElement());
// readjust undefined width columns
lazyAdjustColumnWidths.cancel();
lazyAdjustColumnWidths.schedule(1);
fireColumnResizeEvent(cid, originalWidth, getColWidth(cid));
break;
case Event.ONMOUSEMOVE:
if (isResizing) {
final int deltaX = DOM.eventGetClientX(event) - dragStartX;
if (deltaX == 0) {
return;
}
int newWidth = originalWidth + deltaX;
if (newWidth < scrollBody.getCellExtraWidth()) {
newWidth = scrollBody.getCellExtraWidth();
}
setColWidth(colIndex, newWidth, true);
}
break;
default:
break;
}
}
public String getCaption() {
return DOM.getInnerText(captionContainer);
}
public boolean isEnabled() {
return getParent() != null;
}
public void setAlign(char c) {
if (align != c) {
switch (c) {
case ALIGN_CENTER:
DOM.setStyleAttribute(captionContainer, "textAlign",
"center");
break;
case ALIGN_RIGHT:
DOM.setStyleAttribute(captionContainer, "textAlign",
"right");
break;
default:
DOM.setStyleAttribute(captionContainer, "textAlign", "");
break;
}
}
align = c;
}
public char getAlign() {
return align;
}
/**
* Detects the natural minimum width for the column of this header cell.
* If column is resized by user or the width is defined by server the
* actual width is returned. Else the natural min width is returned.
*
* @param columnIndex
* column index hint, if -1 (unknown) it will be detected
*
* @return
*/
public int getNaturalColumnWidth(int columnIndex) {
if (isDefinedWidth()) {
return width;
} else {
if (naturalWidth < 0) {
// This is recently revealed column. Try to detect a proper
// value (greater of header and data
// cols)
final int hw = ((Element) getElement().getLastChild())
.getOffsetWidth() + scrollBody.getCellExtraWidth();
if (columnIndex < 0) {
columnIndex = 0;
for (Iterator<Widget> it = tHead.iterator(); it
.hasNext(); columnIndex++) {
if (it.next() == this) {
break;
}
}
}
final int cw = scrollBody.getColWidth(columnIndex);
naturalWidth = (hw > cw ? hw : cw);
}
return naturalWidth;
}
}
public void setExpandRatio(float floatAttribute) {
expandRatio = floatAttribute;
}
public float getExpandRatio() {
return expandRatio;
}
}
/**
* HeaderCell that is header cell for row headers.
*
* Reordering disabled and clicking on it resets sorting.
*/
public class RowHeadersHeaderCell extends HeaderCell {
RowHeadersHeaderCell() {
super("0", "");
}
@Override
protected void handleCaptionEvent(Event event) {
// NOP: RowHeaders cannot be reordered
// TODO It'd be nice to reset sorting here
}
}
public class TableHead extends Panel implements ActionOwner {
private static final int WRAPPER_WIDTH = 900000;
ArrayList<Widget> visibleCells = new ArrayList<Widget>();
HashMap<String, HeaderCell> availableCells = new HashMap<String, HeaderCell>();
Element div = DOM.createDiv();
Element hTableWrapper = DOM.createDiv();
Element hTableContainer = DOM.createDiv();
Element table = DOM.createTable();
Element headerTableBody = DOM.createTBody();
Element tr = DOM.createTR();
private final Element columnSelector = DOM.createDiv();
private int focusedSlot = -1;
public TableHead() {
if (BrowserInfo.get().isIE()) {
table.setPropertyInt("cellSpacing", 0);
}
DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
DOM.setElementProperty(hTableWrapper, "className", CLASSNAME
+ "-header");
// TODO move styles to CSS
DOM.setElementProperty(columnSelector, "className", CLASSNAME
+ "-column-selector");
DOM.setStyleAttribute(columnSelector, "display", "none");
DOM.appendChild(table, headerTableBody);
DOM.appendChild(headerTableBody, tr);
DOM.appendChild(hTableContainer, table);
DOM.appendChild(hTableWrapper, hTableContainer);
DOM.appendChild(div, hTableWrapper);
DOM.appendChild(div, columnSelector);
setElement(div);
setStyleName(CLASSNAME + "-header-wrap");
DOM.sinkEvents(columnSelector, Event.ONCLICK);
availableCells.put("0", new RowHeadersHeaderCell());
}
@Override
public void clear() {
for (String cid : availableCells.keySet()) {
removeCell(cid);
}
availableCells.clear();
availableCells.put("0", new RowHeadersHeaderCell());
}
public void updateCellsFromUIDL(UIDL uidl) {
Iterator<?> it = uidl.getChildIterator();
HashSet<String> updated = new HashSet<String>();
updated.add("0");
while (it.hasNext()) {
final UIDL col = (UIDL) it.next();
final String cid = col.getStringAttribute("cid");
updated.add(cid);
String caption = buildCaptionHtmlSnippet(col);
HeaderCell c = getHeaderCell(cid);
if (c == null) {
c = new HeaderCell(cid, caption);
availableCells.put(cid, c);
if (initializedAndAttached) {
// we will need a column width recalculation
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
} else {
c.setText(caption);
}
if (col.hasAttribute("sortable")) {
c.setSortable(true);
if (cid.equals(sortColumn)) {
c.setSorted(true);
} else {
c.setSorted(false);
}
} else {
c.setSortable(false);
}
if (col.hasAttribute("align")) {
c.setAlign(col.getStringAttribute("align").charAt(0));
}
if (col.hasAttribute("width")) {
final String width = col.getStringAttribute("width");
c.setWidth(Integer.parseInt(width), true);
} else if (recalcWidths) {
c.setUndefinedWidth();
}
if (col.hasAttribute("er")) {
c.setExpandRatio(col.getFloatAttribute("er"));
}
if (col.hasAttribute("collapsed")) {
// ensure header is properly removed from parent (case when
// collapsing happens via servers side api)
if (c.isAttached()) {
c.removeFromParent();
headerChangedDuringUpdate = true;
}
}
}
// check for orphaned header cells
for (Iterator<String> cit = availableCells.keySet().iterator(); cit
.hasNext();) {
String cid = cit.next();
if (!updated.contains(cid)) {
removeCell(cid);
cit.remove();
}
}
}
public void enableColumn(String cid, int index) {
final HeaderCell c = getHeaderCell(cid);
if (!c.isEnabled() || getHeaderCell(index) != c) {
setHeaderCell(index, c);
if (initializedAndAttached) {
headerChangedDuringUpdate = true;
}
}
}
public int getVisibleCellCount() {
return visibleCells.size();
}
public void setHorizontalScrollPosition(int scrollLeft) {
if (BrowserInfo.get().isIE6()) {
hTableWrapper.getStyle().setProperty("position", "relative");
hTableWrapper.getStyle().setPropertyPx("left", -scrollLeft);
} else {
hTableWrapper.setScrollLeft(scrollLeft);
}
}
public void setColumnCollapsingAllowed(boolean cc) {
if (cc) {
DOM.setStyleAttribute(columnSelector, "display", "block");
} else {
DOM.setStyleAttribute(columnSelector, "display", "none");
}
}
public void disableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", WRAPPER_WIDTH
+ "px");
}
public void enableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", "");
}
public void setHeaderCell(int index, HeaderCell cell) {
if (cell.isEnabled()) {
// we're moving the cell
DOM.removeChild(tr, cell.getElement());
orphan(cell);
}
if (index < visibleCells.size()) {
// insert to right slot
DOM.insertChild(tr, cell.getElement(), index);
adopt(cell);
visibleCells.add(index, cell);
} else if (index == visibleCells.size()) {
// simply append
DOM.appendChild(tr, cell.getElement());
adopt(cell);
visibleCells.add(cell);
} else {
throw new RuntimeException(
"Header cells must be appended in order");
}
}
public HeaderCell getHeaderCell(int index) {
if (index < visibleCells.size()) {
return (HeaderCell) visibleCells.get(index);
} else {
return null;
}
}
/**
* Get's HeaderCell by it's column Key.
*
* Note that this returns HeaderCell even if it is currently collapsed.
*
* @param cid
* Column key of accessed HeaderCell
* @return HeaderCell
*/
public HeaderCell getHeaderCell(String cid) {
return availableCells.get(cid);
}
public void moveCell(int oldIndex, int newIndex) {
final HeaderCell hCell = getHeaderCell(oldIndex);
final Element cell = hCell.getElement();
visibleCells.remove(oldIndex);
DOM.removeChild(tr, cell);
DOM.insertChild(tr, cell, newIndex);
visibleCells.add(newIndex, hCell);
}
public Iterator<Widget> iterator() {
return visibleCells.iterator();
}
@Override
public boolean remove(Widget w) {
if (visibleCells.contains(w)) {
visibleCells.remove(w);
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
return true;
}
return false;
}
public void removeCell(String colKey) {
final HeaderCell c = getHeaderCell(colKey);
remove(c);
}
private void focusSlot(int index) {
removeSlotFocus();
if (index > 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, index - 1)),
"className", CLASSNAME + "-resizer " + CLASSNAME
+ "-focus-slot-right");
} else {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, index)),
"className", CLASSNAME + "-resizer " + CLASSNAME
+ "-focus-slot-left");
}
focusedSlot = index;
}
private void removeSlotFocus() {
if (focusedSlot < 0) {
return;
}
if (focusedSlot == 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, focusedSlot)),
"className", CLASSNAME + "-resizer");
} else if (focusedSlot > 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, focusedSlot - 1)),
"className", CLASSNAME + "-resizer");
}
focusedSlot = -1;
}
@Override
public void onBrowserEvent(Event event) {
if (enabled) {
if (event.getEventTarget().cast() == columnSelector) {
final int left = DOM.getAbsoluteLeft(columnSelector);
final int top = DOM.getAbsoluteTop(columnSelector)
+ DOM.getElementPropertyInt(columnSelector,
"offsetHeight");
client.getContextMenu().showAt(this, left, top);
}
}
}
@Override
protected void onDetach() {
super.onDetach();
if (client != null) {
client.getContextMenu().ensureHidden(this);
}
}
class VisibleColumnAction extends Action {
String colKey;
private boolean collapsed;
public VisibleColumnAction(String colKey) {
super(VScrollTable.TableHead.this);
this.colKey = colKey;
caption = tHead.getHeaderCell(colKey).getCaption();
}
@Override
public void execute() {
client.getContextMenu().hide();
// toggle selected column
if (collapsedColumns.contains(colKey)) {
collapsedColumns.remove(colKey);
} else {
tHead.removeCell(colKey);
collapsedColumns.add(colKey);
lazyAdjustColumnWidths.schedule(1);
}
// update variable to server
client.updateVariable(paintableId, "collapsedcolumns",
collapsedColumns.toArray(new String[collapsedColumns
.size()]), false);
// let rowRequestHandler determine proper rows
rowRequestHandler.refreshContent();
}
public void setCollapsed(boolean b) {
collapsed = b;
}
/**
* Override default method to distinguish on/off columns
*/
@Override
public String getHTML() {
final StringBuffer buf = new StringBuffer();
if (collapsed) {
buf.append("<span class=\"v-off\">");
} else {
buf.append("<span class=\"v-on\">");
}
buf.append(super.getHTML());
buf.append("</span>");
return buf.toString();
}
}
/*
* Returns columns as Action array for column select popup
*/
public Action[] getActions() {
Object[] cols;
if (columnReordering && columnOrder != null) {
cols = columnOrder;
} else {
// if columnReordering is disabled, we need different way to get
// all available columns
cols = visibleColOrder;
cols = new Object[visibleColOrder.length
+ collapsedColumns.size()];
int i;
for (i = 0; i < visibleColOrder.length; i++) {
cols[i] = visibleColOrder[i];
}
for (final Iterator<String> it = collapsedColumns.iterator(); it
.hasNext();) {
cols[i++] = it.next();
}
}
final Action[] actions = new Action[cols.length];
for (int i = 0; i < cols.length; i++) {
final String cid = (String) cols[i];
final HeaderCell c = getHeaderCell(cid);
final VisibleColumnAction a = new VisibleColumnAction(
c.getColKey());
a.setCaption(c.getCaption());
if (!c.isEnabled()) {
a.setCollapsed(true);
}
actions[i] = a;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
/**
* Returns column alignments for visible columns
*/
public char[] getColumnAlignments() {
final Iterator<Widget> it = visibleCells.iterator();
final char[] aligns = new char[visibleCells.size()];
int colIndex = 0;
while (it.hasNext()) {
aligns[colIndex++] = ((HeaderCell) it.next()).getAlign();
}
return aligns;
}
}
/**
* A cell in the footer
*/
public class FooterCell extends Widget {
private Element td = DOM.createTD();
private Element captionContainer = DOM.createDiv();
private char align = ALIGN_LEFT;
private int width = -1;
private float expandRatio = 0;
private String cid;
boolean definedWidth = false;
private int naturalWidth = -1;
public FooterCell(String colId, String headerText) {
cid = colId;
setText(headerText);
DOM.setElementProperty(captionContainer, "className", CLASSNAME
+ "-footer-container");
// ensure no clipping initially (problem on column additions)
DOM.setStyleAttribute(captionContainer, "overflow", "visible");
DOM.sinkEvents(captionContainer, Event.MOUSEEVENTS);
DOM.appendChild(td, captionContainer);
DOM.sinkEvents(td, Event.MOUSEEVENTS);
setElement(td);
}
/**
* Sets the text of the footer
*
* @param footerText
* The text in the footer
*/
public void setText(String footerText) {
DOM.setInnerHTML(captionContainer, footerText);
}
/**
* Set alignment of the text in the cell
*
* @param c
* The alignment which can be ALIGN_CENTER, ALIGN_LEFT,
* ALIGN_RIGHT
*/
public void setAlign(char c) {
if (align != c) {
switch (c) {
case ALIGN_CENTER:
DOM.setStyleAttribute(captionContainer, "textAlign",
"center");
break;
case ALIGN_RIGHT:
DOM.setStyleAttribute(captionContainer, "textAlign",
"right");
break;
default:
DOM.setStyleAttribute(captionContainer, "textAlign", "");
break;
}
}
align = c;
}
/**
* Get the alignment of the text int the cell
*
* @return Returns either ALIGN_CENTER, ALIGN_LEFT or ALIGN_RIGHT
*/
public char getAlign() {
return align;
}
/**
* Sets the width of the cell
*
* @param w
* The width of the cell
* @param ensureDefinedWidth
* Ensures the the given width is not recalculated
*/
public void setWidth(int w, boolean ensureDefinedWidth) {
if (ensureDefinedWidth) {
definedWidth = true;
// on column resize expand ratio becomes zero
expandRatio = 0;
}
if (width == w) {
return;
}
if (width == -1) {
// go to default mode, clip content if necessary
DOM.setStyleAttribute(captionContainer, "overflow", "");
}
width = w;
if (w == -1) {
DOM.setStyleAttribute(captionContainer, "width", "");
setWidth("");
} else {
/*
* Reduce width with one pixel for the right border since the
* footers does not have any spacers between them.
*/
int borderWidths = 1;
// Set the container width (check for negative value)
if (w - borderWidths >= 0) {
captionContainer.getStyle().setPropertyPx("width",
w - borderWidths);
} else {
captionContainer.getStyle().setPropertyPx("width", 0);
}
/*
* if we already have tBody, set the header width properly, if
* not defer it. IE will fail with complex float in table header
* unless TD width is not explicitly set.
*/
if (scrollBody != null) {
/*
* Reduce with one since footer does not have any spacers,
* instead a 1 pixel border.
*/
int tdWidth = width + scrollBody.getCellExtraWidth()
- borderWidths;
setWidth(tdWidth + "px");
} else {
DeferredCommand.addCommand(new Command() {
public void execute() {
int borderWidths = 1;
int tdWidth = width
+ scrollBody.getCellExtraWidth()
- borderWidths;
setWidth(tdWidth + "px");
}
});
}
}
}
/**
* Sets the width to undefined
*/
public void setUndefinedWidth() {
setWidth(-1, false);
}
/**
* Detects if width is fixed by developer on server side or resized to
* current width by user.
*
* @return true if defined, false if "natural" width
*/
public boolean isDefinedWidth() {
return definedWidth;
}
/**
* Returns the pixels width of the footer cell
*
* @return The width in pixels
*/
public int getWidth() {
return width;
}
/**
* Sets the expand ratio of the cell
*
* @param floatAttribute
* The expand ratio
*/
public void setExpandRatio(float floatAttribute) {
expandRatio = floatAttribute;
}
/**
* Returns the expand ration of the cell
*
* @return The expand ratio
*/
public float getExpandRatio() {
return expandRatio;
}
/**
* Is the cell enabled?
*
* @return True if enabled else False
*/
public boolean isEnabled() {
return getParent() != null;
}
/**
* Handle column clicking
*/
@Override
public void onBrowserEvent(Event event) {
if (enabled && event != null) {
handleCaptionEvent(event);
if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
scrollBodyPanel.setFocus(true);
}
}
}
/**
* Handles a event on the captions
*
* @param event
* The event to handle
*/
protected void handleCaptionEvent(Event event) {
if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
fireFooterClickedEvent(event);
}
}
/**
* Fires a footer click event after the user has clicked a column footer
* cell
*
* @param event
* The click event
*/
private void fireFooterClickedEvent(Event event) {
if (client.hasEventListeners(VScrollTable.this,
FOOTER_CLICK_EVENT_ID)) {
MouseEventDetails details = new MouseEventDetails(event);
client.updateVariable(paintableId, "footerClickEvent",
details.toString(), false);
client.updateVariable(paintableId, "footerClickCID", cid, true);
}
}
/**
* Returns the column key of the column
*
* @return The column key
*/
public String getColKey() {
return cid;
}
/**
* Detects the natural minimum width for the column of this header cell.
* If column is resized by user or the width is defined by server the
* actual width is returned. Else the natural min width is returned.
*
* @param columnIndex
* column index hint, if -1 (unknown) it will be detected
*
* @return
*/
public int getNaturalColumnWidth(int columnIndex) {
if (isDefinedWidth()) {
return width;
} else {
if (naturalWidth < 0) {
// This is recently revealed column. Try to detect a proper
// value (greater of header and data
// cols)
final int hw = ((Element) getElement().getLastChild())
.getOffsetWidth() + scrollBody.getCellExtraWidth();
if (columnIndex < 0) {
columnIndex = 0;
for (Iterator<Widget> it = tHead.iterator(); it
.hasNext(); columnIndex++) {
if (it.next() == this) {
break;
}
}
}
final int cw = scrollBody.getColWidth(columnIndex);
naturalWidth = (hw > cw ? hw : cw);
}
return naturalWidth;
}
}
public void setNaturalMinimumColumnWidth(int w) {
naturalWidth = w;
}
}
/**
* HeaderCell that is header cell for row headers.
*
* Reordering disabled and clicking on it resets sorting.
*/
public class RowHeadersFooterCell extends FooterCell {
RowHeadersFooterCell() {
super("0", "");
}
@Override
protected void handleCaptionEvent(Event event) {
// NOP: RowHeaders cannot be reordered
// TODO It'd be nice to reset sorting here
}
}
/**
* The footer of the table which can be seen in the bottom of the Table.
*/
public class TableFooter extends Panel {
private static final int WRAPPER_WIDTH = 900000;
ArrayList<Widget> visibleCells = new ArrayList<Widget>();
HashMap<String, FooterCell> availableCells = new HashMap<String, FooterCell>();
Element div = DOM.createDiv();
Element hTableWrapper = DOM.createDiv();
Element hTableContainer = DOM.createDiv();
Element table = DOM.createTable();
Element headerTableBody = DOM.createTBody();
Element tr = DOM.createTR();
public TableFooter() {
DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
DOM.setElementProperty(hTableWrapper, "className", CLASSNAME
+ "-footer");
DOM.appendChild(table, headerTableBody);
DOM.appendChild(headerTableBody, tr);
DOM.appendChild(hTableContainer, table);
DOM.appendChild(hTableWrapper, hTableContainer);
DOM.appendChild(div, hTableWrapper);
setElement(div);
setStyleName(CLASSNAME + "-footer-wrap");
availableCells.put("0", new RowHeadersFooterCell());
}
@Override
public void clear() {
for (String cid : availableCells.keySet()) {
removeCell(cid);
}
availableCells.clear();
availableCells.put("0", new RowHeadersFooterCell());
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.user.client.ui.Panel#remove(com.google.gwt.user.client
* .ui.Widget)
*/
@Override
public boolean remove(Widget w) {
if (visibleCells.contains(w)) {
visibleCells.remove(w);
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see com.google.gwt.user.client.ui.HasWidgets#iterator()
*/
public Iterator<Widget> iterator() {
return visibleCells.iterator();
}
/**
* Gets a footer cell which represents the given columnId
*
* @param cid
* The columnId
*
* @return The cell
*/
public FooterCell getFooterCell(String cid) {
return availableCells.get(cid);
}
/**
* Gets a footer cell by using a column index
*
* @param index
* The index of the column
* @return The Cell
*/
public FooterCell getFooterCell(int index) {
if (index < visibleCells.size()) {
return (FooterCell) visibleCells.get(index);
} else {
return null;
}
}
/**
* Updates the cells contents when updateUIDL request is received
*
* @param uidl
* The UIDL
*/
public void updateCellsFromUIDL(UIDL uidl) {
Iterator<?> columnIterator = uidl.getChildIterator();
HashSet<String> updated = new HashSet<String>();
updated.add("0");
while (columnIterator.hasNext()) {
final UIDL col = (UIDL) columnIterator.next();
final String cid = col.getStringAttribute("cid");
updated.add(cid);
String caption = col.getStringAttribute("fcaption");
FooterCell c = getFooterCell(cid);
if (c == null) {
c = new FooterCell(cid, caption);
availableCells.put(cid, c);
if (initializedAndAttached) {
// we will need a column width recalculation
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
} else {
c.setText(caption);
}
if (col.hasAttribute("align")) {
c.setAlign(col.getStringAttribute("align").charAt(0));
}
if (col.hasAttribute("width")) {
final String width = col.getStringAttribute("width");
c.setWidth(Integer.parseInt(width), true);
} else if (recalcWidths) {
c.setUndefinedWidth();
}
if (col.hasAttribute("er")) {
c.setExpandRatio(col.getFloatAttribute("er"));
}
if (col.hasAttribute("collapsed")) {
// ensure header is properly removed from parent (case when
// collapsing happens via servers side api)
if (c.isAttached()) {
c.removeFromParent();
headerChangedDuringUpdate = true;
}
}
}
// check for orphaned header cells
for (Iterator<String> cit = availableCells.keySet().iterator(); cit
.hasNext();) {
String cid = cit.next();
if (!updated.contains(cid)) {
removeCell(cid);
cit.remove();
}
}
}
/**
* Set a footer cell for a specified column index
*
* @param index
* The index
* @param cell
* The footer cell
*/
public void setFooterCell(int index, FooterCell cell) {
if (cell.isEnabled()) {
// we're moving the cell
DOM.removeChild(tr, cell.getElement());
orphan(cell);
}
if (index < visibleCells.size()) {
// insert to right slot
DOM.insertChild(tr, cell.getElement(), index);
adopt(cell);
visibleCells.add(index, cell);
} else if (index == visibleCells.size()) {
// simply append
DOM.appendChild(tr, cell.getElement());
adopt(cell);
visibleCells.add(cell);
} else {
throw new RuntimeException(
"Header cells must be appended in order");
}
}
/**
* Remove a cell by using the columnId
*
* @param colKey
* The columnId to remove
*/
public void removeCell(String colKey) {
final FooterCell c = getFooterCell(colKey);
remove(c);
}
/**
* Enable a column (Sets the footer cell)
*
* @param cid
* The columnId
* @param index
* The index of the column
*/
public void enableColumn(String cid, int index) {
final FooterCell c = getFooterCell(cid);
if (!c.isEnabled() || getFooterCell(index) != c) {
setFooterCell(index, c);
if (initializedAndAttached) {
headerChangedDuringUpdate = true;
}
}
}
/**
* Disable browser measurement of the table width
*/
public void disableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", WRAPPER_WIDTH
+ "px");
}
/**
* Enable browser measurement of the table width
*/
public void enableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", "");
}
/**
* Set the horizontal position in the cell in the footer. This is done
* when a horizontal scrollbar is present.
*
* @param scrollLeft
* The value of the leftScroll
*/
public void setHorizontalScrollPosition(int scrollLeft) {
if (BrowserInfo.get().isIE6()) {
hTableWrapper.getStyle().setProperty("position", "relative");
hTableWrapper.getStyle().setPropertyPx("left", -scrollLeft);
} else {
hTableWrapper.setScrollLeft(scrollLeft);
}
}
/**
* Swap cells when the column are dragged
*
* @param oldIndex
* The old index of the cell
* @param newIndex
* The new index of the cell
*/
public void moveCell(int oldIndex, int newIndex) {
final FooterCell hCell = getFooterCell(oldIndex);
final Element cell = hCell.getElement();
visibleCells.remove(oldIndex);
DOM.removeChild(tr, cell);
DOM.insertChild(tr, cell, newIndex);
visibleCells.add(newIndex, hCell);
}
}
/**
* This Panel can only contain VScrollTableRow type of widgets. This
* "simulates" very large table, keeping spacers which take room of
* unrendered rows.
*
*/
public class VScrollTableBody extends Panel {
public static final int DEFAULT_ROW_HEIGHT = 24;
private double rowHeight = -1;
private final List<Widget> renderedRows = new ArrayList<Widget>();
/**
* Due some optimizations row height measuring is deferred and initial
* set of rows is rendered detached. Flag set on when table body has
* been attached in dom and rowheight has been measured.
*/
private boolean tBodyMeasurementsDone = false;
Element preSpacer = DOM.createDiv();
Element postSpacer = DOM.createDiv();
Element container = DOM.createDiv();
TableSectionElement tBodyElement = Document.get().createTBodyElement();
Element table = DOM.createTable();
private int firstRendered;
private int lastRendered;
private char[] aligns;
protected VScrollTableBody() {
constructDOM();
setElement(container);
}
/**
* @return the height of scrollable body, subpixels ceiled.
*/
public int getRequiredHeight() {
return preSpacer.getOffsetHeight() + postSpacer.getOffsetHeight()
+ Util.getRequiredHeight(table);
}
private void constructDOM() {
DOM.setElementProperty(table, "className", CLASSNAME + "-table");
if (BrowserInfo.get().isIE()) {
table.setPropertyInt("cellSpacing", 0);
}
DOM.setElementProperty(preSpacer, "className", CLASSNAME
+ "-row-spacer");
DOM.setElementProperty(postSpacer, "className", CLASSNAME
+ "-row-spacer");
table.appendChild(tBodyElement);
DOM.appendChild(container, preSpacer);
DOM.appendChild(container, table);
DOM.appendChild(container, postSpacer);
}
public int getAvailableWidth() {
int availW = scrollBodyPanel.getOffsetWidth() - getBorderWidth();
return availW;
}
public void renderInitialRows(UIDL rowData, int firstIndex, int rows) {
firstRendered = firstIndex;
lastRendered = firstIndex + rows - 1;
final Iterator<?> it = rowData.getChildIterator();
aligns = tHead.getColumnAlignments();
while (it.hasNext()) {
final VScrollTableRow row = createRow((UIDL) it.next(), aligns);
addRow(row);
}
if (isAttached()) {
fixSpacers();
}
}
public void renderRows(UIDL rowData, int firstIndex, int rows) {
// FIXME REVIEW
aligns = tHead.getColumnAlignments();
final Iterator<?> it = rowData.getChildIterator();
if (firstIndex == lastRendered + 1) {
while (it.hasNext()) {
final VScrollTableRow row = prepareRow((UIDL) it.next());
addRow(row);
lastRendered++;
}
fixSpacers();
} else if (firstIndex + rows == firstRendered) {
final VScrollTableRow[] rowArray = new VScrollTableRow[rows];
int i = rows;
while (it.hasNext()) {
i--;
rowArray[i] = prepareRow((UIDL) it.next());
}
for (i = 0; i < rows; i++) {
addRowBeforeFirstRendered(rowArray[i]);
firstRendered--;
}
} else {
// completely new set of rows
while (lastRendered + 1 > firstRendered) {
unlinkRow(false);
}
final VScrollTableRow row = prepareRow((UIDL) it.next());
firstRendered = firstIndex;
lastRendered = firstIndex - 1;
addRow(row);
lastRendered++;
setContainerHeight();
fixSpacers();
while (it.hasNext()) {
addRow(prepareRow((UIDL) it.next()));
lastRendered++;
}
fixSpacers();
}
// this may be a new set of rows due content change,
// ensure we have proper cache rows
int reactFirstRow = (int) (firstRowInViewPort - pageLength
* cache_react_rate);
int reactLastRow = (int) (firstRowInViewPort + pageLength + pageLength
* cache_react_rate);
if (reactFirstRow < 0) {
reactFirstRow = 0;
}
if (reactLastRow >= totalRows) {
reactLastRow = totalRows - 1;
}
if (lastRendered < reactLastRow) {
// get some cache rows below visible area
rowRequestHandler.setReqFirstRow(lastRendered + 1);
rowRequestHandler.setReqRows(reactLastRow - lastRendered);
rowRequestHandler.deferRowFetch(1);
} else if (scrollBody.getFirstRendered() > reactFirstRow) {
/*
* Branch for fetching cache above visible area.
*
* If cache needed for both before and after visible area, this
* will be rendered after-cache is reveived and rendered. So in
* some rare situations table may take two cache visits to
* server.
*/
rowRequestHandler.setReqFirstRow(reactFirstRow);
rowRequestHandler.setReqRows(firstRendered - reactFirstRow);
rowRequestHandler.deferRowFetch(1);
}
}
/**
* This method is used to instantiate new rows for this table. It
* automatically sets correct widths to rows cells and assigns correct
* client reference for child widgets.
*
* This method can be called only after table has been initialized
*
* @param uidl
*/
private VScrollTableRow prepareRow(UIDL uidl) {
final VScrollTableRow row = createRow(uidl, aligns);
final int cells = DOM.getChildCount(row.getElement());
for (int i = 0; i < cells; i++) {
final Element cell = DOM.getChild(row.getElement(), i);
int w = VScrollTable.this.getColWidth(getColKeyByIndex(i));
if (w < 0) {
w = 0;
}
cell.getFirstChildElement().getStyle()
.setPropertyPx("width", w);
cell.getStyle().setPropertyPx("width", w);
}
return row;
}
protected VScrollTableRow createRow(UIDL uidl, char[] aligns2) {
return new VScrollTableRow(uidl, aligns);
}
private void addRowBeforeFirstRendered(VScrollTableRow row) {
VScrollTableRow first = null;
if (renderedRows.size() > 0) {
first = (VScrollTableRow) renderedRows.get(0);
}
if (first != null && first.getStyleName().indexOf("-odd") == -1) {
row.addStyleName(CLASSNAME + "-row-odd");
} else {
row.addStyleName(CLASSNAME + "-row");
}
if (row.isSelected()) {
row.addStyleName("v-selected");
}
tBodyElement.insertBefore(row.getElement(),
tBodyElement.getFirstChild());
adopt(row);
renderedRows.add(0, row);
}
private void addRow(VScrollTableRow row) {
VScrollTableRow last = null;
if (renderedRows.size() > 0) {
last = (VScrollTableRow) renderedRows
.get(renderedRows.size() - 1);
}
if (last != null && last.getStyleName().indexOf("-odd") == -1) {
row.addStyleName(CLASSNAME + "-row-odd");
} else {
row.addStyleName(CLASSNAME + "-row");
}
if (row.isSelected()) {
row.addStyleName("v-selected");
}
tBodyElement.appendChild(row.getElement());
adopt(row);
renderedRows.add(row);
}
public Iterator<Widget> iterator() {
return renderedRows.iterator();
}
/**
* @return false if couldn't remove row
*/
public boolean unlinkRow(boolean fromBeginning) {
if (lastRendered - firstRendered < 0) {
return false;
}
int index;
if (fromBeginning) {
index = 0;
firstRendered++;
} else {
index = renderedRows.size() - 1;
lastRendered--;
}
if (index >= 0) {
final VScrollTableRow toBeRemoved = (VScrollTableRow) renderedRows
.get(index);
lazyUnregistryBag.add(toBeRemoved);
tBodyElement.removeChild(toBeRemoved.getElement());
orphan(toBeRemoved);
renderedRows.remove(index);
fixSpacers();
return true;
} else {
return false;
}
}
@Override
public boolean remove(Widget w) {
throw new UnsupportedOperationException();
}
@Override
protected void onAttach() {
super.onAttach();
setContainerHeight();
}
/**
* Fix container blocks height according to totalRows to avoid
* "bouncing" when scrolling
*/
private void setContainerHeight() {
fixSpacers();
DOM.setStyleAttribute(container, "height", totalRows
* getRowHeight() + "px");
}
private void fixSpacers() {
int prepx = (int) Math.round(getRowHeight() * firstRendered);
if (prepx < 0) {
prepx = 0;
}
preSpacer.getStyle().setPropertyPx("height", prepx);
int postpx = (int) (getRowHeight() * (totalRows - 1 - lastRendered));
if (postpx < 0) {
postpx = 0;
}
postSpacer.getStyle().setPropertyPx("height", postpx);
}
public double getRowHeight() {
return getRowHeight(false);
}
public double getRowHeight(boolean forceUpdate) {
if (tBodyMeasurementsDone && !forceUpdate) {
return rowHeight;
} else {
if (tBodyElement.getRows().getLength() > 0) {
int tableHeight = getTableHeight();
int rowCount = tBodyElement.getRows().getLength();
rowHeight = tableHeight / (double) rowCount;
} else {
if (isAttached()) {
// measure row height by adding a dummy row
VScrollTableRow scrollTableRow = new VScrollTableRow();
tBodyElement.appendChild(scrollTableRow.getElement());
getRowHeight(forceUpdate);
tBodyElement.removeChild(scrollTableRow.getElement());
} else {
// TODO investigate if this can never happen anymore
return DEFAULT_ROW_HEIGHT;
}
}
tBodyMeasurementsDone = true;
return rowHeight;
}
}
public int getTableHeight() {
return table.getOffsetHeight();
}
/**
* Returns the width available for column content.
*
* @param columnIndex
* @return
*/
public int getColWidth(int columnIndex) {
if (tBodyMeasurementsDone) {
NodeList<TableRowElement> rows = tBodyElement.getRows();
if (rows.getLength() == 0) {
// no rows yet rendered
return 0;
} else {
com.google.gwt.dom.client.Element wrapperdiv = rows
.getItem(0).getCells().getItem(columnIndex)
.getFirstChildElement();
return wrapperdiv.getOffsetWidth();
}
} else {
return 0;
}
}
/**
* Sets the content width of a column.
*
* Due IE limitation, we must set the width to a wrapper elements inside
* table cells (with overflow hidden, which does not work on td
* elements).
*
* To get this work properly crossplatform, we will also set the width
* of td.
*
* @param colIndex
* @param w
*/
public void setColWidth(int colIndex, int w) {
NodeList<TableRowElement> rows2 = tBodyElement.getRows();
final int rows = rows2.getLength();
for (int i = 0; i < rows; i++) {
TableRowElement row = rows2.getItem(i);
TableCellElement cell = row.getCells().getItem(colIndex);
cell.getFirstChildElement().getStyle()
.setPropertyPx("width", w);
cell.getStyle().setPropertyPx("width", w);
}
}
private int cellExtraWidth = -1;
/**
* Method to return the space used for cell paddings + border.
*/
private int getCellExtraWidth() {
if (cellExtraWidth < 0) {
detectExtrawidth();
}
return cellExtraWidth;
}
private void detectExtrawidth() {
NodeList<TableRowElement> rows = tBodyElement.getRows();
if (rows.getLength() == 0) {
/* need to temporary add empty row and detect */
VScrollTableRow scrollTableRow = new VScrollTableRow();
tBodyElement.appendChild(scrollTableRow.getElement());
detectExtrawidth();
tBodyElement.removeChild(scrollTableRow.getElement());
} else {
boolean noCells = false;
TableRowElement item = rows.getItem(0);
TableCellElement firstTD = item.getCells().getItem(0);
if (firstTD == null) {
// content is currently empty, we need to add a fake cell
// for measuring
noCells = true;
VScrollTableRow next = (VScrollTableRow) iterator().next();
next.addCell(null, "", ALIGN_LEFT, "", true);
firstTD = item.getCells().getItem(0);
}
com.google.gwt.dom.client.Element wrapper = firstTD
.getFirstChildElement();
cellExtraWidth = firstTD.getOffsetWidth()
- wrapper.getOffsetWidth();
if (noCells) {
firstTD.getParentElement().removeChild(firstTD);
}
}
}
private void reLayoutComponents() {
for (Widget w : this) {
VScrollTableRow r = (VScrollTableRow) w;
for (Widget widget : r) {
client.handleComponentRelativeSize(widget);
}
}
}
public int getLastRendered() {
return lastRendered;
}
public int getFirstRendered() {
return firstRendered;
}
public void moveCol(int oldIndex, int newIndex) {
// loop all rows and move given index to its new place
final Iterator<?> rows = iterator();
while (rows.hasNext()) {
final VScrollTableRow row = (VScrollTableRow) rows.next();
final Element td = DOM.getChild(row.getElement(), oldIndex);
DOM.removeChild(row.getElement(), td);
DOM.insertChild(row.getElement(), td, newIndex);
}
}
/**
* Restore row visibility which is set to "none" when the row is
* rendered (due a performance optimization).
*/
private void restoreRowVisibility() {
for (Widget row : renderedRows) {
row.getElement().getStyle().setProperty("visibility", "");
}
}
public class VScrollTableRow extends Panel implements ActionOwner,
Container {
private static final int DRAGMODE_MULTIROW = 2;
protected ArrayList<Widget> childWidgets = new ArrayList<Widget>();
private boolean selected = false;
protected final int rowKey;
private List<UIDL> pendingComponentPaints;
private String[] actionKeys = null;
private final TableRowElement rowElement;
private boolean mDown;
private VScrollTableRow(int rowKey) {
this.rowKey = rowKey;
rowElement = Document.get().createTRElement();
setElement(rowElement);
DOM.sinkEvents(getElement(), Event.MOUSEEVENTS
| Event.ONDBLCLICK | Event.ONCONTEXTMENU
| Event.ONKEYDOWN);
}
private void paintComponent(Paintable p, UIDL uidl) {
if (isAttached()) {
p.updateFromUIDL(uidl, client);
} else {
if (pendingComponentPaints == null) {
pendingComponentPaints = new LinkedList<UIDL>();
}
pendingComponentPaints.add(uidl);
}
}
@Override
protected void onAttach() {
super.onAttach();
if (pendingComponentPaints != null) {
for (UIDL uidl : pendingComponentPaints) {
Paintable paintable = client.getPaintable(uidl);
paintable.updateFromUIDL(uidl, client);
}
}
}
@Override
protected void onDetach() {
super.onDetach();
client.getContextMenu().ensureHidden(this);
}
public String getKey() {
return String.valueOf(rowKey);
}
public VScrollTableRow(UIDL uidl, char[] aligns) {
this(uidl.getIntAttribute("key"));
/*
* Rendering the rows as hidden improves Firefox and Safari
* performance drastically.
*/
getElement().getStyle().setProperty("visibility", "hidden");
String rowStyle = uidl.getStringAttribute("rowstyle");
if (rowStyle != null) {
addStyleName(CLASSNAME + "-row-" + rowStyle);
}
tHead.getColumnAlignments();
int col = 0;
int visibleColumnIndex = -1;
// row header
if (showRowHeaders) {
addCell(uidl, buildCaptionHtmlSnippet(uidl), aligns[col++],
"", true);
}
if (uidl.hasAttribute("al")) {
actionKeys = uidl.getStringArrayAttribute("al");
}
final Iterator<?> cells = uidl.getChildIterator();
while (cells.hasNext()) {
final Object cell = cells.next();
visibleColumnIndex++;
String columnId = visibleColOrder[visibleColumnIndex];
String style = "";
if (uidl.hasAttribute("style-" + columnId)) {
style = uidl.getStringAttribute("style-" + columnId);
}
if (cell instanceof String) {
addCell(uidl, cell.toString(), aligns[col++], style,
false);
} else {
final Paintable cellContent = client
.getPaintable((UIDL) cell);
addCell(uidl, (Widget) cellContent, aligns[col++],
style);
paintComponent(cellContent, (UIDL) cell);
}
}
if (uidl.hasAttribute("selected") && !isSelected()) {
toggleSelection();
}
}
/**
* Add a dummy row, used for measurements if Table is empty.
*/
public VScrollTableRow() {
this(0);
addStyleName(CLASSNAME + "-row");
addCell(null, "_", 'b', "", true);
}
public void addCell(UIDL rowUidl, String text, char align,
String style, boolean textIsHTML) {
// String only content is optimized by not using Label widget
final Element td = DOM.createTD();
final Element container = DOM.createDiv();
String className = CLASSNAME + "-cell-content";
if (style != null && !style.equals("")) {
className += " " + CLASSNAME + "-cell-content-" + style;
}
td.setClassName(className);
container.setClassName(CLASSNAME + "-cell-wrapper");
if (textIsHTML) {
container.setInnerHTML(text);
} else {
container.setInnerText(text);
}
if (align != ALIGN_LEFT) {
switch (align) {
case ALIGN_CENTER:
container.getStyle().setProperty("textAlign", "center");
break;
case ALIGN_RIGHT:
default:
container.getStyle().setProperty("textAlign", "right");
break;
}
}
td.appendChild(container);
getElement().appendChild(td);
}
public void addCell(UIDL rowUidl, Widget w, char align, String style) {
final Element td = DOM.createTD();
final Element container = DOM.createDiv();
String className = CLASSNAME + "-cell-content";
if (style != null && !style.equals("")) {
className += " " + CLASSNAME + "-cell-content-" + style;
}
td.setClassName(className);
container.setClassName(CLASSNAME + "-cell-wrapper");
// TODO most components work with this, but not all (e.g.
// Select)
// Old comment: make widget cells respect align.
// text-align:center for IE, margin: auto for others
if (align != ALIGN_LEFT) {
switch (align) {
case ALIGN_CENTER:
container.getStyle().setProperty("textAlign", "center");
break;
case ALIGN_RIGHT:
default:
container.getStyle().setProperty("textAlign", "right");
break;
}
}
td.appendChild(container);
getElement().appendChild(td);
// ensure widget not attached to another element (possible tBody
// change)
w.removeFromParent();
container.appendChild(w.getElement());
adopt(w);
childWidgets.add(w);
}
public Iterator<Widget> iterator() {
return childWidgets.iterator();
}
@Override
public boolean remove(Widget w) {
if (childWidgets.contains(w)) {
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()),
w.getElement());
childWidgets.remove(w);
return true;
} else {
return false;
}
}
private void handleClickEvent(Event event, Element targetTdOrTr) {
if (client.hasEventListeners(VScrollTable.this,
ITEM_CLICK_EVENT_ID)) {
boolean doubleClick = (DOM.eventGetType(event) == Event.ONDBLCLICK);
/* This row was clicked */
client.updateVariable(paintableId, "clickedKey", ""
+ rowKey, false);
if (getElement() == targetTdOrTr.getParentElement()) {
/* A specific column was clicked */
int childIndex = DOM.getChildIndex(getElement(),
targetTdOrTr);
String colKey = null;
colKey = tHead.getHeaderCell(childIndex).getColKey();
client.updateVariable(paintableId, "clickedColKey",
colKey, false);
}
MouseEventDetails details = new MouseEventDetails(event);
boolean imm = true;
if (immediate && event.getButton() == Event.BUTTON_LEFT
&& !doubleClick && isSelectable() && !isSelected()) {
/*
* A left click when the table is selectable and in
* immediate mode on a row that is not currently
* selected will cause a selection event to be fired
* after this click event. By making the click event
* non-immediate we avoid sending two separate messages
* to the server.
*/
imm = false;
}
client.updateVariable(paintableId, "clickEvent",
details.toString(), imm);
}
}
/**
* Add this to the element mouse down event by using
* element.setPropertyJSO
* ("onselectstart",applyDisableTextSelectionIEHack()); Remove it
* then again when the mouse is depressed in the mouse up event.
*
* @return Returns the JSO preventing text selection
*/
private native JavaScriptObject applyDisableTextSelectionIEHack()
/*-{
return function(){ return false; };
}-*/;
/*
* React on click that occur on content cells only
*/
@Override
public void onBrowserEvent(Event event) {
if (enabled) {
int type = event.getTypeInt();
Element targetTdOrTr = getEventTargetTdOrTr(event);
if (type == Event.ONCONTEXTMENU) {
showContextMenu(event);
event.stopPropagation();
return;
}
if (targetTdOrTr != null) {
switch (type) {
case Event.ONDBLCLICK:
handleClickEvent(event, targetTdOrTr);
break;
case Event.ONMOUSEUP:
mDown = false;
handleClickEvent(event, targetTdOrTr);
scrollBodyPanel.setFocus(true);
if (event.getButton() == Event.BUTTON_LEFT
&& isSelectable()) {
// Ctrl+Shift click
if ((event.getCtrlKey() || event.getMetaKey())
&& event.getShiftKey()
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
toggleShiftSelection(false);
setRowFocus(this);
// Ctrl click
} else if ((event.getCtrlKey() || event
.getMetaKey())
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
toggleSelection();
setRowFocus(this);
// Ctrl click (Single selection)
} else if ((event.getCtrlKey() || event
.getMetaKey()
&& selectMode == SELECT_MODE_SINGLE)) {
if (!isSelected()
|| (isSelected() && nullSelectionAllowed)) {
if (!isSelected()) {
deselectAll();
}
toggleSelection();
setRowFocus(this);
}
// Shift click
} else if (event.getShiftKey()
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
toggleShiftSelection(true);
// click
} else {
boolean currentlyJustThisRowSelected = selectedRowKeys
.size() == 1
&& selectedRowKeys
.contains(getKey());
if (!currentlyJustThisRowSelected) {
if (multiselectmode == MULTISELECT_MODE_DEFAULT) {
deselectAll();
}
toggleSelection();
} else if (selectMode == SELECT_MODE_SINGLE
&& nullSelectionAllowed) {
toggleSelection();
}/*
* else NOP to avoid excessive server
* visits (selection is removed with
* CTRL/META click)
*/
selectionRangeStart = this;
setRowFocus(this);
}
// Remove IE text selection hack
if (BrowserInfo.get().isIE()) {
((Element) event.getEventTarget().cast())
.setPropertyJSO("onselectstart",
null);
}
sendSelectedRows();
}
break;
case Event.ONMOUSEDOWN:
if (dragmode != 0
&& event.getButton() == NativeEvent.BUTTON_LEFT) {
mDown = true;
VTransferable transferable = new VTransferable();
transferable.setDragSource(VScrollTable.this);
transferable.setData("itemId", "" + rowKey);
NodeList<TableCellElement> cells = rowElement
.getCells();
for (int i = 0; i < cells.getLength(); i++) {
if (cells.getItem(i).isOrHasChild(
targetTdOrTr)) {
HeaderCell headerCell = tHead
.getHeaderCell(i);
transferable.setData("propertyId",
headerCell.cid);
break;
}
}
VDragEvent ev = VDragAndDropManager.get()
.startDrag(transferable, event, true);
if (dragmode == DRAGMODE_MULTIROW
&& selectMode == SELECT_MODE_MULTI
&& selectedRowKeys
.contains("" + rowKey)) {
ev.createDragImage(
(Element) scrollBody.tBodyElement
.cast(), true);
Element dragImage = ev.getDragImage();
int i = 0;
for (Iterator<Widget> iterator = scrollBody
.iterator(); iterator.hasNext();) {
VScrollTableRow next = (VScrollTableRow) iterator
.next();
Element child = (Element) dragImage
.getChild(i++);
if (!selectedRowKeys.contains(""
+ next.rowKey)) {
child.getStyle().setVisibility(
Visibility.HIDDEN);
}
}
} else {
ev.createDragImage(getElement(), true);
}
// because we are preventing the default (due to
// prevent text selection) we must ensure
// gaining the focus.
ensureFocus();
event.preventDefault();
event.stopPropagation();
} else if (event.getCtrlKey()
|| event.getShiftKey()
|| event.getMetaKey()
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
// because we are preventing the default (due to
// prevent text selection) we must ensure
// gaining the focus.
ensureFocus();
// Prevent default text selection in Firefox
event.preventDefault();
// Prevent default text selection in IE
if (BrowserInfo.get().isIE()) {
((Element) event.getEventTarget().cast())
.setPropertyJSO(
"onselectstart",
applyDisableTextSelectionIEHack());
}
event.stopPropagation();
}
break;
case Event.ONMOUSEOUT:
mDown = false;
break;
default:
break;
}
}
}
super.onBrowserEvent(event);
}
/**
* Finds the TD that the event interacts with. Returns null if the
* target of the event should not be handled. If the event target is
* the row directly this method returns the TR element instead of
* the TD.
*
* @param event
* @return TD or TR element that the event targets (the actual event
* target is this element or a child of it)
*/
private Element getEventTargetTdOrTr(Event event) {
Element targetTdOrTr = null;
final Element eventTarget = DOM.eventGetTarget(event);
final Element eventTargetParent = DOM.getParent(eventTarget);
final Element eventTargetGrandParent = DOM
.getParent(eventTargetParent);
final Element thisTrElement = getElement();
if (eventTarget == thisTrElement) {
// This was a click on the TR element
targetTdOrTr = eventTarget;
// rowTarget = true;
} else if (thisTrElement == eventTargetParent) {
// Target parent is the TR, so the actual target is the TD
targetTdOrTr = eventTarget;
} else if (thisTrElement == eventTargetGrandParent) {
// Target grand parent is the TR, so the parent is the TD
targetTdOrTr = eventTargetParent;
} else {
/*
* This is a workaround to make Labels, read only TextFields
* and Embedded in a Table clickable (see #2688). It is
* really not a fix as it does not work with a custom read
* only components (not extending VLabel/VEmbedded).
*/
Widget widget = Util.findWidget(eventTarget, null);
if (widget != this) {
while (widget != null && widget.getParent() != this) {
widget = widget.getParent();
}
if (widget != null) {
// widget is now the closest widget to this row
if (widget instanceof VLabel
|| widget instanceof VEmbedded
|| (widget instanceof VTextField && ((VTextField) widget)
.isReadOnly())) {
Element tdElement = eventTargetParent;
while (DOM.getParent(tdElement) != thisTrElement) {
tdElement = DOM.getParent(tdElement);
}
targetTdOrTr = tdElement;
}
}
}
}
return targetTdOrTr;
}
public void showContextMenu(Event event) {
if (enabled && actionKeys != null) {
int left = event.getClientX();
int top = event.getClientY();
top += Window.getScrollTop();
left += Window.getScrollLeft();
client.getContextMenu().showAt(this, left, top);
}
event.stopPropagation();
event.preventDefault();
}
/**
* Has the row been selected?
*
* @return Returns true if selected, else false
*/
public boolean isSelected() {
return selected;
}
/**
* Toggle the selection of the row
*/
public void toggleSelection() {
selected = !selected;
selectionChanged = true;
if (selected) {
selectedRowKeys.add(String.valueOf(rowKey));
addStyleName("v-selected");
} else {
removeStyleName("v-selected");
selectedRowKeys.remove(String.valueOf(rowKey));
}
removeKeyFromSelectedRange(rowKey);
}
/**
* Is called when a user clicks an item when holding SHIFT key down.
* This will select a new range from the last cell clicked
*
* @param deselectPrevious
* Should the previous selected range be deselected
*/
private void toggleShiftSelection(boolean deselectPrevious) {
/*
* Ensures that we are in multiselect mode and that we have a
* previous selection which was not a deselection
*/
if (selectMode == SELECT_MODE_SINGLE) {
// No previous selection found
deselectAll();
toggleSelection();
return;
}
// Set the selectable range
int startKey;
if (selectionRangeStart != null) {
startKey = Integer.valueOf(selectionRangeStart.getKey());
} else {
startKey = Integer.valueOf(focusedRow.getKey());
}
int endKey = rowKey;
if (endKey < startKey) {
// Swap keys if in the wrong order
startKey ^= endKey;
endKey ^= startKey;
startKey ^= endKey;
}
// Deselect previous items if so desired
if (deselectPrevious) {
deselectAll();
}
// Select the range (not including this row)
VScrollTableRow startRow = getRenderedRowByKey(String
.valueOf(startKey));
VScrollTableRow endRow = getRenderedRowByKey(String
.valueOf(endKey));
// If start row is null then we have a multipage selection from
// above
if (startRow == null) {
startRow = (VScrollTableRow) scrollBody.iterator().next();
setRowFocus(endRow);
}
if (endRow == null) {
setRowFocus(startRow);
}
Iterator<Widget> rows = scrollBody.iterator();
boolean startSelection = false;
while (rows.hasNext()) {
VScrollTableRow row = (VScrollTableRow) rows.next();
if (row == startRow || startSelection) {
startSelection = true;
if (!row.isSelected()) {
row.toggleSelection();
}
selectedRowKeys.add(row.getKey());
}
if (row == endRow && row != null) {
startSelection = false;
}
}
// Add range
if (startRow != endRow) {
selectedRowRanges.add(new SelectionRange(startKey, endKey));
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.ui.IActionOwner#getActions ()
*/
public Action[] getActions() {
if (actionKeys == null) {
return new Action[] {};
}
final Action[] actions = new Action[actionKeys.length];
for (int i = 0; i < actions.length; i++) {
final String actionKey = actionKeys[i];
final TreeAction a = new TreeAction(this,
String.valueOf(rowKey), actionKey);
a.setCaption(getActionCaption(actionKey));
a.setIconUrl(getActionIcon(actionKey));
actions[i] = a;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
public RenderSpace getAllocatedSpace(Widget child) {
int w = 0;
int i = getColIndexOf(child);
HeaderCell headerCell = tHead.getHeaderCell(i);
if (headerCell != null) {
if (initializedAndAttached) {
w = headerCell.getWidth();
} else {
// header offset width is not absolutely correct value,
// but a best guess (expecting similar content in all
// columns ->
// if one component is relative width so are others)
w = headerCell.getOffsetWidth() - getCellExtraWidth();
}
}
return new RenderSpace(w, 0) {
@Override
public int getHeight() {
return (int) getRowHeight();
}
};
}
private int getColIndexOf(Widget child) {
com.google.gwt.dom.client.Element widgetCell = child
.getElement().getParentElement().getParentElement();
NodeList<TableCellElement> cells = rowElement.getCells();
for (int i = 0; i < cells.getLength(); i++) {
if (cells.getItem(i) == widgetCell) {
return i;
}
}
return -1;
}
public boolean hasChildComponent(Widget component) {
return childWidgets.contains(component);
}
public void replaceChildComponent(Widget oldComponent,
Widget newComponent) {
com.google.gwt.dom.client.Element parentElement = oldComponent
.getElement().getParentElement();
int index = childWidgets.indexOf(oldComponent);
oldComponent.removeFromParent();
parentElement.appendChild(newComponent.getElement());
childWidgets.add(index, newComponent);
adopt(newComponent);
}
public boolean requestLayout(Set<Paintable> children) {
// row size should never change and system wouldn't event
// survive as this is a kind of fake paitable
return true;
}
public void updateCaption(Paintable component, UIDL uidl) {
// NOP, not rendered
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Should never be called,
// Component container interface faked here to get layouts
// render properly
}
}
/**
* Ensure the component has a focus.
*
* TODO the current implementation simply always calls focus for the
* component. In case the Table at some point implements focus/blur
* listeners, this method needs to be evolved to conditionally call
* focus only if not currently focused.
*/
protected void ensureFocus() {
focus();
}
}
/**
* Deselects all items
*/
public void deselectAll() {
final Object[] keys = selectedRowKeys.toArray();
for (int i = 0; i < keys.length; i++) {
final VScrollTableRow row = getRenderedRowByKey((String) keys[i]);
if (row != null && row.isSelected()) {
row.toggleSelection();
removeKeyFromSelectedRange(Integer.parseInt(row.getKey()));
}
}
// still ensure all selects are removed from (not necessary rendered)
selectedRowKeys.clear();
selectedRowRanges.clear();
}
/**
* Determines the pagelength when the table height is fixed.
*/
public void updatePageLength() {
// Only update if visible and enabled
if (!isVisible() || !enabled) {
return;
}
if (scrollBody == null) {
return;
}
if (height == null || height.equals("")) {
return;
}
int rowHeight = (int) scrollBody.getRowHeight();
int bodyH = scrollBodyPanel.getOffsetHeight();
int rowsAtOnce = bodyH / rowHeight;
boolean anotherPartlyVisible = ((bodyH % rowHeight) != 0);
if (anotherPartlyVisible) {
rowsAtOnce++;
}
if (pageLength != rowsAtOnce) {
pageLength = rowsAtOnce;
client.updateVariable(paintableId, "pagelength", pageLength, false);
if (!rendering) {
int currentlyVisible = scrollBody.lastRendered
- scrollBody.firstRendered;
if (currentlyVisible < pageLength
&& currentlyVisible < totalRows) {
// shake scrollpanel to fill empty space
scrollBodyPanel.setScrollPosition(scrollTop + 1);
scrollBodyPanel.setScrollPosition(scrollTop - 1);
}
}
}
}
@Override
public void setWidth(String width) {
if (this.width.equals(width)) {
return;
}
this.width = width;
if (width != null && !"".equals(width)) {
super.setWidth(width);
int innerPixels = getOffsetWidth() - getBorderWidth();
if (innerPixels < 0) {
innerPixels = 0;
}
setContentWidth(innerPixels);
if (!rendering) {
// readjust undefined width columns
lazyAdjustColumnWidths.cancel();
lazyAdjustColumnWidths.schedule(LAZY_COLUMN_ADJUST_TIMEOUT);
}
} else {
super.setWidth("");
}
/*
* setting width may affect wheter the component has scrollbars -> needs
* scrolling or not
*/
setProperTabIndex();
}
private static final int LAZY_COLUMN_ADJUST_TIMEOUT = 300;
private final Timer lazyAdjustColumnWidths = new Timer() {
/**
* Check for column widths, and available width, to see if we can fix
* column widths "optimally". Doing this lazily to avoid expensive
* calculation when resizing is not yet finished.
*/
@Override
public void run() {
Iterator<Widget> headCells = tHead.iterator();
int usedMinimumWidth = 0;
int totalExplicitColumnsWidths = 0;
float expandRatioDivider = 0;
int colIndex = 0;
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
if (hCell.isDefinedWidth()) {
totalExplicitColumnsWidths += hCell.getWidth();
usedMinimumWidth += hCell.getWidth();
} else {
usedMinimumWidth += hCell.getNaturalColumnWidth(colIndex);
expandRatioDivider += hCell.getExpandRatio();
}
colIndex++;
}
int availW = scrollBody.getAvailableWidth();
// Hey IE, are you really sure about this?
availW = scrollBody.getAvailableWidth();
int visibleCellCount = tHead.getVisibleCellCount();
availW -= scrollBody.getCellExtraWidth() * visibleCellCount;
if (willHaveScrollbars()) {
availW -= Util.getNativeScrollbarSize();
}
int extraSpace = availW - usedMinimumWidth;
if (extraSpace < 0) {
extraSpace = 0;
}
int totalUndefinedNaturaWidths = usedMinimumWidth
- totalExplicitColumnsWidths;
// we have some space that can be divided optimally
HeaderCell hCell;
colIndex = 0;
headCells = tHead.iterator();
while (headCells.hasNext()) {
hCell = (HeaderCell) headCells.next();
if (!hCell.isDefinedWidth()) {
int w = hCell.getNaturalColumnWidth(colIndex);
int newSpace;
if (expandRatioDivider > 0) {
// divide excess space by expand ratios
newSpace = (int) (w + extraSpace
* hCell.getExpandRatio() / expandRatioDivider);
} else {
if (totalUndefinedNaturaWidths != 0) {
// divide relatively to natural column widths
newSpace = w + extraSpace * w
/ totalUndefinedNaturaWidths;
} else {
newSpace = w;
}
}
setColWidth(colIndex, newSpace, false);
}
colIndex++;
}
if ((height == null || "".equals(height))
&& totalRows == pageLength) {
// fix body height (may vary if lazy loading is offhorizontal
// scrollbar appears/disappears)
int bodyHeight = scrollBody.getRequiredHeight();
boolean needsSpaceForHorizontalSrollbar = (availW < usedMinimumWidth);
if (needsSpaceForHorizontalSrollbar) {
bodyHeight += Util.getNativeScrollbarSize();
}
int heightBefore = getOffsetHeight();
scrollBodyPanel.setHeight(bodyHeight + "px");
if (heightBefore != getOffsetHeight()) {
Util.notifyParentOfSizeChange(VScrollTable.this, false);
}
}
scrollBody.reLayoutComponents();
DeferredCommand.addCommand(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
});
}
};
/**
* helper to set pixel size of head and body part
*
* @param pixels
*/
private void setContentWidth(int pixels) {
tHead.setWidth(pixels + "px");
scrollBodyPanel.setWidth(pixels + "px");
tFoot.setWidth(pixels + "px");
}
private int borderWidth = -1;
/**
* @return border left + border right
*/
private int getBorderWidth() {
if (borderWidth < 0) {
borderWidth = Util.measureHorizontalPaddingAndBorder(
scrollBodyPanel.getElement(), 2);
if (borderWidth < 0) {
borderWidth = 0;
}
}
return borderWidth;
}
/**
* Ensures scrollable area is properly sized. This method is used when fixed
* size is used.
*/
private int containerHeight;
private void setContainerHeight() {
if (height != null && !"".equals(height)) {
containerHeight = getOffsetHeight();
containerHeight -= showColHeaders ? tHead.getOffsetHeight() : 0;
containerHeight -= tFoot.getOffsetHeight();
containerHeight -= getContentAreaBorderHeight();
if (containerHeight < 0) {
containerHeight = 0;
}
scrollBodyPanel.setHeight(containerHeight + "px");
}
}
private int contentAreaBorderHeight = -1;
private int scrollLeft;
private int scrollTop;
private VScrollTableDropHandler dropHandler;
/**
* @return border top + border bottom of the scrollable area of table
*/
private int getContentAreaBorderHeight() {
if (contentAreaBorderHeight < 0) {
if (BrowserInfo.get().isIE7() || BrowserInfo.get().isIE6()) {
contentAreaBorderHeight = Util
.measureVerticalBorder(scrollBodyPanel.getElement());
} else {
DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
"hidden");
int oh = scrollBodyPanel.getOffsetHeight();
int ch = scrollBodyPanel.getElement().getPropertyInt(
"clientHeight");
contentAreaBorderHeight = oh - ch;
DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
"auto");
}
}
return contentAreaBorderHeight;
}
@Override
public void setHeight(String height) {
this.height = height;
super.setHeight(height);
setContainerHeight();
if (initializedAndAttached) {
updatePageLength();
}
if (!rendering) {
// Webkit may sometimes get an odd rendering bug (white space
// between header and body), see bug #3875. Running
// overflow hack here to shake body element a bit.
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
/*
* setting height may affect wheter the component has scrollbars ->
* needs scrolling or not
*/
setProperTabIndex();
}
/*
* Overridden due Table might not survive of visibility change (scroll pos
* lost). Example ITabPanel just set contained components invisible and back
* when changing tabs.
*/
@Override
public void setVisible(boolean visible) {
if (isVisible() != visible) {
super.setVisible(visible);
if (initializedAndAttached) {
if (visible) {
DeferredCommand.addCommand(new Command() {
public void execute() {
scrollBodyPanel
.setScrollPosition((int) (firstRowInViewPort * scrollBody
.getRowHeight()));
}
});
}
}
}
}
/**
* Helper function to build html snippet for column or row headers
*
* @param uidl
* possibly with values caption and icon
* @return html snippet containing possibly an icon + caption text
*/
protected String buildCaptionHtmlSnippet(UIDL uidl) {
String s = uidl.getStringAttribute("caption");
if (uidl.hasAttribute("icon")) {
s = "<img src=\""
+ client.translateVaadinUri(uidl.getStringAttribute("icon"))
+ "\" alt=\"icon\" class=\"v-icon\">" + s;
}
return s;
}
/**
* This method has logic which rows needs to be requested from server when
* user scrolls
*/
public void onScroll(ScrollEvent event) {
scrollLeft = scrollBodyPanel.getElement().getScrollLeft();
scrollTop = scrollBodyPanel.getScrollPosition();
if (!initializedAndAttached) {
return;
}
if (!enabled) {
scrollBodyPanel
.setScrollPosition((int) (firstRowInViewPort * scrollBody
.getRowHeight()));
return;
}
rowRequestHandler.cancel();
if (BrowserInfo.get().isSafari() && event != null && scrollTop == 0) {
// due to the webkitoverflowworkaround, top may sometimes report 0
// for webkit, although it really is not. Expecting to have the
// correct
// value available soon.
DeferredCommand.addCommand(new Command() {
public void execute() {
onScroll(null);
}
});
return;
}
// fix headers horizontal scrolling
tHead.setHorizontalScrollPosition(scrollLeft);
// fix footers horizontal scrolling
tFoot.setHorizontalScrollPosition(scrollLeft);
firstRowInViewPort = (int) Math.ceil(scrollTop
/ scrollBody.getRowHeight());
if (firstRowInViewPort > totalRows - pageLength) {
firstRowInViewPort = totalRows - pageLength;
}
int postLimit = (int) (firstRowInViewPort + (pageLength - 1) + pageLength
* cache_react_rate);
if (postLimit > totalRows - 1) {
postLimit = totalRows - 1;
}
int preLimit = (int) (firstRowInViewPort - pageLength
* cache_react_rate);
if (preLimit < 0) {
preLimit = 0;
}
final int lastRendered = scrollBody.getLastRendered();
final int firstRendered = scrollBody.getFirstRendered();
if (postLimit <= lastRendered && preLimit >= firstRendered) {
// remember which firstvisible we requested, in case the server has
// a differing opinion
lastRequestedFirstvisible = firstRowInViewPort;
client.updateVariable(paintableId, "firstvisible",
firstRowInViewPort, false);
return; // scrolled withing "non-react area"
}
if (firstRowInViewPort - pageLength * cache_rate > lastRendered
|| firstRowInViewPort + pageLength + pageLength * cache_rate < firstRendered) {
// need a totally new set
rowRequestHandler
.setReqFirstRow((firstRowInViewPort - (int) (pageLength * cache_rate)));
int last = firstRowInViewPort + (int) (cache_rate * pageLength)
+ pageLength - 1;
if (last >= totalRows) {
last = totalRows - 1;
}
rowRequestHandler.setReqRows(last
- rowRequestHandler.getReqFirstRow() + 1);
rowRequestHandler.deferRowFetch();
return;
}
if (preLimit < firstRendered) {
// need some rows to the beginning of the rendered area
rowRequestHandler
.setReqFirstRow((int) (firstRowInViewPort - pageLength
* cache_rate));
rowRequestHandler.setReqRows(firstRendered
- rowRequestHandler.getReqFirstRow());
rowRequestHandler.deferRowFetch();
return;
}
if (postLimit > lastRendered) {
// need some rows to the end of the rendered area
rowRequestHandler.setReqFirstRow(lastRendered + 1);
rowRequestHandler.setReqRows((int) ((firstRowInViewPort
+ pageLength + pageLength * cache_rate) - lastRendered));
rowRequestHandler.deferRowFetch();
}
}
public VScrollTableDropHandler getDropHandler() {
return dropHandler;
}
private static class TableDDDetails {
int overkey = -1;
VerticalDropLocation dropLocation;
String colkey;
@Override
public boolean equals(Object obj) {
if (obj instanceof TableDDDetails) {
TableDDDetails other = (TableDDDetails) obj;
return dropLocation == other.dropLocation
&& overkey == other.overkey
&& ((colkey != null && colkey.equals(other.colkey)) || (colkey == null && other.colkey == null));
}
return false;
}
// @Override
// public int hashCode() {
// return overkey;
// }
}
public class VScrollTableDropHandler extends VAbstractDropHandler {
private static final String ROWSTYLEBASE = "v-table-row-drag-";
private TableDDDetails dropDetails;
private TableDDDetails lastEmphasized;
@Override
public void dragEnter(VDragEvent drag) {
updateDropDetails(drag);
super.dragEnter(drag);
}
private void updateDropDetails(VDragEvent drag) {
dropDetails = new TableDDDetails();
Element elementOver = drag.getElementOver();
VScrollTableRow row = Util.findWidget(elementOver, getRowClass());
if (row != null) {
dropDetails.overkey = row.rowKey;
Element tr = row.getElement();
Element element = elementOver;
while (element != null && element.getParentElement() != tr) {
element = (Element) element.getParentElement();
}
int childIndex = DOM.getChildIndex(tr, element);
dropDetails.colkey = tHead.getHeaderCell(childIndex)
.getColKey();
dropDetails.dropLocation = DDUtil.getVerticalDropLocation(row
.getElement(), drag.getCurrentGwtEvent().getClientY(),
0.2);
}
drag.getDropDetails().put("itemIdOver", dropDetails.overkey + "");
drag.getDropDetails().put(
"detail",
dropDetails.dropLocation != null ? dropDetails.dropLocation
.toString() : null);
}
private Class<? extends Widget> getRowClass() {
// get the row type this way to make dd work in derived
// implementations
return scrollBody.iterator().next().getClass();
}
@Override
public void dragOver(VDragEvent drag) {
TableDDDetails oldDetails = dropDetails;
updateDropDetails(drag);
if (!oldDetails.equals(dropDetails)) {
deEmphasis();
final TableDDDetails newDetails = dropDetails;
VAcceptCallback cb = new VAcceptCallback() {
public void accepted(VDragEvent event) {
if (newDetails.equals(dropDetails)) {
dragAccepted(event);
}
/*
* Else new target slot already defined, ignore
*/
}
};
validate(cb, drag);
}
}
@Override
public void dragLeave(VDragEvent drag) {
deEmphasis();
super.dragLeave(drag);
}
@Override
public boolean drop(VDragEvent drag) {
deEmphasis();
return super.drop(drag);
}
private void deEmphasis() {
UIObject.setStyleName(getElement(), CLASSNAME + "-drag", false);
if (lastEmphasized == null) {
return;
}
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (lastEmphasized != null
&& row.rowKey == lastEmphasized.overkey) {
if (row != null) {
String stylename = ROWSTYLEBASE
+ lastEmphasized.dropLocation.toString()
.toLowerCase();
VScrollTableRow.setStyleName(row.getElement(),
stylename, false);
}
lastEmphasized = null;
return;
}
}
}
/**
* TODO needs different drop modes ?? (on cells, on rows), now only
* supports rows
*/
private void emphasis(TableDDDetails details) {
deEmphasis();
UIObject.setStyleName(getElement(), CLASSNAME + "-drag", true);
// iterate old and new emphasized row
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (details != null && details.overkey == row.rowKey) {
if (row != null) {
String stylename = ROWSTYLEBASE
+ details.dropLocation.toString().toLowerCase();
VScrollTableRow.setStyleName(row.getElement(),
stylename, true);
}
lastEmphasized = details;
return;
}
}
}
@Override
protected void dragAccepted(VDragEvent drag) {
emphasis(dropDetails);
}
@Override
public Paintable getPaintable() {
return VScrollTable.this;
}
public ApplicationConnection getApplicationConnection() {
return client;
}
}
protected VScrollTableRow getFocusedRow() {
return focusedRow;
}
/**
* Moves the selection head to a specific row
*
* @param row
* The row to where the selection head should move
* @return Returns true if focus was moved successfully, else false
*/
private boolean setRowFocus(VScrollTableRow row) {
if (selectMode == SELECT_MODE_NONE) {
return false;
}
// Remove previous selection
if (focusedRow != null && focusedRow != row) {
focusedRow.removeStyleName(CLASSNAME_SELECTION_FOCUS);
}
if (row != null) {
// Apply focus style to new selection
row.addStyleName(CLASSNAME_SELECTION_FOCUS);
// Trying to set focus on already focused row
if (row == focusedRow) {
return false;
}
// Set new focused row
focusedRow = row;
ensureRowIsVisible(row);
return true;
}
return false;
}
/**
* Ensures that the row is visible
*
* @param row
* The row to ensure is visible
*/
private void ensureRowIsVisible(VScrollTableRow row) {
scrollIntoViewVertically(row.getElement());
}
/**
* Scrolls an element into view vertically only. Modified version of
* Element.scrollIntoView.
*
* @param elem
* The element to scroll into view
*/
private native void scrollIntoViewVertically(Element elem)
/*-{
var top = elem.offsetTop;
var height = elem.offsetHeight;
if (elem.parentNode != elem.offsetParent) {
top -= elem.parentNode.offsetTop;
}
var cur = elem.parentNode;
while (cur && (cur.nodeType == 1)) {
if (top < cur.scrollTop) {
cur.scrollTop = top;
}
if (top + height > cur.scrollTop + cur.clientHeight) {
cur.scrollTop = (top + height) - cur.clientHeight;
}
var offsetTop = cur.offsetTop;
if (cur.parentNode != cur.offsetParent) {
offsetTop -= cur.parentNode.offsetTop;
}
top += offsetTop - cur.scrollTop;
cur = cur.parentNode;
}
}-*/;
/**
* Handles the keyboard events handled by the table
*
* @param event
* The keyboard event received
* @return true iff the navigation event was handled
*/
protected boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
if (keycode == KeyCodes.KEY_TAB) {
// Do not handle tab key
return false;
}
// Down navigation
if (selectMode == SELECT_MODE_NONE && keycode == getNavigationDownKey()) {
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() + scrollingVelocity);
return true;
} else if (keycode == getNavigationDownKey()) {
if (selectMode == SELECT_MODE_MULTI && moveFocusDown()) {
selectFocusedRow(ctrl, shift);
} else if (selectMode == SELECT_MODE_SINGLE && !shift
&& moveFocusDown()) {
selectFocusedRow(ctrl, shift);
}
return true;
}
// Up navigation
if (selectMode == SELECT_MODE_NONE && keycode == getNavigationUpKey()) {
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() - scrollingVelocity);
return true;
} else if (keycode == getNavigationUpKey()) {
if (selectMode == SELECT_MODE_MULTI && moveFocusUp()) {
selectFocusedRow(ctrl, shift);
} else if (selectMode == SELECT_MODE_SINGLE && !shift
&& moveFocusUp()) {
selectFocusedRow(ctrl, shift);
}
return true;
}
if (keycode == getNavigationLeftKey()) {
// Left navigation
scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
.getHorizontalScrollPosition() - scrollingVelocity);
return true;
} else if (keycode == getNavigationRightKey()) {
// Right navigation
scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
.getHorizontalScrollPosition() + scrollingVelocity);
return true;
}
// Select navigation
if (isSelectable() && keycode == getNavigationSelectKey()) {
if (selectMode == SELECT_MODE_SINGLE) {
boolean wasSelected = focusedRow.isSelected();
deselectAll();
if (!wasSelected || !nullSelectionAllowed) {
focusedRow.toggleSelection();
}
} else {
focusedRow.toggleSelection();
}
sendSelectedRows();
return true;
}
// Page Down navigation
if (keycode == getNavigationPageDownKey()) {
int rowHeight = (int) scrollBody.getRowHeight();
int offset = pageLength * rowHeight - rowHeight;
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() + offset);
if (isSelectable()) {
if (!moveFocusDown(pageLength - 2)) {
final int lastRendered = scrollBody.getLastRendered();
if (lastRendered == totalRows - 1) {
selectLastRenderedRow(false);
} else {
selectLastItemInNextRender = true;
}
} else {
selectFocusedRow(false, false);
sendSelectedRows();
}
}
return true;
}
// Page Up navigation
if (keycode == getNavigationPageUpKey()) {
int rowHeight = (int) scrollBody.getRowHeight();
int offset = pageLength * rowHeight - rowHeight;
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() - offset);
if (isSelectable()) {
if (!moveFocusUp(pageLength - 2)) {
final int firstRendered = scrollBody.getFirstRendered();
if (firstRendered == 0) {
selectFirstRenderedRow(false);
} else {
selectFirstItemInNextRender = true;
}
} else {
selectFocusedRow(false, false);
sendSelectedRows();
}
}
return true;
}
// Goto start navigation
if (keycode == getNavigationStartKey()) {
if (isSelectable()) {
final int firstRendered = scrollBody.getFirstRendered();
boolean focusOnly = ctrl;
if (firstRendered == 0) {
selectFirstRenderedRow(focusOnly);
} else if (focusOnly) {
focusFirstItemInNextRender = true;
} else {
selectFirstItemInNextRender = true;
}
}
scrollBodyPanel.setScrollPosition(0);
return true;
}
// Goto end navigation
if (keycode == getNavigationEndKey()) {
if (isSelectable()) {
final int lastRendered = scrollBody.getLastRendered();
boolean focusOnly = ctrl;
if (lastRendered == totalRows - 1) {
selectLastRenderedRow(focusOnly);
} else if (focusOnly) {
focusLastItemInNextRender = true;
} else {
selectLastItemInNextRender = true;
}
}
scrollBodyPanel.setScrollPosition(scrollBody.getOffsetHeight());
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.KeyPressHandler#onKeyPress(com.google
* .gwt.event.dom.client.KeyPressEvent)
*/
public void onKeyPress(KeyPressEvent event) {
if (hasFocus) {
if (handleNavigation(event.getNativeEvent().getKeyCode(),
event.isControlKeyDown() || event.isMetaKeyDown(),
event.isShiftKeyDown())) {
event.preventDefault();
}
// Start the velocityTimer
if (scrollingVelocityTimer == null) {
scrollingVelocityTimer = new Timer() {
@Override
public void run() {
scrollingVelocity++;
}
};
scrollingVelocityTimer.scheduleRepeating(100);
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
* .event.dom.client.KeyDownEvent)
*/
public void onKeyDown(KeyDownEvent event) {
if (hasFocus) {
if (handleNavigation(event.getNativeEvent().getKeyCode(),
event.isControlKeyDown() || event.isMetaKeyDown(),
event.isShiftKeyDown())) {
event.preventDefault();
}
// Start the velocityTimer
if (scrollingVelocityTimer == null) {
scrollingVelocityTimer = new Timer() {
@Override
public void run() {
scrollingVelocity++;
}
};
scrollingVelocityTimer.scheduleRepeating(100);
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
* .dom.client.FocusEvent)
*/
public void onFocus(FocusEvent event) {
if (isFocusable()) {
scrollBodyPanel.addStyleName("focused");
hasFocus = true;
// Focus a row if no row is in focus
if (focusedRow == null) {
setRowFocus((VScrollTableRow) scrollBody.iterator().next());
} else {
setRowFocus(focusedRow);
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
* .dom.client.BlurEvent)
*/
public void onBlur(BlurEvent event) {
scrollBodyPanel.removeStyleName("focused");
hasFocus = false;
// Unfocus any row
setRowFocus(null);
}
/**
* Removes a key from a range if the key is found in a selected range
*
* @param key
* The key to remove
*/
private void removeKeyFromSelectedRange(int key) {
for (SelectionRange range : selectedRowRanges) {
if (range.inRange(key)) {
int start = range.getStartKey();
int end = range.getEndKey();
if (start < key && end > key) {
selectedRowRanges.add(new SelectionRange(start, key - 1));
selectedRowRanges.add(new SelectionRange(key + 1, end));
} else if (start == key && start < end) {
selectedRowRanges.add(new SelectionRange(start + 1, end));
} else if (end == key && start < end) {
selectedRowRanges.add(new SelectionRange(start, end - 1));
}
selectedRowRanges.remove(range);
break;
}
}
}
/**
* Can the Table be focused?
*
* @return True if the table can be focused, else false
*/
public boolean isFocusable() {
if (scrollBody != null) {
boolean hasVerticalScrollbars = scrollBody.getOffsetHeight() > scrollBodyPanel
.getOffsetHeight();
boolean hasHorizontalScrollbars = scrollBody.getOffsetWidth() > scrollBodyPanel
.getOffsetWidth();
return !(!hasHorizontalScrollbars && !hasVerticalScrollbars && selectMode == SELECT_MODE_NONE);
}
return false;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.Focusable#focus()
*/
public void focus() {
scrollBodyPanel.focus();
}
/**
* Sets the proper tabIndex for scrollBodyPanel (the focusable elemen in the
* component).
*
* If the component has no explicit tabIndex a zero is given (default
* tabbing order based on dom hierarchy) or -1 if the component does not
* need to gain focus. The component needs no focus if it has no scrollabars
* (not scrollable) and not selectable. Note that in the future shortcut
* actions may need focus.
*
*/
private void setProperTabIndex() {
if (tabIndex == 0 && !isFocusable()) {
scrollBodyPanel.getElement().setTabIndex(-1);
} else {
scrollBodyPanel.getElement().setTabIndex(tabIndex);
}
}
}
|
src/com/vaadin/terminal/gwt/client/ui/VScrollTable.java
|
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.dom.client.Style.Visibility;
import com.google.gwt.dom.client.TableCellElement;
import com.google.gwt.dom.client.TableRowElement;
import com.google.gwt.dom.client.TableSectionElement;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.dom.client.ScrollHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.Container;
import com.vaadin.terminal.gwt.client.Focusable;
import com.vaadin.terminal.gwt.client.MouseEventDetails;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.RenderSpace;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.ui.VScrollTable.VScrollTableBody.VScrollTableRow;
import com.vaadin.terminal.gwt.client.ui.dd.DDUtil;
import com.vaadin.terminal.gwt.client.ui.dd.VAbstractDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VAcceptCallback;
import com.vaadin.terminal.gwt.client.ui.dd.VDragAndDropManager;
import com.vaadin.terminal.gwt.client.ui.dd.VDragEvent;
import com.vaadin.terminal.gwt.client.ui.dd.VHasDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VTransferable;
import com.vaadin.terminal.gwt.client.ui.dd.VerticalDropLocation;
/**
* VScrollTable
*
* VScrollTable is a FlowPanel having two widgets in it: * TableHead component *
* ScrollPanel
*
* TableHead contains table's header and widgets + logic for resizing,
* reordering and hiding columns.
*
* ScrollPanel contains VScrollTableBody object which handles content. To save
* some bandwidth and to improve clients responsiveness with loads of data, in
* VScrollTableBody all rows are not necessary rendered. There are "spacers" in
* VScrollTableBody to use the exact same space as non-rendered rows would use.
* This way we can use seamlessly traditional scrollbars and scrolling to fetch
* more rows instead of "paging".
*
* In VScrollTable we listen to scroll events. On horizontal scrolling we also
* update TableHeads scroll position which has its scrollbars hidden. On
* vertical scroll events we will check if we are reaching the end of area where
* we have rows rendered and
*
* TODO implement unregistering for child components in Cells
*/
public class VScrollTable extends FlowPanel implements Table, ScrollHandler,
VHasDropHandler, KeyPressHandler, KeyDownHandler, FocusHandler,
BlurHandler, Focusable {
public static final String CLASSNAME = "v-table";
public static final String CLASSNAME_SELECTION_FOCUS = CLASSNAME + "-focus";
public static final String ITEM_CLICK_EVENT_ID = "itemClick";
public static final String HEADER_CLICK_EVENT_ID = "handleHeaderClick";
public static final String FOOTER_CLICK_EVENT_ID = "handleFooterClick";
public static final String COLUMN_RESIZE_EVENT_ID = "columnResize";
private static final double CACHE_RATE_DEFAULT = 2;
/**
* The default multi select mode where simple left clicks only selects one
* item, CTRL+left click selects multiple items and SHIFT-left click selects
* a range of items.
*/
private static final int MULTISELECT_MODE_DEFAULT = 0;
/**
* multiple of pagelength which component will cache when requesting more
* rows
*/
private double cache_rate = CACHE_RATE_DEFAULT;
/**
* fraction of pageLenght which can be scrolled without making new request
*/
private double cache_react_rate = 0.75 * cache_rate;
public static final char ALIGN_CENTER = 'c';
public static final char ALIGN_LEFT = 'b';
public static final char ALIGN_RIGHT = 'e';
private int firstRowInViewPort = 0;
private int pageLength = 15;
private int lastRequestedFirstvisible = 0; // to detect "serverside scroll"
protected boolean showRowHeaders = false;
private String[] columnOrder;
protected ApplicationConnection client;
protected String paintableId;
private boolean immediate;
private boolean nullSelectionAllowed = true;
private int selectMode = Table.SELECT_MODE_NONE;
private final HashSet<String> selectedRowKeys = new HashSet<String>();
/*
* These are used when jumping between pages when pressing Home and End
*/
private boolean selectLastItemInNextRender = false;
private boolean selectFirstItemInNextRender = false;
private boolean focusFirstItemInNextRender = false;
private boolean focusLastItemInNextRender = false;
/*
* The currently focused row
*/
private VScrollTableRow focusedRow;
/*
* Helper to store selection range start in when using the keyboard
*/
private VScrollTableRow selectionRangeStart;
/*
* Flag for notifying when the selection has changed and should be sent to
* the server
*/
private boolean selectionChanged = false;
/*
* The speed (in pixels) which the scrolling scrolls vertically/horizontally
*/
private int scrollingVelocity = 10;
private Timer scrollingVelocityTimer = null;;
/**
* Represents a select range of rows
*/
private class SelectionRange {
/**
* The starting key of the range
*/
private int startRowKey;
/**
* The ending key of the range
*/
private int endRowKey;
/**
* Constuctor.
*
* @param startRowKey
* The range start. Must be less than endRowKey
* @param endRowKey
* The range end. Must be bigger than startRowKey
*/
public SelectionRange(int startRowKey, int endRowKey) {
this.startRowKey = startRowKey;
this.endRowKey = endRowKey;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return startRowKey + "-" + endRowKey;
}
public boolean inRange(int key) {
return key >= startRowKey && key <= endRowKey;
}
public int getStartKey() {
return startRowKey;
}
public int getEndKey() {
return endRowKey;
}
};
private final HashSet<SelectionRange> selectedRowRanges = new HashSet<SelectionRange>();
private boolean initializedAndAttached = false;
/**
* Flag to indicate if a column width recalculation is needed due update.
*/
private boolean headerChangedDuringUpdate = false;
private final TableHead tHead = new TableHead();
private final TableFooter tFoot = new TableFooter();
private final FocusableScrollPanel scrollBodyPanel = new FocusableScrollPanel();
private int totalRows;
private Set<String> collapsedColumns;
private final RowRequestHandler rowRequestHandler;
private VScrollTableBody scrollBody;
private int firstvisible = 0;
private boolean sortAscending;
private String sortColumn;
private boolean columnReordering;
/**
* This map contains captions and icon urls for actions like: * "33_c" ->
* "Edit" * "33_i" -> "http://dom.com/edit.png"
*/
private final HashMap<Object, String> actionMap = new HashMap<Object, String>();
private String[] visibleColOrder;
private boolean initialContentReceived = false;
private Element scrollPositionElement;
private boolean enabled;
private boolean showColHeaders;
private boolean showColFooters;
/** flag to indicate that table body has changed */
private boolean isNewBody = true;
/*
* Read from the "recalcWidths" -attribute. When it is true, the table will
* recalculate the widths for columns - desirable in some cases. For #1983,
* marked experimental.
*/
boolean recalcWidths = false;
private final ArrayList<Panel> lazyUnregistryBag = new ArrayList<Panel>();
private String height;
private String width = "";
private boolean rendering = false;
private boolean hasFocus = false;
private int dragmode;
private int multiselectmode;
public VScrollTable() {
scrollBodyPanel.setStyleName(CLASSNAME + "-body-wrapper");
/*
* Firefox auto-repeat works correctly only if we use a key press
* handler, other browsers handle it correctly when using a key down
* handler
*/
if (BrowserInfo.get().isGecko()) {
scrollBodyPanel.addKeyPressHandler(this);
} else {
scrollBodyPanel.addKeyDownHandler(this);
}
scrollBodyPanel.addFocusHandler(this);
scrollBodyPanel.addBlurHandler(this);
scrollBodyPanel.addScrollHandler(this);
scrollBodyPanel.setStyleName(CLASSNAME + "-body");
setStyleName(CLASSNAME);
add(tHead);
add(scrollBodyPanel);
add(tFoot);
rowRequestHandler = new RowRequestHandler();
/*
* We need to use the sinkEvents method to catch the keyUp events so we
* can cache a single shift. KeyUpHandler cannot do this.
*/
sinkEvents(Event.ONKEYUP);
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt.user
* .client.Event)
*/
@Override
public void onBrowserEvent(Event event) {
if (event.getTypeInt() == Event.ONKEYUP) {
if (event.getKeyCode() == KeyCodes.KEY_SHIFT) {
sendSelectedRows();
selectionRangeStart = null;
} else if ((event.getKeyCode() == getNavigationUpKey()
|| event.getKeyCode() == getNavigationDownKey()
|| event.getKeyCode() == getNavigationPageUpKey() || event
.getKeyCode() == getNavigationPageDownKey())
&& !event.getShiftKey()) {
sendSelectedRows();
if (scrollingVelocityTimer != null) {
scrollingVelocityTimer.cancel();
scrollingVelocityTimer = null;
scrollingVelocity = 10;
}
}
}
}
/**
* Fires a column resize event which sends the resize information to the
* server.
*
* @param columnId
* The columnId of the column which was resized
* @param originalWidth
* The width in pixels of the column before the resize event
* @param newWidth
* The width in pixels of the column after the resize event
*/
private void fireColumnResizeEvent(String columnId, int originalWidth,
int newWidth) {
client.updateVariable(paintableId, "columnResizeEventColumn", columnId,
false);
client.updateVariable(paintableId, "columnResizeEventPrev",
originalWidth, false);
client.updateVariable(paintableId, "columnResizeEventCurr", newWidth,
immediate);
}
/**
* Moves the focus one step down
*
* @return Returns true if succeeded
*/
private boolean moveFocusDown() {
return moveFocusDown(0);
}
/**
* Moves the focus down by 1+offset rows
*
* @return Returns true if succeeded, else false if the selection could not
* be move downwards
*/
private boolean moveFocusDown(int offset) {
if (isSelectable()) {
if (focusedRow == null && scrollBody.iterator().hasNext()) {
return setRowFocus((VScrollTableRow) scrollBody.iterator()
.next());
} else {
VScrollTableRow next = getNextRow(focusedRow, offset);
if (next != null) {
return setRowFocus(next);
}
}
}
return false;
}
/**
* Moves the selection one step up
*
* @return Returns true if succeeded
*/
private boolean moveFocusUp() {
return moveFocusUp(0);
}
/**
* Moves the focus row upwards
*
* @return Returns true if succeeded, else false if the selection could not
* be move upwards
*
*/
private boolean moveFocusUp(int offset) {
if (isSelectable()) {
if (focusedRow == null && scrollBody.iterator().hasNext()) {
return setRowFocus((VScrollTableRow) scrollBody.iterator()
.next());
} else {
VScrollTableRow prev = getPreviousRow(focusedRow, offset);
if (prev != null) {
return setRowFocus(prev);
}
}
}
return false;
}
/**
* Selects a row where the current selection head is
*
* @param ctrlSelect
* Is the selection a ctrl+selection
* @param shiftSelect
* Is the selection a shift+selection
* @return Returns truw
*/
private void selectFocusedRow(boolean ctrlSelect, boolean shiftSelect) {
if (focusedRow != null) {
// Arrows moves the selection and clears previous selections
if (isSelectable() && !ctrlSelect && !shiftSelect) {
deselectAll();
focusedRow.toggleSelection();
selectionRangeStart = focusedRow;
}
// Ctrl+arrows moves selection head
else if (isSelectable() && ctrlSelect && !shiftSelect) {
selectionRangeStart = focusedRow;
// No selection, only selection head is moved
}
// Shift+arrows selection selects a range
else if (selectMode == SELECT_MODE_MULTI && !ctrlSelect
&& shiftSelect) {
focusedRow.toggleShiftSelection(shiftSelect);
}
}
}
/**
* Sends the selection to the server if changed since the last update/visit.
*/
protected void sendSelectedRows() {
// Don't send anything if selection has not changed
if (!selectionChanged) {
return;
}
// Reset selection changed flag
selectionChanged = false;
// Note: changing the immediateness of this might require changes to
// "clickEvent" immediateness also.
if (multiselectmode == MULTISELECT_MODE_DEFAULT) {
// Convert ranges to a set of strings
Set<String> ranges = new HashSet<String>();
for (SelectionRange range : selectedRowRanges) {
ranges.add(range.toString());
}
// Send the selected row ranges
client.updateVariable(paintableId, "selectedRanges",
ranges.toArray(new String[selectedRowRanges.size()]), false);
}
// Send the selected rows
client.updateVariable(paintableId, "selected",
selectedRowKeys.toArray(new String[selectedRowKeys.size()]),
immediate);
}
/**
* Get the key that moves the selection head upwards. By default it is the
* up arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationUpKey() {
return KeyCodes.KEY_UP;
}
/**
* Get the key that moves the selection head downwards. By default it is the
* down arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationDownKey() {
return KeyCodes.KEY_DOWN;
}
/**
* Get the key that scrolls to the left in the table. By default it is the
* left arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationLeftKey() {
return KeyCodes.KEY_LEFT;
}
/**
* Get the key that scroll to the right on the table. By default it is the
* right arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationRightKey() {
return KeyCodes.KEY_RIGHT;
}
/**
* Get the key that selects an item in the table. By default it is the space
* bar key but by overriding this you can change the key to whatever you
* want.
*
* @return
*/
protected int getNavigationSelectKey() {
return 32;
}
/**
* Get the key the moves the selection one page up in the table. By default
* this is the Page Up key but by overriding this you can change the key to
* whatever you want.
*
* @return
*/
protected int getNavigationPageUpKey() {
return KeyCodes.KEY_PAGEUP;
}
/**
* Get the key the moves the selection one page down in the table. By
* default this is the Page Down key but by overriding this you can change
* the key to whatever you want.
*
* @return
*/
protected int getNavigationPageDownKey() {
return KeyCodes.KEY_PAGEDOWN;
}
/**
* Get the key the moves the selection to the beginning of the table. By
* default this is the Home key but by overriding this you can change the
* key to whatever you want.
*
* @return
*/
protected int getNavigationStartKey() {
return KeyCodes.KEY_HOME;
}
/**
* Get the key the moves the selection to the end of the table. By default
* this is the End key but by overriding this you can change the key to
* whatever you want.
*
* @return
*/
protected int getNavigationEndKey() {
return KeyCodes.KEY_END;
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.terminal.gwt.client.Paintable#updateFromUIDL(com.vaadin.terminal
* .gwt.client.UIDL, com.vaadin.terminal.gwt.client.ApplicationConnection)
*/
@SuppressWarnings("unchecked")
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
rendering = true;
/*
* We need to do this before updateComponent since updateComponent calls
* this.setHeight() which will calculate a new body height depending on
* the space available.
*/
if (uidl.hasAttribute("colfooters")) {
showColFooters = uidl.getBooleanAttribute("colfooters");
}
tFoot.setVisible(showColFooters);
if (client.updateComponent(this, uidl, true)) {
rendering = false;
return;
}
// we may have pending cache row fetch, cancel it. See #2136
rowRequestHandler.cancel();
enabled = !uidl.hasAttribute("disabled");
this.client = client;
paintableId = uidl.getStringAttribute("id");
immediate = uidl.getBooleanAttribute("immediate");
final int newTotalRows = uidl.getIntAttribute("totalrows");
if (newTotalRows != totalRows) {
if (scrollBody != null) {
if (totalRows == 0) {
tHead.clear();
tFoot.clear();
}
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
totalRows = newTotalRows;
}
dragmode = uidl.hasAttribute("dragmode") ? uidl
.getIntAttribute("dragmode") : 0;
multiselectmode = uidl.hasAttribute("multiselectmode") ? uidl
.getIntAttribute("multiselectmode") : MULTISELECT_MODE_DEFAULT;
setCacheRate(uidl.hasAttribute("cr") ? uidl.getDoubleAttribute("cr")
: CACHE_RATE_DEFAULT);
recalcWidths = uidl.hasAttribute("recalcWidths");
if (recalcWidths) {
tHead.clear();
tFoot.clear();
}
if (uidl.hasAttribute("pagelength")) {
pageLength = uidl.getIntAttribute("pagelength");
} else {
// pagelenght is "0" meaning scrolling is turned off
pageLength = totalRows;
}
firstvisible = uidl.hasVariable("firstvisible") ? uidl
.getIntVariable("firstvisible") : 0;
if (firstvisible != lastRequestedFirstvisible && scrollBody != null) {
// received 'surprising' firstvisible from server: scroll there
firstRowInViewPort = firstvisible;
scrollBodyPanel.setScrollPosition((int) (firstvisible * scrollBody
.getRowHeight()));
}
showRowHeaders = uidl.getBooleanAttribute("rowheaders");
showColHeaders = uidl.getBooleanAttribute("colheaders");
nullSelectionAllowed = uidl.hasAttribute("nsa") ? uidl
.getBooleanAttribute("nsa") : true;
if (uidl.hasVariable("sortascending")) {
sortAscending = uidl.getBooleanVariable("sortascending");
sortColumn = uidl.getStringVariable("sortcolumn");
}
if (uidl.hasVariable("selected")) {
final Set<String> selectedKeys = uidl
.getStringArrayVariableAsSet("selected");
if (scrollBody != null) {
Iterator<Widget> iterator = scrollBody.iterator();
while (iterator.hasNext()) {
VScrollTableRow row = (VScrollTableRow) iterator.next();
boolean selected = selectedKeys.contains(row.getKey());
if (selected != row.isSelected()) {
row.toggleSelection();
}
}
}
}
if (uidl.hasAttribute("selectmode")) {
if (uidl.getBooleanAttribute("readonly")) {
selectMode = Table.SELECT_MODE_NONE;
} else if (uidl.getStringAttribute("selectmode").equals("multi")) {
selectMode = Table.SELECT_MODE_MULTI;
} else if (uidl.getStringAttribute("selectmode").equals("single")) {
selectMode = Table.SELECT_MODE_SINGLE;
} else {
selectMode = Table.SELECT_MODE_NONE;
}
}
if (uidl.hasVariable("columnorder")) {
columnReordering = true;
columnOrder = uidl.getStringArrayVariable("columnorder");
} else {
columnReordering = false;
columnOrder = null;
}
if (uidl.hasVariable("collapsedcolumns")) {
tHead.setColumnCollapsingAllowed(true);
collapsedColumns = uidl
.getStringArrayVariableAsSet("collapsedcolumns");
} else {
tHead.setColumnCollapsingAllowed(false);
}
UIDL rowData = null;
UIDL ac = null;
for (final Iterator it = uidl.getChildIterator(); it.hasNext();) {
final UIDL c = (UIDL) it.next();
if (c.getTag().equals("rows")) {
rowData = c;
} else if (c.getTag().equals("actions")) {
updateActionMap(c);
} else if (c.getTag().equals("visiblecolumns")) {
tHead.updateCellsFromUIDL(c);
tFoot.updateCellsFromUIDL(c);
} else if (c.getTag().equals("-ac")) {
ac = c;
}
}
if (ac == null) {
if (dropHandler != null) {
// remove dropHandler if not present anymore
dropHandler = null;
}
} else {
if (dropHandler == null) {
dropHandler = new VScrollTableDropHandler();
}
dropHandler.updateAcceptRules(ac);
}
updateHeader(uidl.getStringArrayAttribute("vcolorder"));
updateFooter(uidl.getStringArrayAttribute("vcolorder"));
if (!recalcWidths && initializedAndAttached) {
updateBody(rowData, uidl.getIntAttribute("firstrow"),
uidl.getIntAttribute("rows"));
if (headerChangedDuringUpdate) {
lazyAdjustColumnWidths.schedule(1);
} else {
// webkits may still bug with their disturbing scrollbar bug,
// See #3457
// run overflow fix for scrollable area
DeferredCommand.addCommand(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel
.getElement());
}
});
}
} else {
if (scrollBody != null) {
scrollBody.removeFromParent();
lazyUnregistryBag.add(scrollBody);
}
scrollBody = createScrollBody();
scrollBody.renderInitialRows(rowData,
uidl.getIntAttribute("firstrow"),
uidl.getIntAttribute("rows"));
scrollBodyPanel.add(scrollBody);
initialContentReceived = true;
if (isAttached()) {
sizeInit();
}
scrollBody.restoreRowVisibility();
}
if (selectMode == Table.SELECT_MODE_NONE) {
scrollBody.addStyleName(CLASSNAME + "-body-noselection");
} else {
scrollBody.removeStyleName(CLASSNAME + "-body-noselection");
}
hideScrollPositionAnnotation();
purgeUnregistryBag();
// selection is no in sync with server, avoid excessive server visits by
// clearing to flag used during the normal operation
selectionChanged = false;
// This is called when the Home button has been pressed and the pages
// changes
if (selectFirstItemInNextRender) {
selectFirstRenderedRow(false);
selectFirstItemInNextRender = false;
}
if (focusFirstItemInNextRender) {
selectFirstRenderedRow(true);
focusFirstItemInNextRender = false;
}
// This is called when the End button has been pressed and the pages
// changes
if (selectLastItemInNextRender) {
selectLastRenderedRow(false);
selectLastItemInNextRender = false;
}
if (focusLastItemInNextRender) {
selectLastRenderedRow(true);
focusLastItemInNextRender = false;
}
if (focusedRow != null) {
if (!focusedRow.isAttached()) {
// focused row has orphaned, can't focus
focusedRow = null;
if (SELECT_MODE_SINGLE == selectMode
&& selectedRowKeys.size() > 0) {
// try to focusa row currently selected and in viewport
String selectedRowKey = selectedRowKeys.iterator().next();
if (selectedRowKey != null) {
setRowFocus(getRenderedRowByKey(selectedRowKey));
}
}
// TODO what should happen in multiselect mode?
} else {
setRowFocus(getRenderedRowByKey(focusedRow.getKey()));
}
}
setProperTabIndex();
rendering = false;
headerChangedDuringUpdate = false;
// Ensure that the focus has not scrolled outside the viewport
if (focusedRow != null) {
ensureRowIsVisible(focusedRow);
}
}
protected VScrollTableBody createScrollBody() {
return new VScrollTableBody();
}
/**
* Selects the last rendered row in the table
*
* @param focusOnly
* Should the focus only be moved to the last row
*/
private void selectLastRenderedRow(boolean focusOnly) {
VScrollTableRow row = null;
Iterator<Widget> it = scrollBody.iterator();
while (it.hasNext()) {
row = (VScrollTableRow) it.next();
}
if (row != null) {
setRowFocus(row);
if (!focusOnly) {
deselectAll();
selectFocusedRow(false, false);
sendSelectedRows();
}
}
}
/**
* Selects the first rendered row
*
* @param focusOnly
* Should the focus only be moved to the first row
*/
private void selectFirstRenderedRow(boolean focusOnly) {
setRowFocus((VScrollTableRow) scrollBody.iterator().next());
if (!focusOnly) {
deselectAll();
selectFocusedRow(false, false);
sendSelectedRows();
}
}
private void setCacheRate(double d) {
if (cache_rate != d) {
cache_rate = d;
cache_react_rate = 0.75 * d;
}
}
/**
* Unregisters Paintables in "trashed" HasWidgets (IScrollTableBodys or
* IScrollTableRows). This is done lazily as Table must survive from
* "subtreecaching" logic.
*/
private void purgeUnregistryBag() {
for (Iterator<Panel> iterator = lazyUnregistryBag.iterator(); iterator
.hasNext();) {
client.unregisterChildPaintables(iterator.next());
}
lazyUnregistryBag.clear();
}
private void updateActionMap(UIDL c) {
final Iterator<?> it = c.getChildIterator();
while (it.hasNext()) {
final UIDL action = (UIDL) it.next();
final String key = action.getStringAttribute("key");
final String caption = action.getStringAttribute("caption");
actionMap.put(key + "_c", caption);
if (action.hasAttribute("icon")) {
// TODO need some uri handling ??
actionMap.put(key + "_i", client.translateVaadinUri(action
.getStringAttribute("icon")));
}
}
}
public String getActionCaption(String actionKey) {
return actionMap.get(actionKey + "_c");
}
public String getActionIcon(String actionKey) {
return actionMap.get(actionKey + "_i");
}
private void updateHeader(String[] strings) {
if (strings == null) {
return;
}
int visibleCols = strings.length;
int colIndex = 0;
if (showRowHeaders) {
tHead.enableColumn("0", colIndex);
visibleCols++;
visibleColOrder = new String[visibleCols];
visibleColOrder[colIndex] = "0";
colIndex++;
} else {
visibleColOrder = new String[visibleCols];
tHead.removeCell("0");
}
int i;
for (i = 0; i < strings.length; i++) {
final String cid = strings[i];
visibleColOrder[colIndex] = cid;
tHead.enableColumn(cid, colIndex);
colIndex++;
}
tHead.setVisible(showColHeaders);
setContainerHeight();
}
/**
* Updates footers.
* <p>
* Update headers whould be called before this method is called!
* </p>
*
* @param strings
*/
private void updateFooter(String[] strings) {
if (strings == null) {
return;
}
// Add dummy column if row headers are present
int colIndex = 0;
if (showRowHeaders) {
tFoot.enableColumn("0", colIndex);
colIndex++;
} else {
tFoot.removeCell("0");
}
int i;
for (i = 0; i < strings.length; i++) {
final String cid = strings[i];
tFoot.enableColumn(cid, colIndex);
colIndex++;
}
tFoot.setVisible(showColFooters);
}
/**
* @param uidl
* which contains row data
* @param firstRow
* first row in data set
* @param reqRows
* amount of rows in data set
*/
private void updateBody(UIDL uidl, int firstRow, int reqRows) {
if (uidl == null || reqRows < 1) {
// container is empty, remove possibly existing rows
if (firstRow < 0) {
while (scrollBody.getLastRendered() > scrollBody.firstRendered) {
scrollBody.unlinkRow(false);
}
scrollBody.unlinkRow(false);
}
return;
}
scrollBody.renderRows(uidl, firstRow, reqRows);
final int optimalFirstRow = (int) (firstRowInViewPort - pageLength
* cache_rate);
boolean cont = true;
while (cont && scrollBody.getLastRendered() > optimalFirstRow
&& scrollBody.getFirstRendered() < optimalFirstRow) {
// removing row from start
cont = scrollBody.unlinkRow(true);
}
final int optimalLastRow = (int) (firstRowInViewPort + pageLength + pageLength
* cache_rate);
cont = true;
while (cont && scrollBody.getLastRendered() > optimalLastRow) {
// removing row from the end
cont = scrollBody.unlinkRow(false);
}
scrollBody.fixSpacers();
scrollBody.restoreRowVisibility();
}
/**
* Gives correct column index for given column key ("cid" in UIDL).
*
* @param colKey
* @return column index of visible columns, -1 if column not visible
*/
private int getColIndexByKey(String colKey) {
// return 0 if asked for rowHeaders
if ("0".equals(colKey)) {
return 0;
}
for (int i = 0; i < visibleColOrder.length; i++) {
if (visibleColOrder[i].equals(colKey)) {
return i;
}
}
return -1;
}
protected boolean isSelectable() {
return selectMode > Table.SELECT_MODE_NONE;
}
private boolean isCollapsedColumn(String colKey) {
if (collapsedColumns == null) {
return false;
}
if (collapsedColumns.contains(colKey)) {
return true;
}
return false;
}
private String getColKeyByIndex(int index) {
return tHead.getHeaderCell(index).getColKey();
}
private void setColWidth(int colIndex, int w, boolean isDefinedWidth) {
// Set header column width
final HeaderCell hcell = tHead.getHeaderCell(colIndex);
hcell.setWidth(w, isDefinedWidth);
// Set body column width
scrollBody.setColWidth(colIndex, w);
// Set footer column width
FooterCell fcell = tFoot.getFooterCell(colIndex);
fcell.setWidth(w, isDefinedWidth);
}
private int getColWidth(String colKey) {
return tHead.getHeaderCell(colKey).getWidth();
}
/**
* Get a rendered row by its key
*
* @param key
* The key to search with
* @return
*/
private VScrollTableRow getRenderedRowByKey(String key) {
if (scrollBody != null) {
final Iterator<Widget> it = scrollBody.iterator();
VScrollTableRow r = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (r.getKey().equals(key)) {
return r;
}
}
}
return null;
}
/**
* Returns the next row to the given row
*
* @param row
* The row to calculate from
*
* @return The next row or null if no row exists
*/
private VScrollTableRow getNextRow(VScrollTableRow row, int offset) {
final Iterator<Widget> it = scrollBody.iterator();
VScrollTableRow r = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (r == row) {
r = null;
while (offset >= 0 && it.hasNext()) {
r = (VScrollTableRow) it.next();
offset--;
}
return r;
}
}
return null;
}
/**
* Returns the previous row from the given row
*
* @param row
* The row to calculate from
* @return The previous row or null if no row exists
*/
private VScrollTableRow getPreviousRow(VScrollTableRow row, int offset) {
final Iterator<Widget> it = scrollBody.iterator();
final Iterator<Widget> offsetIt = scrollBody.iterator();
VScrollTableRow r = null;
VScrollTableRow prev = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (offset < 0) {
prev = (VScrollTableRow) offsetIt.next();
}
if (r == row) {
return prev;
}
offset--;
}
return null;
}
protected void reOrderColumn(String columnKey, int newIndex) {
final int oldIndex = getColIndexByKey(columnKey);
// Change header order
tHead.moveCell(oldIndex, newIndex);
// Change body order
scrollBody.moveCol(oldIndex, newIndex);
// Change footer order
tFoot.moveCell(oldIndex, newIndex);
/*
* Build new columnOrder and update it to server Note that columnOrder
* also contains collapsed columns so we cannot directly build it from
* cells vector Loop the old columnOrder and append in order to new
* array unless on moved columnKey. On new index also put the moved key
* i == index on columnOrder, j == index on newOrder
*/
final String oldKeyOnNewIndex = visibleColOrder[newIndex];
if (showRowHeaders) {
newIndex--; // columnOrder don't have rowHeader
}
// add back hidden rows,
for (int i = 0; i < columnOrder.length; i++) {
if (columnOrder[i].equals(oldKeyOnNewIndex)) {
break; // break loop at target
}
if (isCollapsedColumn(columnOrder[i])) {
newIndex++;
}
}
// finally we can build the new columnOrder for server
final String[] newOrder = new String[columnOrder.length];
for (int i = 0, j = 0; j < newOrder.length; i++) {
if (j == newIndex) {
newOrder[j] = columnKey;
j++;
}
if (i == columnOrder.length) {
break;
}
if (columnOrder[i].equals(columnKey)) {
continue;
}
newOrder[j] = columnOrder[i];
j++;
}
columnOrder = newOrder;
// also update visibleColumnOrder
int i = showRowHeaders ? 1 : 0;
for (int j = 0; j < newOrder.length; j++) {
final String cid = newOrder[j];
if (!isCollapsedColumn(cid)) {
visibleColOrder[i++] = cid;
}
}
client.updateVariable(paintableId, "columnorder", columnOrder, false);
}
@Override
protected void onAttach() {
super.onAttach();
if (initialContentReceived) {
sizeInit();
}
}
@Override
protected void onDetach() {
rowRequestHandler.cancel();
super.onDetach();
// ensure that scrollPosElement will be detached
if (scrollPositionElement != null) {
final Element parent = DOM.getParent(scrollPositionElement);
if (parent != null) {
DOM.removeChild(parent, scrollPositionElement);
}
}
}
/**
* Run only once when component is attached and received its initial
* content. This function : * Syncs headers and bodys "natural widths and
* saves the values. * Sets proper width and height * Makes deferred request
* to get some cache rows
*/
private void sizeInit() {
/*
* We will use browsers table rendering algorithm to find proper column
* widths. If content and header take less space than available, we will
* divide extra space relatively to each column which has not width set.
*
* Overflow pixels are added to last column.
*/
Iterator<Widget> headCells = tHead.iterator();
Iterator<Widget> footCells = tFoot.iterator();
int i = 0;
int totalExplicitColumnsWidths = 0;
int total = 0;
float expandRatioDivider = 0;
final int[] widths = new int[tHead.visibleCells.size()];
tHead.enableBrowserIntelligence();
tFoot.enableBrowserIntelligence();
// first loop: collect natural widths
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
final FooterCell fCell = (FooterCell) footCells.next();
int w = hCell.getWidth();
if (hCell.isDefinedWidth()) {
// server has defined column width explicitly
totalExplicitColumnsWidths += w;
} else {
if (hCell.getExpandRatio() > 0) {
expandRatioDivider += hCell.getExpandRatio();
w = 0;
} else {
// get and store greater of header width and column width,
// and
// store it as a minimumn natural col width
int headerWidth = hCell.getNaturalColumnWidth(i);
int footerWidth = fCell.getNaturalColumnWidth(i);
w = headerWidth > footerWidth ? headerWidth : footerWidth;
}
hCell.setNaturalMinimumColumnWidth(w);
fCell.setNaturalMinimumColumnWidth(w);
}
widths[i] = w;
total += w;
i++;
}
tHead.disableBrowserIntelligence();
tFoot.disableBrowserIntelligence();
boolean willHaveScrollbarz = willHaveScrollbars();
// fix "natural" width if width not set
if (width == null || "".equals(width)) {
int w = total;
w += scrollBody.getCellExtraWidth() * visibleColOrder.length;
if (willHaveScrollbarz) {
w += Util.getNativeScrollbarSize();
}
setContentWidth(w);
}
int availW = scrollBody.getAvailableWidth();
if (BrowserInfo.get().isIE()) {
// Hey IE, are you really sure about this?
availW = scrollBody.getAvailableWidth();
}
availW -= scrollBody.getCellExtraWidth() * visibleColOrder.length;
if (willHaveScrollbarz) {
availW -= Util.getNativeScrollbarSize();
}
// TODO refactor this code to be the same as in resize timer
boolean needsReLayout = false;
if (availW > total) {
// natural size is smaller than available space
final int extraSpace = availW - total;
final int totalWidthR = total - totalExplicitColumnsWidths;
needsReLayout = true;
if (expandRatioDivider > 0) {
// visible columns have some active expand ratios, excess
// space is divided according to them
headCells = tHead.iterator();
i = 0;
while (headCells.hasNext()) {
HeaderCell hCell = (HeaderCell) headCells.next();
if (hCell.getExpandRatio() > 0) {
int w = widths[i];
final int newSpace = (int) (extraSpace * (hCell
.getExpandRatio() / expandRatioDivider));
w += newSpace;
widths[i] = w;
}
i++;
}
} else if (totalWidthR > 0) {
// no expand ratios defined, we will share extra space
// relatively to "natural widths" among those without
// explicit width
headCells = tHead.iterator();
i = 0;
while (headCells.hasNext()) {
HeaderCell hCell = (HeaderCell) headCells.next();
if (!hCell.isDefinedWidth()) {
int w = widths[i];
final int newSpace = extraSpace * w / totalWidthR;
w += newSpace;
widths[i] = w;
}
i++;
}
}
} else {
// bodys size will be more than available and scrollbar will appear
}
// last loop: set possibly modified values or reset if new tBody
i = 0;
headCells = tHead.iterator();
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
if (isNewBody || hCell.getWidth() == -1) {
final int w = widths[i];
setColWidth(i, w, false);
}
i++;
}
initializedAndAttached = true;
if (needsReLayout) {
scrollBody.reLayoutComponents();
}
updatePageLength();
/*
* Fix "natural" height if height is not set. This must be after width
* fixing so the components' widths have been adjusted.
*/
if (height == null || "".equals(height)) {
/*
* We must force an update of the row height as this point as it
* might have been (incorrectly) calculated earlier
*/
int bodyHeight;
if (pageLength == totalRows) {
/*
* A hack to support variable height rows when paging is off.
* Generally this is not supported by scrolltable. We want to
* show all rows so the bodyHeight should be equal to the table
* height.
*/
// int bodyHeight = scrollBody.getOffsetHeight();
bodyHeight = scrollBody.getRequiredHeight();
} else {
bodyHeight = (int) Math.round(scrollBody.getRowHeight(true)
* pageLength);
}
boolean needsSpaceForHorizontalSrollbar = (total > availW);
if (needsSpaceForHorizontalSrollbar) {
bodyHeight += Util.getNativeScrollbarSize();
}
scrollBodyPanel.setHeight(bodyHeight + "px");
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
isNewBody = false;
if (firstvisible > 0) {
// Deferred due some Firefox oddities. IE & Safari could survive
// without
DeferredCommand.addCommand(new Command() {
public void execute() {
scrollBodyPanel
.setScrollPosition((int) (firstvisible * scrollBody
.getRowHeight()));
firstRowInViewPort = firstvisible;
}
});
}
if (enabled) {
// Do we need cache rows
if (scrollBody.getLastRendered() + 1 < firstRowInViewPort
+ pageLength + (int) cache_react_rate * pageLength) {
if (totalRows - 1 > scrollBody.getLastRendered()) {
// fetch cache rows
int firstInNewSet = scrollBody.getLastRendered() + 1;
rowRequestHandler.setReqFirstRow(firstInNewSet);
int lastInNewSet = (int) (firstRowInViewPort + pageLength + cache_rate
* pageLength);
if (lastInNewSet > totalRows - 1) {
lastInNewSet = totalRows - 1;
}
rowRequestHandler.setReqRows(lastInNewSet - firstInNewSet
+ 1);
rowRequestHandler.deferRowFetch(1);
}
}
}
/*
* Ensures the column alignments are correct at initial loading. <br/>
* (child components widths are correct)
*/
scrollBody.reLayoutComponents();
DeferredCommand.addCommand(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
});
}
/**
* Note, this method is not official api although declared as protected.
* Extend at you own risk.
*
* @return true if content area will have scrollbars visible.
*/
protected boolean willHaveScrollbars() {
if (!(height != null && !height.equals(""))) {
if (pageLength < totalRows) {
return true;
}
} else {
int fakeheight = (int) Math.round(scrollBody.getRowHeight()
* totalRows);
int availableHeight = scrollBodyPanel.getElement().getPropertyInt(
"clientHeight");
if (fakeheight > availableHeight) {
return true;
}
}
return false;
}
private void announceScrollPosition() {
if (scrollPositionElement == null) {
scrollPositionElement = DOM.createDiv();
scrollPositionElement.setClassName(CLASSNAME + "-scrollposition");
scrollPositionElement.getStyle().setPosition(Position.ABSOLUTE);
scrollPositionElement.getStyle().setDisplay(Display.NONE);
getElement().appendChild(scrollPositionElement);
}
Style style = scrollPositionElement.getStyle();
style.setMarginLeft(getElement().getOffsetWidth() / 2 - 80, Unit.PX);
style.setMarginTop(-scrollBodyPanel.getOffsetHeight(), Unit.PX);
// indexes go from 1-totalRows, as rowheaders in index-mode indicate
int last = (firstRowInViewPort + pageLength);
if (last > totalRows) {
last = totalRows;
}
scrollPositionElement.setInnerHTML("<span>" + (firstRowInViewPort + 1)
+ " – " + (last) + "..." + "</span>");
style.setDisplay(Display.BLOCK);
}
private void hideScrollPositionAnnotation() {
if (scrollPositionElement != null) {
DOM.setStyleAttribute(scrollPositionElement, "display", "none");
}
}
private class RowRequestHandler extends Timer {
private int reqFirstRow = 0;
private int reqRows = 0;
public void deferRowFetch() {
deferRowFetch(250);
}
public void deferRowFetch(int msec) {
if (reqRows > 0 && reqFirstRow < totalRows) {
schedule(msec);
// tell scroll position to user if currently "visible" rows are
// not rendered
if ((firstRowInViewPort + pageLength > scrollBody
.getLastRendered())
|| (firstRowInViewPort < scrollBody.getFirstRendered())) {
announceScrollPosition();
} else {
hideScrollPositionAnnotation();
}
}
}
public void setReqFirstRow(int reqFirstRow) {
if (reqFirstRow < 0) {
reqFirstRow = 0;
} else if (reqFirstRow >= totalRows) {
reqFirstRow = totalRows - 1;
}
this.reqFirstRow = reqFirstRow;
}
public void setReqRows(int reqRows) {
this.reqRows = reqRows;
}
@Override
public void run() {
if (client.hasActiveRequest()) {
// if client connection is busy, don't bother loading it more
schedule(250);
} else {
int firstToBeRendered = scrollBody.firstRendered;
if (reqFirstRow < firstToBeRendered) {
firstToBeRendered = reqFirstRow;
} else if (firstRowInViewPort - (int) (cache_rate * pageLength) > firstToBeRendered) {
firstToBeRendered = firstRowInViewPort
- (int) (cache_rate * pageLength);
if (firstToBeRendered < 0) {
firstToBeRendered = 0;
}
}
int lastToBeRendered = scrollBody.lastRendered;
if (reqFirstRow + reqRows - 1 > lastToBeRendered) {
lastToBeRendered = reqFirstRow + reqRows - 1;
} else if (firstRowInViewPort + pageLength + pageLength
* cache_rate < lastToBeRendered) {
lastToBeRendered = (firstRowInViewPort + pageLength + (int) (pageLength * cache_rate));
if (lastToBeRendered >= totalRows) {
lastToBeRendered = totalRows - 1;
}
// due Safari 3.1 bug (see #2607), verify reqrows, original
// problem unknown, but this should catch the issue
if (reqFirstRow + reqRows - 1 > lastToBeRendered) {
reqRows = lastToBeRendered - reqFirstRow;
}
}
client.updateVariable(paintableId, "firstToBeRendered",
firstToBeRendered, false);
client.updateVariable(paintableId, "lastToBeRendered",
lastToBeRendered, false);
// remember which firstvisible we requested, in case the server
// has
// a differing opinion
lastRequestedFirstvisible = firstRowInViewPort;
client.updateVariable(paintableId, "firstvisible",
firstRowInViewPort, false);
client.updateVariable(paintableId, "reqfirstrow", reqFirstRow,
false);
client.updateVariable(paintableId, "reqrows", reqRows, true);
}
}
public int getReqFirstRow() {
return reqFirstRow;
}
public int getReqRows() {
return reqRows;
}
/**
* Sends request to refresh content at this position.
*/
public void refreshContent() {
int first = (int) (firstRowInViewPort - pageLength * cache_rate);
int reqRows = (int) (2 * pageLength * cache_rate + pageLength);
if (first < 0) {
reqRows = reqRows + first;
first = 0;
}
setReqFirstRow(first);
setReqRows(reqRows);
run();
}
}
public class HeaderCell extends Widget {
Element td = DOM.createTD();
Element captionContainer = DOM.createDiv();
Element colResizeWidget = DOM.createDiv();
Element floatingCopyOfHeaderCell;
private boolean sortable = false;
private final String cid;
private boolean dragging;
private int dragStartX;
private int colIndex;
private int originalWidth;
private boolean isResizing;
private int headerX;
private boolean moved;
private int closestSlot;
private int width = -1;
private int naturalWidth = -1;
private char align = ALIGN_LEFT;
boolean definedWidth = false;
private float expandRatio = 0;
public void setSortable(boolean b) {
sortable = b;
}
public void setNaturalMinimumColumnWidth(int w) {
naturalWidth = w;
}
public HeaderCell(String colId, String headerText) {
cid = colId;
DOM.setElementProperty(colResizeWidget, "className", CLASSNAME
+ "-resizer");
DOM.sinkEvents(colResizeWidget, Event.MOUSEEVENTS);
setText(headerText);
DOM.appendChild(td, colResizeWidget);
DOM.setElementProperty(captionContainer, "className", CLASSNAME
+ "-caption-container");
// ensure no clipping initially (problem on column additions)
DOM.setStyleAttribute(captionContainer, "overflow", "visible");
DOM.sinkEvents(captionContainer, Event.MOUSEEVENTS);
DOM.appendChild(td, captionContainer);
DOM.sinkEvents(td, Event.MOUSEEVENTS);
setElement(td);
}
public void setWidth(int w, boolean ensureDefinedWidth) {
if (ensureDefinedWidth) {
definedWidth = true;
// on column resize expand ratio becomes zero
expandRatio = 0;
}
if (width == w) {
return;
}
if (width == -1) {
// go to default mode, clip content if necessary
DOM.setStyleAttribute(captionContainer, "overflow", "");
}
width = w;
if (w == -1) {
DOM.setStyleAttribute(captionContainer, "width", "");
setWidth("");
} else {
captionContainer.getStyle().setPropertyPx("width", w);
/*
* if we already have tBody, set the header width properly, if
* not defer it. IE will fail with complex float in table header
* unless TD width is not explicitly set.
*/
if (scrollBody != null) {
int tdWidth = width + scrollBody.getCellExtraWidth();
setWidth(tdWidth + "px");
} else {
DeferredCommand.addCommand(new Command() {
public void execute() {
int tdWidth = width
+ scrollBody.getCellExtraWidth();
setWidth(tdWidth + "px");
}
});
}
}
}
public void setUndefinedWidth() {
definedWidth = false;
setWidth(-1, false);
}
/**
* Detects if width is fixed by developer on server side or resized to
* current width by user.
*
* @return true if defined, false if "natural" width
*/
public boolean isDefinedWidth() {
return definedWidth;
}
public int getWidth() {
return width;
}
public void setText(String headerText) {
DOM.setInnerHTML(captionContainer, headerText);
}
public String getColKey() {
return cid;
}
private void setSorted(boolean sorted) {
if (sorted) {
if (sortAscending) {
this.setStyleName(CLASSNAME + "-header-cell-asc");
} else {
this.setStyleName(CLASSNAME + "-header-cell-desc");
}
} else {
this.setStyleName(CLASSNAME + "-header-cell");
}
}
/**
* Handle column reordering.
*/
@Override
public void onBrowserEvent(Event event) {
if (enabled && event != null) {
if (isResizing
|| event.getEventTarget().cast() == colResizeWidget) {
if (dragging && DOM.eventGetType(event) == Event.ONMOUSEUP) {
// Handle releasing column header on spacer #5318
handleCaptionEvent(event);
} else {
onResizeEvent(event);
}
} else {
handleCaptionEvent(event);
if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
scrollBodyPanel.setFocus(true);
}
event.stopPropagation();
event.preventDefault();
}
}
}
private void createFloatingCopy() {
floatingCopyOfHeaderCell = DOM.createDiv();
DOM.setInnerHTML(floatingCopyOfHeaderCell, DOM.getInnerHTML(td));
floatingCopyOfHeaderCell = DOM
.getChild(floatingCopyOfHeaderCell, 1);
DOM.setElementProperty(floatingCopyOfHeaderCell, "className",
CLASSNAME + "-header-drag");
updateFloatingCopysPosition(DOM.getAbsoluteLeft(td),
DOM.getAbsoluteTop(td));
DOM.appendChild(RootPanel.get().getElement(),
floatingCopyOfHeaderCell);
}
private void updateFloatingCopysPosition(int x, int y) {
x -= DOM.getElementPropertyInt(floatingCopyOfHeaderCell,
"offsetWidth") / 2;
DOM.setStyleAttribute(floatingCopyOfHeaderCell, "left", x + "px");
if (y > 0) {
DOM.setStyleAttribute(floatingCopyOfHeaderCell, "top", (y + 7)
+ "px");
}
}
private void hideFloatingCopy() {
DOM.removeChild(RootPanel.get().getElement(),
floatingCopyOfHeaderCell);
floatingCopyOfHeaderCell = null;
}
/**
* Fires a header click event after the user has clicked a column header
* cell
*
* @param event
* The click event
*/
private void fireHeaderClickedEvent(Event event) {
if (client.hasEventListeners(VScrollTable.this,
HEADER_CLICK_EVENT_ID)) {
MouseEventDetails details = new MouseEventDetails(event);
client.updateVariable(paintableId, "headerClickEvent",
details.toString(), false);
client.updateVariable(paintableId, "headerClickCID", cid, true);
}
}
protected void handleCaptionEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
if (columnReordering) {
dragging = true;
moved = false;
colIndex = getColIndexByKey(cid);
DOM.setCapture(getElement());
headerX = tHead.getAbsoluteLeft();
DOM.eventPreventDefault(event); // prevent selecting text
}
break;
case Event.ONMOUSEUP:
if (columnReordering) {
dragging = false;
DOM.releaseCapture(getElement());
if (moved) {
hideFloatingCopy();
tHead.removeSlotFocus();
if (closestSlot != colIndex
&& closestSlot != (colIndex + 1)) {
if (closestSlot > colIndex) {
reOrderColumn(cid, closestSlot - 1);
} else {
reOrderColumn(cid, closestSlot);
}
}
}
}
if (!moved) {
// mouse event was a click to header -> sort column
if (sortable) {
if (sortColumn.equals(cid)) {
// just toggle order
client.updateVariable(paintableId, "sortascending",
!sortAscending, false);
} else {
// set table scrolled by this column
client.updateVariable(paintableId, "sortcolumn",
cid, false);
}
// get also cache columns at the same request
scrollBodyPanel.setScrollPosition(0);
firstvisible = 0;
rowRequestHandler.setReqFirstRow(0);
rowRequestHandler.setReqRows((int) (2 * pageLength
* cache_rate + pageLength));
rowRequestHandler.deferRowFetch();
}
fireHeaderClickedEvent(event);
break;
}
break;
case Event.ONMOUSEMOVE:
if (dragging) {
if (!moved) {
createFloatingCopy();
moved = true;
}
final int x = DOM.eventGetClientX(event)
+ DOM.getElementPropertyInt(tHead.hTableWrapper,
"scrollLeft");
int slotX = headerX;
closestSlot = colIndex;
int closestDistance = -1;
int start = 0;
if (showRowHeaders) {
start++;
}
final int visibleCellCount = tHead.getVisibleCellCount();
for (int i = start; i <= visibleCellCount; i++) {
if (i > 0) {
final String colKey = getColKeyByIndex(i - 1);
slotX += getColWidth(colKey);
}
final int dist = Math.abs(x - slotX);
if (closestDistance == -1 || dist < closestDistance) {
closestDistance = dist;
closestSlot = i;
}
}
tHead.focusSlot(closestSlot);
updateFloatingCopysPosition(DOM.eventGetClientX(event), -1);
}
break;
default:
break;
}
}
private void onResizeEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
isResizing = true;
DOM.setCapture(getElement());
dragStartX = DOM.eventGetClientX(event);
colIndex = getColIndexByKey(cid);
originalWidth = getWidth();
DOM.eventPreventDefault(event);
break;
case Event.ONMOUSEUP:
isResizing = false;
DOM.releaseCapture(getElement());
// readjust undefined width columns
lazyAdjustColumnWidths.cancel();
lazyAdjustColumnWidths.schedule(1);
fireColumnResizeEvent(cid, originalWidth, getColWidth(cid));
break;
case Event.ONMOUSEMOVE:
if (isResizing) {
final int deltaX = DOM.eventGetClientX(event) - dragStartX;
if (deltaX == 0) {
return;
}
int newWidth = originalWidth + deltaX;
if (newWidth < scrollBody.getCellExtraWidth()) {
newWidth = scrollBody.getCellExtraWidth();
}
setColWidth(colIndex, newWidth, true);
}
break;
default:
break;
}
}
public String getCaption() {
return DOM.getInnerText(captionContainer);
}
public boolean isEnabled() {
return getParent() != null;
}
public void setAlign(char c) {
if (align != c) {
switch (c) {
case ALIGN_CENTER:
DOM.setStyleAttribute(captionContainer, "textAlign",
"center");
break;
case ALIGN_RIGHT:
DOM.setStyleAttribute(captionContainer, "textAlign",
"right");
break;
default:
DOM.setStyleAttribute(captionContainer, "textAlign", "");
break;
}
}
align = c;
}
public char getAlign() {
return align;
}
/**
* Detects the natural minimum width for the column of this header cell.
* If column is resized by user or the width is defined by server the
* actual width is returned. Else the natural min width is returned.
*
* @param columnIndex
* column index hint, if -1 (unknown) it will be detected
*
* @return
*/
public int getNaturalColumnWidth(int columnIndex) {
if (isDefinedWidth()) {
return width;
} else {
if (naturalWidth < 0) {
// This is recently revealed column. Try to detect a proper
// value (greater of header and data
// cols)
final int hw = ((Element) getElement().getLastChild())
.getOffsetWidth() + scrollBody.getCellExtraWidth();
if (columnIndex < 0) {
columnIndex = 0;
for (Iterator<Widget> it = tHead.iterator(); it
.hasNext(); columnIndex++) {
if (it.next() == this) {
break;
}
}
}
final int cw = scrollBody.getColWidth(columnIndex);
naturalWidth = (hw > cw ? hw : cw);
}
return naturalWidth;
}
}
public void setExpandRatio(float floatAttribute) {
expandRatio = floatAttribute;
}
public float getExpandRatio() {
return expandRatio;
}
}
/**
* HeaderCell that is header cell for row headers.
*
* Reordering disabled and clicking on it resets sorting.
*/
public class RowHeadersHeaderCell extends HeaderCell {
RowHeadersHeaderCell() {
super("0", "");
}
@Override
protected void handleCaptionEvent(Event event) {
// NOP: RowHeaders cannot be reordered
// TODO It'd be nice to reset sorting here
}
}
public class TableHead extends Panel implements ActionOwner {
private static final int WRAPPER_WIDTH = 900000;
ArrayList<Widget> visibleCells = new ArrayList<Widget>();
HashMap<String, HeaderCell> availableCells = new HashMap<String, HeaderCell>();
Element div = DOM.createDiv();
Element hTableWrapper = DOM.createDiv();
Element hTableContainer = DOM.createDiv();
Element table = DOM.createTable();
Element headerTableBody = DOM.createTBody();
Element tr = DOM.createTR();
private final Element columnSelector = DOM.createDiv();
private int focusedSlot = -1;
public TableHead() {
if (BrowserInfo.get().isIE()) {
table.setPropertyInt("cellSpacing", 0);
}
DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
DOM.setElementProperty(hTableWrapper, "className", CLASSNAME
+ "-header");
// TODO move styles to CSS
DOM.setElementProperty(columnSelector, "className", CLASSNAME
+ "-column-selector");
DOM.setStyleAttribute(columnSelector, "display", "none");
DOM.appendChild(table, headerTableBody);
DOM.appendChild(headerTableBody, tr);
DOM.appendChild(hTableContainer, table);
DOM.appendChild(hTableWrapper, hTableContainer);
DOM.appendChild(div, hTableWrapper);
DOM.appendChild(div, columnSelector);
setElement(div);
setStyleName(CLASSNAME + "-header-wrap");
DOM.sinkEvents(columnSelector, Event.ONCLICK);
availableCells.put("0", new RowHeadersHeaderCell());
}
@Override
public void clear() {
for (String cid : availableCells.keySet()) {
removeCell(cid);
}
availableCells.clear();
availableCells.put("0", new RowHeadersHeaderCell());
}
public void updateCellsFromUIDL(UIDL uidl) {
Iterator<?> it = uidl.getChildIterator();
HashSet<String> updated = new HashSet<String>();
updated.add("0");
while (it.hasNext()) {
final UIDL col = (UIDL) it.next();
final String cid = col.getStringAttribute("cid");
updated.add(cid);
String caption = buildCaptionHtmlSnippet(col);
HeaderCell c = getHeaderCell(cid);
if (c == null) {
c = new HeaderCell(cid, caption);
availableCells.put(cid, c);
if (initializedAndAttached) {
// we will need a column width recalculation
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
} else {
c.setText(caption);
}
if (col.hasAttribute("sortable")) {
c.setSortable(true);
if (cid.equals(sortColumn)) {
c.setSorted(true);
} else {
c.setSorted(false);
}
} else {
c.setSortable(false);
}
if (col.hasAttribute("align")) {
c.setAlign(col.getStringAttribute("align").charAt(0));
}
if (col.hasAttribute("width")) {
final String width = col.getStringAttribute("width");
c.setWidth(Integer.parseInt(width), true);
} else if (recalcWidths) {
c.setUndefinedWidth();
}
if (col.hasAttribute("er")) {
c.setExpandRatio(col.getFloatAttribute("er"));
}
if (col.hasAttribute("collapsed")) {
// ensure header is properly removed from parent (case when
// collapsing happens via servers side api)
if (c.isAttached()) {
c.removeFromParent();
headerChangedDuringUpdate = true;
}
}
}
// check for orphaned header cells
for (Iterator<String> cit = availableCells.keySet().iterator(); cit
.hasNext();) {
String cid = cit.next();
if (!updated.contains(cid)) {
removeCell(cid);
cit.remove();
}
}
}
public void enableColumn(String cid, int index) {
final HeaderCell c = getHeaderCell(cid);
if (!c.isEnabled() || getHeaderCell(index) != c) {
setHeaderCell(index, c);
if (initializedAndAttached) {
headerChangedDuringUpdate = true;
}
}
}
public int getVisibleCellCount() {
return visibleCells.size();
}
public void setHorizontalScrollPosition(int scrollLeft) {
if (BrowserInfo.get().isIE6()) {
hTableWrapper.getStyle().setProperty("position", "relative");
hTableWrapper.getStyle().setPropertyPx("left", -scrollLeft);
} else {
hTableWrapper.setScrollLeft(scrollLeft);
}
}
public void setColumnCollapsingAllowed(boolean cc) {
if (cc) {
DOM.setStyleAttribute(columnSelector, "display", "block");
} else {
DOM.setStyleAttribute(columnSelector, "display", "none");
}
}
public void disableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", WRAPPER_WIDTH
+ "px");
}
public void enableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", "");
}
public void setHeaderCell(int index, HeaderCell cell) {
if (cell.isEnabled()) {
// we're moving the cell
DOM.removeChild(tr, cell.getElement());
orphan(cell);
}
if (index < visibleCells.size()) {
// insert to right slot
DOM.insertChild(tr, cell.getElement(), index);
adopt(cell);
visibleCells.add(index, cell);
} else if (index == visibleCells.size()) {
// simply append
DOM.appendChild(tr, cell.getElement());
adopt(cell);
visibleCells.add(cell);
} else {
throw new RuntimeException(
"Header cells must be appended in order");
}
}
public HeaderCell getHeaderCell(int index) {
if (index < visibleCells.size()) {
return (HeaderCell) visibleCells.get(index);
} else {
return null;
}
}
/**
* Get's HeaderCell by it's column Key.
*
* Note that this returns HeaderCell even if it is currently collapsed.
*
* @param cid
* Column key of accessed HeaderCell
* @return HeaderCell
*/
public HeaderCell getHeaderCell(String cid) {
return availableCells.get(cid);
}
public void moveCell(int oldIndex, int newIndex) {
final HeaderCell hCell = getHeaderCell(oldIndex);
final Element cell = hCell.getElement();
visibleCells.remove(oldIndex);
DOM.removeChild(tr, cell);
DOM.insertChild(tr, cell, newIndex);
visibleCells.add(newIndex, hCell);
}
public Iterator<Widget> iterator() {
return visibleCells.iterator();
}
@Override
public boolean remove(Widget w) {
if (visibleCells.contains(w)) {
visibleCells.remove(w);
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
return true;
}
return false;
}
public void removeCell(String colKey) {
final HeaderCell c = getHeaderCell(colKey);
remove(c);
}
private void focusSlot(int index) {
removeSlotFocus();
if (index > 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, index - 1)),
"className", CLASSNAME + "-resizer " + CLASSNAME
+ "-focus-slot-right");
} else {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, index)),
"className", CLASSNAME + "-resizer " + CLASSNAME
+ "-focus-slot-left");
}
focusedSlot = index;
}
private void removeSlotFocus() {
if (focusedSlot < 0) {
return;
}
if (focusedSlot == 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, focusedSlot)),
"className", CLASSNAME + "-resizer");
} else if (focusedSlot > 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, focusedSlot - 1)),
"className", CLASSNAME + "-resizer");
}
focusedSlot = -1;
}
@Override
public void onBrowserEvent(Event event) {
if (enabled) {
if (event.getEventTarget().cast() == columnSelector) {
final int left = DOM.getAbsoluteLeft(columnSelector);
final int top = DOM.getAbsoluteTop(columnSelector)
+ DOM.getElementPropertyInt(columnSelector,
"offsetHeight");
client.getContextMenu().showAt(this, left, top);
}
}
}
@Override
protected void onDetach() {
super.onDetach();
if (client != null) {
client.getContextMenu().ensureHidden(this);
}
}
class VisibleColumnAction extends Action {
String colKey;
private boolean collapsed;
public VisibleColumnAction(String colKey) {
super(VScrollTable.TableHead.this);
this.colKey = colKey;
caption = tHead.getHeaderCell(colKey).getCaption();
}
@Override
public void execute() {
client.getContextMenu().hide();
// toggle selected column
if (collapsedColumns.contains(colKey)) {
collapsedColumns.remove(colKey);
} else {
tHead.removeCell(colKey);
collapsedColumns.add(colKey);
lazyAdjustColumnWidths.schedule(1);
}
// update variable to server
client.updateVariable(paintableId, "collapsedcolumns",
collapsedColumns.toArray(new String[collapsedColumns
.size()]), false);
// let rowRequestHandler determine proper rows
rowRequestHandler.refreshContent();
}
public void setCollapsed(boolean b) {
collapsed = b;
}
/**
* Override default method to distinguish on/off columns
*/
@Override
public String getHTML() {
final StringBuffer buf = new StringBuffer();
if (collapsed) {
buf.append("<span class=\"v-off\">");
} else {
buf.append("<span class=\"v-on\">");
}
buf.append(super.getHTML());
buf.append("</span>");
return buf.toString();
}
}
/*
* Returns columns as Action array for column select popup
*/
public Action[] getActions() {
Object[] cols;
if (columnReordering && columnOrder != null) {
cols = columnOrder;
} else {
// if columnReordering is disabled, we need different way to get
// all available columns
cols = visibleColOrder;
cols = new Object[visibleColOrder.length
+ collapsedColumns.size()];
int i;
for (i = 0; i < visibleColOrder.length; i++) {
cols[i] = visibleColOrder[i];
}
for (final Iterator<String> it = collapsedColumns.iterator(); it
.hasNext();) {
cols[i++] = it.next();
}
}
final Action[] actions = new Action[cols.length];
for (int i = 0; i < cols.length; i++) {
final String cid = (String) cols[i];
final HeaderCell c = getHeaderCell(cid);
final VisibleColumnAction a = new VisibleColumnAction(
c.getColKey());
a.setCaption(c.getCaption());
if (!c.isEnabled()) {
a.setCollapsed(true);
}
actions[i] = a;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
/**
* Returns column alignments for visible columns
*/
public char[] getColumnAlignments() {
final Iterator<Widget> it = visibleCells.iterator();
final char[] aligns = new char[visibleCells.size()];
int colIndex = 0;
while (it.hasNext()) {
aligns[colIndex++] = ((HeaderCell) it.next()).getAlign();
}
return aligns;
}
}
/**
* A cell in the footer
*/
public class FooterCell extends Widget {
private Element td = DOM.createTD();
private Element captionContainer = DOM.createDiv();
private char align = ALIGN_LEFT;
private int width = -1;
private float expandRatio = 0;
private String cid;
boolean definedWidth = false;
private int naturalWidth = -1;
public FooterCell(String colId, String headerText) {
cid = colId;
setText(headerText);
DOM.setElementProperty(captionContainer, "className", CLASSNAME
+ "-footer-container");
// ensure no clipping initially (problem on column additions)
DOM.setStyleAttribute(captionContainer, "overflow", "visible");
DOM.sinkEvents(captionContainer, Event.MOUSEEVENTS);
DOM.appendChild(td, captionContainer);
DOM.sinkEvents(td, Event.MOUSEEVENTS);
setElement(td);
}
/**
* Sets the text of the footer
*
* @param footerText
* The text in the footer
*/
public void setText(String footerText) {
DOM.setInnerHTML(captionContainer, footerText);
}
/**
* Set alignment of the text in the cell
*
* @param c
* The alignment which can be ALIGN_CENTER, ALIGN_LEFT,
* ALIGN_RIGHT
*/
public void setAlign(char c) {
if (align != c) {
switch (c) {
case ALIGN_CENTER:
DOM.setStyleAttribute(captionContainer, "textAlign",
"center");
break;
case ALIGN_RIGHT:
DOM.setStyleAttribute(captionContainer, "textAlign",
"right");
break;
default:
DOM.setStyleAttribute(captionContainer, "textAlign", "");
break;
}
}
align = c;
}
/**
* Get the alignment of the text int the cell
*
* @return Returns either ALIGN_CENTER, ALIGN_LEFT or ALIGN_RIGHT
*/
public char getAlign() {
return align;
}
/**
* Sets the width of the cell
*
* @param w
* The width of the cell
* @param ensureDefinedWidth
* Ensures the the given width is not recalculated
*/
public void setWidth(int w, boolean ensureDefinedWidth) {
if (ensureDefinedWidth) {
definedWidth = true;
// on column resize expand ratio becomes zero
expandRatio = 0;
}
if (width == w) {
return;
}
if (width == -1) {
// go to default mode, clip content if necessary
DOM.setStyleAttribute(captionContainer, "overflow", "");
}
width = w;
if (w == -1) {
DOM.setStyleAttribute(captionContainer, "width", "");
setWidth("");
} else {
/*
* Reduce width with one pixel for the right border since the
* footers does not have any spacers between them.
*/
int borderWidths = 1;
// Set the container width (check for negative value)
if (w - borderWidths >= 0) {
captionContainer.getStyle().setPropertyPx("width",
w - borderWidths);
} else {
captionContainer.getStyle().setPropertyPx("width", 0);
}
/*
* if we already have tBody, set the header width properly, if
* not defer it. IE will fail with complex float in table header
* unless TD width is not explicitly set.
*/
if (scrollBody != null) {
/*
* Reduce with one since footer does not have any spacers,
* instead a 1 pixel border.
*/
int tdWidth = width + scrollBody.getCellExtraWidth()
- borderWidths;
setWidth(tdWidth + "px");
} else {
DeferredCommand.addCommand(new Command() {
public void execute() {
int borderWidths = 1;
int tdWidth = width
+ scrollBody.getCellExtraWidth()
- borderWidths;
setWidth(tdWidth + "px");
}
});
}
}
}
/**
* Sets the width to undefined
*/
public void setUndefinedWidth() {
setWidth(-1, false);
}
/**
* Detects if width is fixed by developer on server side or resized to
* current width by user.
*
* @return true if defined, false if "natural" width
*/
public boolean isDefinedWidth() {
return definedWidth;
}
/**
* Returns the pixels width of the footer cell
*
* @return The width in pixels
*/
public int getWidth() {
return width;
}
/**
* Sets the expand ratio of the cell
*
* @param floatAttribute
* The expand ratio
*/
public void setExpandRatio(float floatAttribute) {
expandRatio = floatAttribute;
}
/**
* Returns the expand ration of the cell
*
* @return The expand ratio
*/
public float getExpandRatio() {
return expandRatio;
}
/**
* Is the cell enabled?
*
* @return True if enabled else False
*/
public boolean isEnabled() {
return getParent() != null;
}
/**
* Handle column clicking
*/
@Override
public void onBrowserEvent(Event event) {
if (enabled && event != null) {
handleCaptionEvent(event);
if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
scrollBodyPanel.setFocus(true);
}
}
}
/**
* Handles a event on the captions
*
* @param event
* The event to handle
*/
protected void handleCaptionEvent(Event event) {
if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
fireFooterClickedEvent(event);
}
}
/**
* Fires a footer click event after the user has clicked a column footer
* cell
*
* @param event
* The click event
*/
private void fireFooterClickedEvent(Event event) {
if (client.hasEventListeners(VScrollTable.this,
FOOTER_CLICK_EVENT_ID)) {
MouseEventDetails details = new MouseEventDetails(event);
client.updateVariable(paintableId, "footerClickEvent",
details.toString(), false);
client.updateVariable(paintableId, "footerClickCID", cid, true);
}
}
/**
* Returns the column key of the column
*
* @return The column key
*/
public String getColKey() {
return cid;
}
/**
* Detects the natural minimum width for the column of this header cell.
* If column is resized by user or the width is defined by server the
* actual width is returned. Else the natural min width is returned.
*
* @param columnIndex
* column index hint, if -1 (unknown) it will be detected
*
* @return
*/
public int getNaturalColumnWidth(int columnIndex) {
if (isDefinedWidth()) {
return width;
} else {
if (naturalWidth < 0) {
// This is recently revealed column. Try to detect a proper
// value (greater of header and data
// cols)
final int hw = ((Element) getElement().getLastChild())
.getOffsetWidth() + scrollBody.getCellExtraWidth();
if (columnIndex < 0) {
columnIndex = 0;
for (Iterator<Widget> it = tHead.iterator(); it
.hasNext(); columnIndex++) {
if (it.next() == this) {
break;
}
}
}
final int cw = scrollBody.getColWidth(columnIndex);
naturalWidth = (hw > cw ? hw : cw);
}
return naturalWidth;
}
}
public void setNaturalMinimumColumnWidth(int w) {
naturalWidth = w;
}
}
/**
* HeaderCell that is header cell for row headers.
*
* Reordering disabled and clicking on it resets sorting.
*/
public class RowHeadersFooterCell extends FooterCell {
RowHeadersFooterCell() {
super("0", "");
}
@Override
protected void handleCaptionEvent(Event event) {
// NOP: RowHeaders cannot be reordered
// TODO It'd be nice to reset sorting here
}
}
/**
* The footer of the table which can be seen in the bottom of the Table.
*/
public class TableFooter extends Panel {
private static final int WRAPPER_WIDTH = 900000;
ArrayList<Widget> visibleCells = new ArrayList<Widget>();
HashMap<String, FooterCell> availableCells = new HashMap<String, FooterCell>();
Element div = DOM.createDiv();
Element hTableWrapper = DOM.createDiv();
Element hTableContainer = DOM.createDiv();
Element table = DOM.createTable();
Element headerTableBody = DOM.createTBody();
Element tr = DOM.createTR();
public TableFooter() {
DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
DOM.setElementProperty(hTableWrapper, "className", CLASSNAME
+ "-footer");
DOM.appendChild(table, headerTableBody);
DOM.appendChild(headerTableBody, tr);
DOM.appendChild(hTableContainer, table);
DOM.appendChild(hTableWrapper, hTableContainer);
DOM.appendChild(div, hTableWrapper);
setElement(div);
setStyleName(CLASSNAME + "-footer-wrap");
availableCells.put("0", new RowHeadersFooterCell());
}
@Override
public void clear() {
for (String cid : availableCells.keySet()) {
removeCell(cid);
}
availableCells.clear();
availableCells.put("0", new RowHeadersFooterCell());
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.user.client.ui.Panel#remove(com.google.gwt.user.client
* .ui.Widget)
*/
@Override
public boolean remove(Widget w) {
if (visibleCells.contains(w)) {
visibleCells.remove(w);
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see com.google.gwt.user.client.ui.HasWidgets#iterator()
*/
public Iterator<Widget> iterator() {
return visibleCells.iterator();
}
/**
* Gets a footer cell which represents the given columnId
*
* @param cid
* The columnId
*
* @return The cell
*/
public FooterCell getFooterCell(String cid) {
return availableCells.get(cid);
}
/**
* Gets a footer cell by using a column index
*
* @param index
* The index of the column
* @return The Cell
*/
public FooterCell getFooterCell(int index) {
if (index < visibleCells.size()) {
return (FooterCell) visibleCells.get(index);
} else {
return null;
}
}
/**
* Updates the cells contents when updateUIDL request is received
*
* @param uidl
* The UIDL
*/
public void updateCellsFromUIDL(UIDL uidl) {
Iterator<?> columnIterator = uidl.getChildIterator();
HashSet<String> updated = new HashSet<String>();
updated.add("0");
while (columnIterator.hasNext()) {
final UIDL col = (UIDL) columnIterator.next();
final String cid = col.getStringAttribute("cid");
updated.add(cid);
String caption = col.getStringAttribute("fcaption");
FooterCell c = getFooterCell(cid);
if (c == null) {
c = new FooterCell(cid, caption);
availableCells.put(cid, c);
if (initializedAndAttached) {
// we will need a column width recalculation
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
} else {
c.setText(caption);
}
if (col.hasAttribute("align")) {
c.setAlign(col.getStringAttribute("align").charAt(0));
}
if (col.hasAttribute("width")) {
final String width = col.getStringAttribute("width");
c.setWidth(Integer.parseInt(width), true);
} else if (recalcWidths) {
c.setUndefinedWidth();
}
if (col.hasAttribute("er")) {
c.setExpandRatio(col.getFloatAttribute("er"));
}
if (col.hasAttribute("collapsed")) {
// ensure header is properly removed from parent (case when
// collapsing happens via servers side api)
if (c.isAttached()) {
c.removeFromParent();
headerChangedDuringUpdate = true;
}
}
}
// check for orphaned header cells
for (Iterator<String> cit = availableCells.keySet().iterator(); cit
.hasNext();) {
String cid = cit.next();
if (!updated.contains(cid)) {
removeCell(cid);
cit.remove();
}
}
}
/**
* Set a footer cell for a specified column index
*
* @param index
* The index
* @param cell
* The footer cell
*/
public void setFooterCell(int index, FooterCell cell) {
if (cell.isEnabled()) {
// we're moving the cell
DOM.removeChild(tr, cell.getElement());
orphan(cell);
}
if (index < visibleCells.size()) {
// insert to right slot
DOM.insertChild(tr, cell.getElement(), index);
adopt(cell);
visibleCells.add(index, cell);
} else if (index == visibleCells.size()) {
// simply append
DOM.appendChild(tr, cell.getElement());
adopt(cell);
visibleCells.add(cell);
} else {
throw new RuntimeException(
"Header cells must be appended in order");
}
}
/**
* Remove a cell by using the columnId
*
* @param colKey
* The columnId to remove
*/
public void removeCell(String colKey) {
final FooterCell c = getFooterCell(colKey);
remove(c);
}
/**
* Enable a column (Sets the footer cell)
*
* @param cid
* The columnId
* @param index
* The index of the column
*/
public void enableColumn(String cid, int index) {
final FooterCell c = getFooterCell(cid);
if (!c.isEnabled() || getFooterCell(index) != c) {
setFooterCell(index, c);
if (initializedAndAttached) {
headerChangedDuringUpdate = true;
}
}
}
/**
* Disable browser measurement of the table width
*/
public void disableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", WRAPPER_WIDTH
+ "px");
}
/**
* Enable browser measurement of the table width
*/
public void enableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", "");
}
/**
* Set the horizontal position in the cell in the footer. This is done
* when a horizontal scrollbar is present.
*
* @param scrollLeft
* The value of the leftScroll
*/
public void setHorizontalScrollPosition(int scrollLeft) {
if (BrowserInfo.get().isIE6()) {
hTableWrapper.getStyle().setProperty("position", "relative");
hTableWrapper.getStyle().setPropertyPx("left", -scrollLeft);
} else {
hTableWrapper.setScrollLeft(scrollLeft);
}
}
/**
* Swap cells when the column are dragged
*
* @param oldIndex
* The old index of the cell
* @param newIndex
* The new index of the cell
*/
public void moveCell(int oldIndex, int newIndex) {
final FooterCell hCell = getFooterCell(oldIndex);
final Element cell = hCell.getElement();
visibleCells.remove(oldIndex);
DOM.removeChild(tr, cell);
DOM.insertChild(tr, cell, newIndex);
visibleCells.add(newIndex, hCell);
}
}
/**
* This Panel can only contain VScrollTableRow type of widgets. This
* "simulates" very large table, keeping spacers which take room of
* unrendered rows.
*
*/
public class VScrollTableBody extends Panel {
public static final int DEFAULT_ROW_HEIGHT = 24;
private double rowHeight = -1;
private final List<Widget> renderedRows = new ArrayList<Widget>();
/**
* Due some optimizations row height measuring is deferred and initial
* set of rows is rendered detached. Flag set on when table body has
* been attached in dom and rowheight has been measured.
*/
private boolean tBodyMeasurementsDone = false;
Element preSpacer = DOM.createDiv();
Element postSpacer = DOM.createDiv();
Element container = DOM.createDiv();
TableSectionElement tBodyElement = Document.get().createTBodyElement();
Element table = DOM.createTable();
private int firstRendered;
private int lastRendered;
private char[] aligns;
protected VScrollTableBody() {
constructDOM();
setElement(container);
}
/**
* @return the height of scrollable body, subpixels ceiled.
*/
public int getRequiredHeight() {
return preSpacer.getOffsetHeight() + postSpacer.getOffsetHeight()
+ Util.getRequiredHeight(table);
}
private void constructDOM() {
DOM.setElementProperty(table, "className", CLASSNAME + "-table");
if (BrowserInfo.get().isIE()) {
table.setPropertyInt("cellSpacing", 0);
}
DOM.setElementProperty(preSpacer, "className", CLASSNAME
+ "-row-spacer");
DOM.setElementProperty(postSpacer, "className", CLASSNAME
+ "-row-spacer");
table.appendChild(tBodyElement);
DOM.appendChild(container, preSpacer);
DOM.appendChild(container, table);
DOM.appendChild(container, postSpacer);
}
public int getAvailableWidth() {
int availW = scrollBodyPanel.getOffsetWidth() - getBorderWidth();
return availW;
}
public void renderInitialRows(UIDL rowData, int firstIndex, int rows) {
firstRendered = firstIndex;
lastRendered = firstIndex + rows - 1;
final Iterator<?> it = rowData.getChildIterator();
aligns = tHead.getColumnAlignments();
while (it.hasNext()) {
final VScrollTableRow row = createRow((UIDL) it.next(), aligns);
addRow(row);
}
if (isAttached()) {
fixSpacers();
}
}
public void renderRows(UIDL rowData, int firstIndex, int rows) {
// FIXME REVIEW
aligns = tHead.getColumnAlignments();
final Iterator<?> it = rowData.getChildIterator();
if (firstIndex == lastRendered + 1) {
while (it.hasNext()) {
final VScrollTableRow row = prepareRow((UIDL) it.next());
addRow(row);
lastRendered++;
}
fixSpacers();
} else if (firstIndex + rows == firstRendered) {
final VScrollTableRow[] rowArray = new VScrollTableRow[rows];
int i = rows;
while (it.hasNext()) {
i--;
rowArray[i] = prepareRow((UIDL) it.next());
}
for (i = 0; i < rows; i++) {
addRowBeforeFirstRendered(rowArray[i]);
firstRendered--;
}
} else {
// completely new set of rows
while (lastRendered + 1 > firstRendered) {
unlinkRow(false);
}
final VScrollTableRow row = prepareRow((UIDL) it.next());
firstRendered = firstIndex;
lastRendered = firstIndex - 1;
addRow(row);
lastRendered++;
setContainerHeight();
fixSpacers();
while (it.hasNext()) {
addRow(prepareRow((UIDL) it.next()));
lastRendered++;
}
fixSpacers();
}
// this may be a new set of rows due content change,
// ensure we have proper cache rows
int reactFirstRow = (int) (firstRowInViewPort - pageLength
* cache_react_rate);
int reactLastRow = (int) (firstRowInViewPort + pageLength + pageLength
* cache_react_rate);
if (reactFirstRow < 0) {
reactFirstRow = 0;
}
if (reactLastRow >= totalRows) {
reactLastRow = totalRows - 1;
}
if (lastRendered < reactLastRow) {
// get some cache rows below visible area
rowRequestHandler.setReqFirstRow(lastRendered + 1);
rowRequestHandler.setReqRows(reactLastRow - lastRendered);
rowRequestHandler.deferRowFetch(1);
} else if (scrollBody.getFirstRendered() > reactFirstRow) {
/*
* Branch for fetching cache above visible area.
*
* If cache needed for both before and after visible area, this
* will be rendered after-cache is reveived and rendered. So in
* some rare situations table may take two cache visits to
* server.
*/
rowRequestHandler.setReqFirstRow(reactFirstRow);
rowRequestHandler.setReqRows(firstRendered - reactFirstRow);
rowRequestHandler.deferRowFetch(1);
}
}
/**
* This method is used to instantiate new rows for this table. It
* automatically sets correct widths to rows cells and assigns correct
* client reference for child widgets.
*
* This method can be called only after table has been initialized
*
* @param uidl
*/
private VScrollTableRow prepareRow(UIDL uidl) {
final VScrollTableRow row = createRow(uidl, aligns);
final int cells = DOM.getChildCount(row.getElement());
for (int i = 0; i < cells; i++) {
final Element cell = DOM.getChild(row.getElement(), i);
int w = VScrollTable.this.getColWidth(getColKeyByIndex(i));
if (w < 0) {
w = 0;
}
cell.getFirstChildElement().getStyle()
.setPropertyPx("width", w);
cell.getStyle().setPropertyPx("width", w);
}
return row;
}
protected VScrollTableRow createRow(UIDL uidl, char[] aligns2) {
return new VScrollTableRow(uidl, aligns);
}
private void addRowBeforeFirstRendered(VScrollTableRow row) {
VScrollTableRow first = null;
if (renderedRows.size() > 0) {
first = (VScrollTableRow) renderedRows.get(0);
}
if (first != null && first.getStyleName().indexOf("-odd") == -1) {
row.addStyleName(CLASSNAME + "-row-odd");
} else {
row.addStyleName(CLASSNAME + "-row");
}
if (row.isSelected()) {
row.addStyleName("v-selected");
}
tBodyElement.insertBefore(row.getElement(),
tBodyElement.getFirstChild());
adopt(row);
renderedRows.add(0, row);
}
private void addRow(VScrollTableRow row) {
VScrollTableRow last = null;
if (renderedRows.size() > 0) {
last = (VScrollTableRow) renderedRows
.get(renderedRows.size() - 1);
}
if (last != null && last.getStyleName().indexOf("-odd") == -1) {
row.addStyleName(CLASSNAME + "-row-odd");
} else {
row.addStyleName(CLASSNAME + "-row");
}
if (row.isSelected()) {
row.addStyleName("v-selected");
}
tBodyElement.appendChild(row.getElement());
adopt(row);
renderedRows.add(row);
}
public Iterator<Widget> iterator() {
return renderedRows.iterator();
}
/**
* @return false if couldn't remove row
*/
public boolean unlinkRow(boolean fromBeginning) {
if (lastRendered - firstRendered < 0) {
return false;
}
int index;
if (fromBeginning) {
index = 0;
firstRendered++;
} else {
index = renderedRows.size() - 1;
lastRendered--;
}
if (index >= 0) {
final VScrollTableRow toBeRemoved = (VScrollTableRow) renderedRows
.get(index);
lazyUnregistryBag.add(toBeRemoved);
tBodyElement.removeChild(toBeRemoved.getElement());
orphan(toBeRemoved);
renderedRows.remove(index);
fixSpacers();
return true;
} else {
return false;
}
}
@Override
public boolean remove(Widget w) {
throw new UnsupportedOperationException();
}
@Override
protected void onAttach() {
super.onAttach();
setContainerHeight();
}
/**
* Fix container blocks height according to totalRows to avoid
* "bouncing" when scrolling
*/
private void setContainerHeight() {
fixSpacers();
DOM.setStyleAttribute(container, "height", totalRows
* getRowHeight() + "px");
}
private void fixSpacers() {
int prepx = (int) Math.round(getRowHeight() * firstRendered);
if (prepx < 0) {
prepx = 0;
}
preSpacer.getStyle().setPropertyPx("height", prepx);
int postpx = (int) (getRowHeight() * (totalRows - 1 - lastRendered));
if (postpx < 0) {
postpx = 0;
}
postSpacer.getStyle().setPropertyPx("height", postpx);
}
public double getRowHeight() {
return getRowHeight(false);
}
public double getRowHeight(boolean forceUpdate) {
if (tBodyMeasurementsDone && !forceUpdate) {
return rowHeight;
} else {
if (tBodyElement.getRows().getLength() > 0) {
int tableHeight = getTableHeight();
int rowCount = tBodyElement.getRows().getLength();
rowHeight = tableHeight / (double) rowCount;
} else {
if (isAttached()) {
// measure row height by adding a dummy row
VScrollTableRow scrollTableRow = new VScrollTableRow();
tBodyElement.appendChild(scrollTableRow.getElement());
getRowHeight(forceUpdate);
tBodyElement.removeChild(scrollTableRow.getElement());
} else {
// TODO investigate if this can never happen anymore
return DEFAULT_ROW_HEIGHT;
}
}
tBodyMeasurementsDone = true;
return rowHeight;
}
}
public int getTableHeight() {
return table.getOffsetHeight();
}
/**
* Returns the width available for column content.
*
* @param columnIndex
* @return
*/
public int getColWidth(int columnIndex) {
if (tBodyMeasurementsDone) {
NodeList<TableRowElement> rows = tBodyElement.getRows();
if (rows.getLength() == 0) {
// no rows yet rendered
return 0;
} else {
com.google.gwt.dom.client.Element wrapperdiv = rows
.getItem(0).getCells().getItem(columnIndex)
.getFirstChildElement();
return wrapperdiv.getOffsetWidth();
}
} else {
return 0;
}
}
/**
* Sets the content width of a column.
*
* Due IE limitation, we must set the width to a wrapper elements inside
* table cells (with overflow hidden, which does not work on td
* elements).
*
* To get this work properly crossplatform, we will also set the width
* of td.
*
* @param colIndex
* @param w
*/
public void setColWidth(int colIndex, int w) {
NodeList<TableRowElement> rows2 = tBodyElement.getRows();
final int rows = rows2.getLength();
for (int i = 0; i < rows; i++) {
TableRowElement row = rows2.getItem(i);
TableCellElement cell = row.getCells().getItem(colIndex);
cell.getFirstChildElement().getStyle()
.setPropertyPx("width", w);
cell.getStyle().setPropertyPx("width", w);
}
}
private int cellExtraWidth = -1;
/**
* Method to return the space used for cell paddings + border.
*/
private int getCellExtraWidth() {
if (cellExtraWidth < 0) {
detectExtrawidth();
}
return cellExtraWidth;
}
private void detectExtrawidth() {
NodeList<TableRowElement> rows = tBodyElement.getRows();
if (rows.getLength() == 0) {
/* need to temporary add empty row and detect */
VScrollTableRow scrollTableRow = new VScrollTableRow();
tBodyElement.appendChild(scrollTableRow.getElement());
detectExtrawidth();
tBodyElement.removeChild(scrollTableRow.getElement());
} else {
boolean noCells = false;
TableRowElement item = rows.getItem(0);
TableCellElement firstTD = item.getCells().getItem(0);
if (firstTD == null) {
// content is currently empty, we need to add a fake cell
// for measuring
noCells = true;
VScrollTableRow next = (VScrollTableRow) iterator().next();
next.addCell(null, "", ALIGN_LEFT, "", true);
firstTD = item.getCells().getItem(0);
}
com.google.gwt.dom.client.Element wrapper = firstTD
.getFirstChildElement();
cellExtraWidth = firstTD.getOffsetWidth()
- wrapper.getOffsetWidth();
if (noCells) {
firstTD.getParentElement().removeChild(firstTD);
}
}
}
private void reLayoutComponents() {
for (Widget w : this) {
VScrollTableRow r = (VScrollTableRow) w;
for (Widget widget : r) {
client.handleComponentRelativeSize(widget);
}
}
}
public int getLastRendered() {
return lastRendered;
}
public int getFirstRendered() {
return firstRendered;
}
public void moveCol(int oldIndex, int newIndex) {
// loop all rows and move given index to its new place
final Iterator<?> rows = iterator();
while (rows.hasNext()) {
final VScrollTableRow row = (VScrollTableRow) rows.next();
final Element td = DOM.getChild(row.getElement(), oldIndex);
DOM.removeChild(row.getElement(), td);
DOM.insertChild(row.getElement(), td, newIndex);
}
}
/**
* Restore row visibility which is set to "none" when the row is
* rendered (due a performance optimization).
*/
private void restoreRowVisibility() {
for (Widget row : renderedRows) {
row.getElement().getStyle().setProperty("visibility", "");
}
}
public class VScrollTableRow extends Panel implements ActionOwner,
Container {
private static final int DRAGMODE_MULTIROW = 2;
protected ArrayList<Widget> childWidgets = new ArrayList<Widget>();
private boolean selected = false;
protected final int rowKey;
private List<UIDL> pendingComponentPaints;
private String[] actionKeys = null;
private final TableRowElement rowElement;
private boolean mDown;
private VScrollTableRow(int rowKey) {
this.rowKey = rowKey;
rowElement = Document.get().createTRElement();
setElement(rowElement);
DOM.sinkEvents(getElement(), Event.MOUSEEVENTS
| Event.ONDBLCLICK | Event.ONCONTEXTMENU
| Event.ONKEYDOWN);
}
private void paintComponent(Paintable p, UIDL uidl) {
if (isAttached()) {
p.updateFromUIDL(uidl, client);
} else {
if (pendingComponentPaints == null) {
pendingComponentPaints = new LinkedList<UIDL>();
}
pendingComponentPaints.add(uidl);
}
}
@Override
protected void onAttach() {
super.onAttach();
if (pendingComponentPaints != null) {
for (UIDL uidl : pendingComponentPaints) {
Paintable paintable = client.getPaintable(uidl);
paintable.updateFromUIDL(uidl, client);
}
}
}
@Override
protected void onDetach() {
super.onDetach();
client.getContextMenu().ensureHidden(this);
}
public String getKey() {
return String.valueOf(rowKey);
}
public VScrollTableRow(UIDL uidl, char[] aligns) {
this(uidl.getIntAttribute("key"));
/*
* Rendering the rows as hidden improves Firefox and Safari
* performance drastically.
*/
getElement().getStyle().setProperty("visibility", "hidden");
String rowStyle = uidl.getStringAttribute("rowstyle");
if (rowStyle != null) {
addStyleName(CLASSNAME + "-row-" + rowStyle);
}
tHead.getColumnAlignments();
int col = 0;
int visibleColumnIndex = -1;
// row header
if (showRowHeaders) {
addCell(uidl, buildCaptionHtmlSnippet(uidl), aligns[col++],
"", true);
}
if (uidl.hasAttribute("al")) {
actionKeys = uidl.getStringArrayAttribute("al");
}
final Iterator<?> cells = uidl.getChildIterator();
while (cells.hasNext()) {
final Object cell = cells.next();
visibleColumnIndex++;
String columnId = visibleColOrder[visibleColumnIndex];
String style = "";
if (uidl.hasAttribute("style-" + columnId)) {
style = uidl.getStringAttribute("style-" + columnId);
}
if (cell instanceof String) {
addCell(uidl, cell.toString(), aligns[col++], style,
false);
} else {
final Paintable cellContent = client
.getPaintable((UIDL) cell);
addCell(uidl, (Widget) cellContent, aligns[col++],
style);
paintComponent(cellContent, (UIDL) cell);
}
}
if (uidl.hasAttribute("selected") && !isSelected()) {
toggleSelection();
}
}
/**
* Add a dummy row, used for measurements if Table is empty.
*/
public VScrollTableRow() {
this(0);
addStyleName(CLASSNAME + "-row");
addCell(null, "_", 'b', "", true);
}
public void addCell(UIDL rowUidl, String text, char align,
String style, boolean textIsHTML) {
// String only content is optimized by not using Label widget
final Element td = DOM.createTD();
final Element container = DOM.createDiv();
String className = CLASSNAME + "-cell-content";
if (style != null && !style.equals("")) {
className += " " + CLASSNAME + "-cell-content-" + style;
}
td.setClassName(className);
container.setClassName(CLASSNAME + "-cell-wrapper");
if (textIsHTML) {
container.setInnerHTML(text);
} else {
container.setInnerText(text);
}
if (align != ALIGN_LEFT) {
switch (align) {
case ALIGN_CENTER:
container.getStyle().setProperty("textAlign", "center");
break;
case ALIGN_RIGHT:
default:
container.getStyle().setProperty("textAlign", "right");
break;
}
}
td.appendChild(container);
getElement().appendChild(td);
}
public void addCell(UIDL rowUidl, Widget w, char align, String style) {
final Element td = DOM.createTD();
final Element container = DOM.createDiv();
String className = CLASSNAME + "-cell-content";
if (style != null && !style.equals("")) {
className += " " + CLASSNAME + "-cell-content-" + style;
}
td.setClassName(className);
container.setClassName(CLASSNAME + "-cell-wrapper");
// TODO most components work with this, but not all (e.g.
// Select)
// Old comment: make widget cells respect align.
// text-align:center for IE, margin: auto for others
if (align != ALIGN_LEFT) {
switch (align) {
case ALIGN_CENTER:
container.getStyle().setProperty("textAlign", "center");
break;
case ALIGN_RIGHT:
default:
container.getStyle().setProperty("textAlign", "right");
break;
}
}
td.appendChild(container);
getElement().appendChild(td);
// ensure widget not attached to another element (possible tBody
// change)
w.removeFromParent();
container.appendChild(w.getElement());
adopt(w);
childWidgets.add(w);
}
public Iterator<Widget> iterator() {
return childWidgets.iterator();
}
@Override
public boolean remove(Widget w) {
if (childWidgets.contains(w)) {
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()),
w.getElement());
childWidgets.remove(w);
return true;
} else {
return false;
}
}
private void handleClickEvent(Event event, Element targetTdOrTr) {
if (client.hasEventListeners(VScrollTable.this,
ITEM_CLICK_EVENT_ID)) {
boolean doubleClick = (DOM.eventGetType(event) == Event.ONDBLCLICK);
/* This row was clicked */
client.updateVariable(paintableId, "clickedKey", ""
+ rowKey, false);
if (getElement() == targetTdOrTr.getParentElement()) {
/* A specific column was clicked */
int childIndex = DOM.getChildIndex(getElement(),
targetTdOrTr);
String colKey = null;
colKey = tHead.getHeaderCell(childIndex).getColKey();
client.updateVariable(paintableId, "clickedColKey",
colKey, false);
}
MouseEventDetails details = new MouseEventDetails(event);
boolean imm = true;
if (immediate && event.getButton() == Event.BUTTON_LEFT
&& !doubleClick && isSelectable() && !isSelected()) {
/*
* A left click when the table is selectable and in
* immediate mode on a row that is not currently
* selected will cause a selection event to be fired
* after this click event. By making the click event
* non-immediate we avoid sending two separate messages
* to the server.
*/
imm = false;
}
client.updateVariable(paintableId, "clickEvent",
details.toString(), imm);
}
}
/**
* Add this to the element mouse down event by using
* element.setPropertyJSO
* ("onselectstart",applyDisableTextSelectionIEHack()); Remove it
* then again when the mouse is depressed in the mouse up event.
*
* @return Returns the JSO preventing text selection
*/
private native JavaScriptObject applyDisableTextSelectionIEHack()
/*-{
return function(){ return false; };
}-*/;
/*
* React on click that occur on content cells only
*/
@Override
public void onBrowserEvent(Event event) {
if (enabled) {
int type = event.getTypeInt();
Element targetTdOrTr = getEventTargetTdOrTr(event);
if (type == Event.ONCONTEXTMENU) {
showContextMenu(event);
event.stopPropagation();
return;
}
if (targetTdOrTr != null) {
switch (type) {
case Event.ONDBLCLICK:
handleClickEvent(event, targetTdOrTr);
break;
case Event.ONMOUSEUP:
mDown = false;
handleClickEvent(event, targetTdOrTr);
scrollBodyPanel.setFocus(true);
if (event.getButton() == Event.BUTTON_LEFT
&& isSelectable()) {
// Ctrl+Shift click
if ((event.getCtrlKey() || event.getMetaKey())
&& event.getShiftKey()
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
toggleShiftSelection(false);
setRowFocus(this);
// Ctrl click
} else if ((event.getCtrlKey() || event
.getMetaKey())
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
toggleSelection();
setRowFocus(this);
// Ctrl click (Single selection)
} else if ((event.getCtrlKey() || event
.getMetaKey()
&& selectMode == SELECT_MODE_SINGLE)) {
if (!isSelected()
|| (isSelected() && nullSelectionAllowed)) {
if (!isSelected()) {
deselectAll();
}
toggleSelection();
setRowFocus(this);
}
// Shift click
} else if (event.getShiftKey()
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
toggleShiftSelection(true);
// click
} else {
boolean currentlyJustThisRowSelected = selectedRowKeys
.size() == 1
&& selectedRowKeys
.contains(getKey());
if (!currentlyJustThisRowSelected) {
if (multiselectmode == MULTISELECT_MODE_DEFAULT) {
deselectAll();
}
toggleSelection();
} else if (selectMode == SELECT_MODE_SINGLE
&& nullSelectionAllowed) {
toggleSelection();
}/*
* else NOP to avoid excessive server
* visits (selection is removed with
* CTRL/META click)
*/
selectionRangeStart = this;
setRowFocus(this);
}
// Remove IE text selection hack
if (BrowserInfo.get().isIE()) {
((Element) event.getEventTarget().cast())
.setPropertyJSO("onselectstart",
null);
}
sendSelectedRows();
}
break;
case Event.ONMOUSEDOWN:
if (dragmode != 0
&& event.getButton() == NativeEvent.BUTTON_LEFT) {
mDown = true;
VTransferable transferable = new VTransferable();
transferable.setDragSource(VScrollTable.this);
transferable.setData("itemId", "" + rowKey);
NodeList<TableCellElement> cells = rowElement
.getCells();
for (int i = 0; i < cells.getLength(); i++) {
if (cells.getItem(i).isOrHasChild(
targetTdOrTr)) {
HeaderCell headerCell = tHead
.getHeaderCell(i);
transferable.setData("propertyId",
headerCell.cid);
break;
}
}
VDragEvent ev = VDragAndDropManager.get()
.startDrag(transferable, event, true);
if (dragmode == DRAGMODE_MULTIROW
&& selectMode == SELECT_MODE_MULTI
&& selectedRowKeys
.contains("" + rowKey)) {
ev.createDragImage(
(Element) scrollBody.tBodyElement
.cast(), true);
Element dragImage = ev.getDragImage();
int i = 0;
for (Iterator<Widget> iterator = scrollBody
.iterator(); iterator.hasNext();) {
VScrollTableRow next = (VScrollTableRow) iterator
.next();
Element child = (Element) dragImage
.getChild(i++);
if (!selectedRowKeys.contains(""
+ next.rowKey)) {
child.getStyle().setVisibility(
Visibility.HIDDEN);
}
}
} else {
ev.createDragImage(getElement(), true);
}
// because we are preventing the default (due to
// prevent text selection) we must ensure
// gaining the focus.
ensureFocus();
event.preventDefault();
event.stopPropagation();
} else if (event.getCtrlKey()
|| event.getShiftKey()
|| event.getMetaKey()
&& selectMode == SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT) {
// because we are preventing the default (due to
// prevent text selection) we must ensure
// gaining the focus.
ensureFocus();
// Prevent default text selection in Firefox
event.preventDefault();
// Prevent default text selection in IE
if (BrowserInfo.get().isIE()) {
((Element) event.getEventTarget().cast())
.setPropertyJSO(
"onselectstart",
applyDisableTextSelectionIEHack());
}
event.stopPropagation();
}
break;
case Event.ONMOUSEOUT:
mDown = false;
break;
default:
break;
}
}
}
super.onBrowserEvent(event);
}
/**
* Finds the TD that the event interacts with. Returns null if the
* target of the event should not be handled. If the event target is
* the row directly this method returns the TR element instead of
* the TD.
*
* @param event
* @return TD or TR element that the event targets (the actual event
* target is this element or a child of it)
*/
private Element getEventTargetTdOrTr(Event event) {
Element targetTdOrTr = null;
final Element eventTarget = DOM.eventGetTarget(event);
final Element eventTargetParent = DOM.getParent(eventTarget);
final Element eventTargetGrandParent = DOM
.getParent(eventTargetParent);
final Element thisTrElement = getElement();
if (eventTarget == thisTrElement) {
// This was a click on the TR element
targetTdOrTr = eventTarget;
// rowTarget = true;
} else if (thisTrElement == eventTargetParent) {
// Target parent is the TR, so the actual target is the TD
targetTdOrTr = eventTarget;
} else if (thisTrElement == eventTargetGrandParent) {
// Target grand parent is the TR, so the parent is the TD
targetTdOrTr = eventTargetParent;
} else {
/*
* This is a workaround to make Labels, read only TextFields
* and Embedded in a Table clickable (see #2688). It is
* really not a fix as it does not work with a custom read
* only components (not extending VLabel/VEmbedded).
*/
Widget widget = Util.findWidget(eventTarget, null);
if (widget != this) {
while (widget != null && widget.getParent() != this) {
widget = widget.getParent();
}
if (widget != null) {
// widget is now the closest widget to this row
if (widget instanceof VLabel
|| widget instanceof VEmbedded
|| (widget instanceof VTextField && ((VTextField) widget)
.isReadOnly())) {
Element tdElement = eventTargetParent;
while (DOM.getParent(tdElement) != thisTrElement) {
tdElement = DOM.getParent(tdElement);
}
targetTdOrTr = tdElement;
}
}
}
}
return targetTdOrTr;
}
public void showContextMenu(Event event) {
if (enabled && actionKeys != null) {
int left = event.getClientX();
int top = event.getClientY();
top += Window.getScrollTop();
left += Window.getScrollLeft();
client.getContextMenu().showAt(this, left, top);
}
event.stopPropagation();
event.preventDefault();
}
/**
* Has the row been selected?
*
* @return Returns true if selected, else false
*/
public boolean isSelected() {
return selected;
}
/**
* Toggle the selection of the row
*/
public void toggleSelection() {
selected = !selected;
selectionChanged = true;
if (selected) {
selectedRowKeys.add(String.valueOf(rowKey));
addStyleName("v-selected");
} else {
removeStyleName("v-selected");
selectedRowKeys.remove(String.valueOf(rowKey));
}
removeKeyFromSelectedRange(rowKey);
}
/**
* Is called when a user clicks an item when holding SHIFT key down.
* This will select a new range from the last cell clicked
*
* @param deselectPrevious
* Should the previous selected range be deselected
*/
private void toggleShiftSelection(boolean deselectPrevious) {
/*
* Ensures that we are in multiselect mode and that we have a
* previous selection which was not a deselection
*/
if (selectMode == SELECT_MODE_SINGLE) {
// No previous selection found
deselectAll();
toggleSelection();
return;
}
// Set the selectable range
int startKey;
if (selectionRangeStart != null) {
startKey = Integer.valueOf(selectionRangeStart.getKey());
} else {
startKey = Integer.valueOf(focusedRow.getKey());
}
int endKey = rowKey;
if (endKey < startKey) {
// Swap keys if in the wrong order
startKey ^= endKey;
endKey ^= startKey;
startKey ^= endKey;
}
// Deselect previous items if so desired
if (deselectPrevious) {
deselectAll();
}
// Select the range (not including this row)
VScrollTableRow startRow = getRenderedRowByKey(String
.valueOf(startKey));
VScrollTableRow endRow = getRenderedRowByKey(String
.valueOf(endKey));
// If start row is null then we have a multipage selection from
// above
if (startRow == null) {
startRow = (VScrollTableRow) scrollBody.iterator().next();
setRowFocus(endRow);
}
if (endRow == null) {
setRowFocus(startRow);
}
Iterator<Widget> rows = scrollBody.iterator();
boolean startSelection = false;
while (rows.hasNext()) {
VScrollTableRow row = (VScrollTableRow) rows.next();
if (row == startRow || startSelection) {
startSelection = true;
if (!row.isSelected()) {
row.toggleSelection();
}
selectedRowKeys.add(row.getKey());
}
if (row == endRow && row != null) {
startSelection = false;
}
}
// Add range
if (startRow != endRow) {
selectedRowRanges.add(new SelectionRange(startKey, endKey));
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.ui.IActionOwner#getActions ()
*/
public Action[] getActions() {
if (actionKeys == null) {
return new Action[] {};
}
final Action[] actions = new Action[actionKeys.length];
for (int i = 0; i < actions.length; i++) {
final String actionKey = actionKeys[i];
final TreeAction a = new TreeAction(this,
String.valueOf(rowKey), actionKey);
a.setCaption(getActionCaption(actionKey));
a.setIconUrl(getActionIcon(actionKey));
actions[i] = a;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
public RenderSpace getAllocatedSpace(Widget child) {
int w = 0;
int i = getColIndexOf(child);
HeaderCell headerCell = tHead.getHeaderCell(i);
if (headerCell != null) {
if (initializedAndAttached) {
w = headerCell.getWidth();
} else {
// header offset width is not absolutely correct value,
// but a best guess (expecting similar content in all
// columns ->
// if one component is relative width so are others)
w = headerCell.getOffsetWidth() - getCellExtraWidth();
}
}
return new RenderSpace(w, 0) {
@Override
public int getHeight() {
return (int) getRowHeight();
}
};
}
private int getColIndexOf(Widget child) {
com.google.gwt.dom.client.Element widgetCell = child
.getElement().getParentElement().getParentElement();
NodeList<TableCellElement> cells = rowElement.getCells();
for (int i = 0; i < cells.getLength(); i++) {
if (cells.getItem(i) == widgetCell) {
return i;
}
}
return -1;
}
public boolean hasChildComponent(Widget component) {
return childWidgets.contains(component);
}
public void replaceChildComponent(Widget oldComponent,
Widget newComponent) {
com.google.gwt.dom.client.Element parentElement = oldComponent
.getElement().getParentElement();
int index = childWidgets.indexOf(oldComponent);
oldComponent.removeFromParent();
parentElement.appendChild(newComponent.getElement());
childWidgets.add(index, newComponent);
adopt(newComponent);
}
public boolean requestLayout(Set<Paintable> children) {
// row size should never change and system wouldn't event
// survive as this is a kind of fake paitable
return true;
}
public void updateCaption(Paintable component, UIDL uidl) {
// NOP, not rendered
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Should never be called,
// Component container interface faked here to get layouts
// render properly
}
}
/**
* Ensure the component has a focus.
*
* TODO the current implementation simply always calls focus for the
* component. In case the Table at some point implements focus/blur
* listeners, this method needs to be evolved to conditionally call
* focus only if not currently focused.
*/
protected void ensureFocus() {
focus();
}
}
/**
* Deselects all items
*/
public void deselectAll() {
final Object[] keys = selectedRowKeys.toArray();
for (int i = 0; i < keys.length; i++) {
final VScrollTableRow row = getRenderedRowByKey((String) keys[i]);
if (row != null && row.isSelected()) {
row.toggleSelection();
removeKeyFromSelectedRange(Integer.parseInt(row.getKey()));
}
}
// still ensure all selects are removed from (not necessary rendered)
selectedRowKeys.clear();
selectedRowRanges.clear();
}
/**
* Determines the pagelength when the table height is fixed.
*/
public void updatePageLength() {
// Only update if visible and enabled
if (!isVisible() || !enabled) {
return;
}
if (scrollBody == null) {
return;
}
if (height == null || height.equals("")) {
return;
}
int rowHeight = (int) scrollBody.getRowHeight();
int bodyH = scrollBodyPanel.getOffsetHeight();
int rowsAtOnce = bodyH / rowHeight;
boolean anotherPartlyVisible = ((bodyH % rowHeight) != 0);
if (anotherPartlyVisible) {
rowsAtOnce++;
}
if (pageLength != rowsAtOnce) {
pageLength = rowsAtOnce;
client.updateVariable(paintableId, "pagelength", pageLength, false);
if (!rendering) {
int currentlyVisible = scrollBody.lastRendered
- scrollBody.firstRendered;
if (currentlyVisible < pageLength
&& currentlyVisible < totalRows) {
// shake scrollpanel to fill empty space
scrollBodyPanel.setScrollPosition(scrollTop + 1);
scrollBodyPanel.setScrollPosition(scrollTop - 1);
}
}
}
}
@Override
public void setWidth(String width) {
if (this.width.equals(width)) {
return;
}
this.width = width;
if (width != null && !"".equals(width)) {
super.setWidth(width);
int innerPixels = getOffsetWidth() - getBorderWidth();
if (innerPixels < 0) {
innerPixels = 0;
}
setContentWidth(innerPixels);
if (!rendering) {
// readjust undefined width columns
lazyAdjustColumnWidths.cancel();
lazyAdjustColumnWidths.schedule(LAZY_COLUMN_ADJUST_TIMEOUT);
}
} else {
super.setWidth("");
}
/*
* setting width may affect wheter the component has scrollbars ->
* needs scrolling or not
*/
setProperTabIndex();
}
private static final int LAZY_COLUMN_ADJUST_TIMEOUT = 300;
private final Timer lazyAdjustColumnWidths = new Timer() {
/**
* Check for column widths, and available width, to see if we can fix
* column widths "optimally". Doing this lazily to avoid expensive
* calculation when resizing is not yet finished.
*/
@Override
public void run() {
Iterator<Widget> headCells = tHead.iterator();
int usedMinimumWidth = 0;
int totalExplicitColumnsWidths = 0;
float expandRatioDivider = 0;
int colIndex = 0;
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
if (hCell.isDefinedWidth()) {
totalExplicitColumnsWidths += hCell.getWidth();
usedMinimumWidth += hCell.getWidth();
} else {
usedMinimumWidth += hCell.getNaturalColumnWidth(colIndex);
expandRatioDivider += hCell.getExpandRatio();
}
colIndex++;
}
int availW = scrollBody.getAvailableWidth();
// Hey IE, are you really sure about this?
availW = scrollBody.getAvailableWidth();
int visibleCellCount = tHead.getVisibleCellCount();
availW -= scrollBody.getCellExtraWidth() * visibleCellCount;
if (willHaveScrollbars()) {
availW -= Util.getNativeScrollbarSize();
}
int extraSpace = availW - usedMinimumWidth;
if (extraSpace < 0) {
extraSpace = 0;
}
int totalUndefinedNaturaWidths = usedMinimumWidth
- totalExplicitColumnsWidths;
// we have some space that can be divided optimally
HeaderCell hCell;
colIndex = 0;
headCells = tHead.iterator();
while (headCells.hasNext()) {
hCell = (HeaderCell) headCells.next();
if (!hCell.isDefinedWidth()) {
int w = hCell.getNaturalColumnWidth(colIndex);
int newSpace;
if (expandRatioDivider > 0) {
// divide excess space by expand ratios
newSpace = (int) (w + extraSpace
* hCell.getExpandRatio() / expandRatioDivider);
} else {
if (totalUndefinedNaturaWidths != 0) {
// divide relatively to natural column widths
newSpace = w + extraSpace * w
/ totalUndefinedNaturaWidths;
} else {
newSpace = w;
}
}
setColWidth(colIndex, newSpace, false);
}
colIndex++;
}
if ((height == null || "".equals(height))
&& totalRows == pageLength) {
// fix body height (may vary if lazy loading is offhorizontal
// scrollbar appears/disappears)
int bodyHeight = scrollBody.getRequiredHeight();
boolean needsSpaceForHorizontalSrollbar = (availW < usedMinimumWidth);
if (needsSpaceForHorizontalSrollbar) {
bodyHeight += Util.getNativeScrollbarSize();
}
int heightBefore = getOffsetHeight();
scrollBodyPanel.setHeight(bodyHeight + "px");
if (heightBefore != getOffsetHeight()) {
Util.notifyParentOfSizeChange(VScrollTable.this, false);
}
}
scrollBody.reLayoutComponents();
DeferredCommand.addCommand(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
});
}
};
/**
* helper to set pixel size of head and body part
*
* @param pixels
*/
private void setContentWidth(int pixels) {
tHead.setWidth(pixels + "px");
scrollBodyPanel.setWidth(pixels + "px");
tFoot.setWidth(pixels + "px");
}
private int borderWidth = -1;
/**
* @return border left + border right
*/
private int getBorderWidth() {
if (borderWidth < 0) {
borderWidth = Util.measureHorizontalPaddingAndBorder(
scrollBodyPanel.getElement(), 2);
if (borderWidth < 0) {
borderWidth = 0;
}
}
return borderWidth;
}
/**
* Ensures scrollable area is properly sized. This method is used when fixed
* size is used.
*/
private int containerHeight;
private void setContainerHeight() {
if (height != null && !"".equals(height)) {
containerHeight = getOffsetHeight();
containerHeight -= showColHeaders ? tHead.getOffsetHeight() : 0;
containerHeight -= tFoot.getOffsetHeight();
containerHeight -= getContentAreaBorderHeight();
if (containerHeight < 0) {
containerHeight = 0;
}
scrollBodyPanel.setHeight(containerHeight + "px");
}
}
private int contentAreaBorderHeight = -1;
private int scrollLeft;
private int scrollTop;
private VScrollTableDropHandler dropHandler;
/**
* @return border top + border bottom of the scrollable area of table
*/
private int getContentAreaBorderHeight() {
if (contentAreaBorderHeight < 0) {
if (BrowserInfo.get().isIE7() || BrowserInfo.get().isIE6()) {
contentAreaBorderHeight = Util
.measureVerticalBorder(scrollBodyPanel.getElement());
} else {
DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
"hidden");
int oh = scrollBodyPanel.getOffsetHeight();
int ch = scrollBodyPanel.getElement().getPropertyInt(
"clientHeight");
contentAreaBorderHeight = oh - ch;
DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
"auto");
}
}
return contentAreaBorderHeight;
}
@Override
public void setHeight(String height) {
this.height = height;
super.setHeight(height);
setContainerHeight();
if (initializedAndAttached) {
updatePageLength();
}
if (!rendering) {
// Webkit may sometimes get an odd rendering bug (white space
// between header and body), see bug #3875. Running
// overflow hack here to shake body element a bit.
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
/*
* setting height may affect wheter the component has scrollbars ->
* needs scrolling or not
*/
setProperTabIndex();
}
/*
* Overridden due Table might not survive of visibility change (scroll pos
* lost). Example ITabPanel just set contained components invisible and back
* when changing tabs.
*/
@Override
public void setVisible(boolean visible) {
if (isVisible() != visible) {
super.setVisible(visible);
if (initializedAndAttached) {
if (visible) {
DeferredCommand.addCommand(new Command() {
public void execute() {
scrollBodyPanel
.setScrollPosition((int) (firstRowInViewPort * scrollBody
.getRowHeight()));
}
});
}
}
}
}
/**
* Helper function to build html snippet for column or row headers
*
* @param uidl
* possibly with values caption and icon
* @return html snippet containing possibly an icon + caption text
*/
protected String buildCaptionHtmlSnippet(UIDL uidl) {
String s = uidl.getStringAttribute("caption");
if (uidl.hasAttribute("icon")) {
s = "<img src=\""
+ client.translateVaadinUri(uidl.getStringAttribute("icon"))
+ "\" alt=\"icon\" class=\"v-icon\">" + s;
}
return s;
}
/**
* This method has logic which rows needs to be requested from server when
* user scrolls
*/
public void onScroll(ScrollEvent event) {
scrollLeft = scrollBodyPanel.getElement().getScrollLeft();
scrollTop = scrollBodyPanel.getScrollPosition();
if (!initializedAndAttached) {
return;
}
if (!enabled) {
scrollBodyPanel
.setScrollPosition((int) (firstRowInViewPort * scrollBody
.getRowHeight()));
return;
}
rowRequestHandler.cancel();
if (BrowserInfo.get().isSafari() && event != null && scrollTop == 0) {
// due to the webkitoverflowworkaround, top may sometimes report 0
// for webkit, although it really is not. Expecting to have the
// correct
// value available soon.
DeferredCommand.addCommand(new Command() {
public void execute() {
onScroll(null);
}
});
return;
}
// fix headers horizontal scrolling
tHead.setHorizontalScrollPosition(scrollLeft);
// fix footers horizontal scrolling
tFoot.setHorizontalScrollPosition(scrollLeft);
firstRowInViewPort = (int) Math.ceil(scrollTop
/ scrollBody.getRowHeight());
if (firstRowInViewPort > totalRows - pageLength) {
firstRowInViewPort = totalRows - pageLength;
}
int postLimit = (int) (firstRowInViewPort + (pageLength - 1) + pageLength
* cache_react_rate);
if (postLimit > totalRows - 1) {
postLimit = totalRows - 1;
}
int preLimit = (int) (firstRowInViewPort - pageLength
* cache_react_rate);
if (preLimit < 0) {
preLimit = 0;
}
final int lastRendered = scrollBody.getLastRendered();
final int firstRendered = scrollBody.getFirstRendered();
if (postLimit <= lastRendered && preLimit >= firstRendered) {
// remember which firstvisible we requested, in case the server has
// a differing opinion
lastRequestedFirstvisible = firstRowInViewPort;
client.updateVariable(paintableId, "firstvisible",
firstRowInViewPort, false);
return; // scrolled withing "non-react area"
}
if (firstRowInViewPort - pageLength * cache_rate > lastRendered
|| firstRowInViewPort + pageLength + pageLength * cache_rate < firstRendered) {
// need a totally new set
rowRequestHandler
.setReqFirstRow((firstRowInViewPort - (int) (pageLength * cache_rate)));
int last = firstRowInViewPort + (int) (cache_rate * pageLength)
+ pageLength - 1;
if (last >= totalRows) {
last = totalRows - 1;
}
rowRequestHandler.setReqRows(last
- rowRequestHandler.getReqFirstRow() + 1);
rowRequestHandler.deferRowFetch();
return;
}
if (preLimit < firstRendered) {
// need some rows to the beginning of the rendered area
rowRequestHandler
.setReqFirstRow((int) (firstRowInViewPort - pageLength
* cache_rate));
rowRequestHandler.setReqRows(firstRendered
- rowRequestHandler.getReqFirstRow());
rowRequestHandler.deferRowFetch();
return;
}
if (postLimit > lastRendered) {
// need some rows to the end of the rendered area
rowRequestHandler.setReqFirstRow(lastRendered + 1);
rowRequestHandler.setReqRows((int) ((firstRowInViewPort
+ pageLength + pageLength * cache_rate) - lastRendered));
rowRequestHandler.deferRowFetch();
}
}
public VScrollTableDropHandler getDropHandler() {
return dropHandler;
}
private static class TableDDDetails {
int overkey = -1;
VerticalDropLocation dropLocation;
String colkey;
@Override
public boolean equals(Object obj) {
if (obj instanceof TableDDDetails) {
TableDDDetails other = (TableDDDetails) obj;
return dropLocation == other.dropLocation
&& overkey == other.overkey
&& ((colkey != null && colkey.equals(other.colkey)) || (colkey == null && other.colkey == null));
}
return false;
}
// @Override
// public int hashCode() {
// return overkey;
// }
}
public class VScrollTableDropHandler extends VAbstractDropHandler {
private static final String ROWSTYLEBASE = "v-table-row-drag-";
private TableDDDetails dropDetails;
private TableDDDetails lastEmphasized;
@Override
public void dragEnter(VDragEvent drag) {
updateDropDetails(drag);
super.dragEnter(drag);
}
private void updateDropDetails(VDragEvent drag) {
dropDetails = new TableDDDetails();
Element elementOver = drag.getElementOver();
VScrollTableRow row = Util.findWidget(elementOver, getRowClass());
if (row != null) {
dropDetails.overkey = row.rowKey;
Element tr = row.getElement();
Element element = elementOver;
while (element != null && element.getParentElement() != tr) {
element = (Element) element.getParentElement();
}
int childIndex = DOM.getChildIndex(tr, element);
dropDetails.colkey = tHead.getHeaderCell(childIndex)
.getColKey();
dropDetails.dropLocation = DDUtil.getVerticalDropLocation(row
.getElement(), drag.getCurrentGwtEvent().getClientY(),
0.2);
}
drag.getDropDetails().put("itemIdOver", dropDetails.overkey + "");
drag.getDropDetails().put(
"detail",
dropDetails.dropLocation != null ? dropDetails.dropLocation
.toString() : null);
}
private Class<? extends Widget> getRowClass() {
// get the row type this way to make dd work in derived
// implementations
return scrollBody.iterator().next().getClass();
}
@Override
public void dragOver(VDragEvent drag) {
TableDDDetails oldDetails = dropDetails;
updateDropDetails(drag);
if (!oldDetails.equals(dropDetails)) {
deEmphasis();
final TableDDDetails newDetails = dropDetails;
VAcceptCallback cb = new VAcceptCallback() {
public void accepted(VDragEvent event) {
if (newDetails.equals(dropDetails)) {
dragAccepted(event);
}
/*
* Else new target slot already defined, ignore
*/
}
};
validate(cb, drag);
}
}
@Override
public void dragLeave(VDragEvent drag) {
deEmphasis();
super.dragLeave(drag);
}
@Override
public boolean drop(VDragEvent drag) {
deEmphasis();
return super.drop(drag);
}
private void deEmphasis() {
UIObject.setStyleName(getElement(), CLASSNAME + "-drag", false);
if (lastEmphasized == null) {
return;
}
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (lastEmphasized != null
&& row.rowKey == lastEmphasized.overkey) {
if (row != null) {
String stylename = ROWSTYLEBASE
+ lastEmphasized.dropLocation.toString()
.toLowerCase();
VScrollTableRow.setStyleName(row.getElement(),
stylename, false);
}
lastEmphasized = null;
return;
}
}
}
/**
* TODO needs different drop modes ?? (on cells, on rows), now only
* supports rows
*/
private void emphasis(TableDDDetails details) {
deEmphasis();
UIObject.setStyleName(getElement(), CLASSNAME + "-drag", true);
// iterate old and new emphasized row
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (details != null && details.overkey == row.rowKey) {
if (row != null) {
String stylename = ROWSTYLEBASE
+ details.dropLocation.toString().toLowerCase();
VScrollTableRow.setStyleName(row.getElement(),
stylename, true);
}
lastEmphasized = details;
return;
}
}
}
@Override
protected void dragAccepted(VDragEvent drag) {
emphasis(dropDetails);
}
@Override
public Paintable getPaintable() {
return VScrollTable.this;
}
public ApplicationConnection getApplicationConnection() {
return client;
}
}
protected VScrollTableRow getFocusedRow() {
return focusedRow;
}
/**
* Moves the selection head to a specific row
*
* @param row
* The row to where the selection head should move
* @return Returns true if focus was moved successfully, else false
*/
private boolean setRowFocus(VScrollTableRow row) {
if (selectMode == SELECT_MODE_NONE) {
return false;
}
// Remove previous selection
if (focusedRow != null && focusedRow != row) {
focusedRow.removeStyleName(CLASSNAME_SELECTION_FOCUS);
}
if (row != null) {
// Apply focus style to new selection
row.addStyleName(CLASSNAME_SELECTION_FOCUS);
// Trying to set focus on already focused row
if (row == focusedRow) {
return false;
}
// Set new focused row
focusedRow = row;
ensureRowIsVisible(row);
return true;
}
return false;
}
/**
* Ensures that the row is visible
*
* @param row
* The row to ensure is visible
*/
private void ensureRowIsVisible(VScrollTableRow row) {
scrollIntoViewVertically(row.getElement());
}
/**
* Scrolls an element into view vertically only. Modified version of
* Element.scrollIntoView.
*
* @param elem
* The element to scroll into view
*/
private native void scrollIntoViewVertically(Element elem)
/*-{
var top = elem.offsetTop;
var height = elem.offsetHeight;
if (elem.parentNode != elem.offsetParent) {
top -= elem.parentNode.offsetTop;
}
var cur = elem.parentNode;
while (cur && (cur.nodeType == 1)) {
if (top < cur.scrollTop) {
cur.scrollTop = top;
}
if (top + height > cur.scrollTop + cur.clientHeight) {
cur.scrollTop = (top + height) - cur.clientHeight;
}
var offsetTop = cur.offsetTop;
if (cur.parentNode != cur.offsetParent) {
offsetTop -= cur.parentNode.offsetTop;
}
top += offsetTop - cur.scrollTop;
cur = cur.parentNode;
}
}-*/;
/**
* Handles the keyboard events handled by the table
*
* @param event
* The keyboard event received
* @return true iff the navigation event was handled
*/
protected boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
if (keycode == KeyCodes.KEY_TAB) {
// Do not handle tab key
return false;
}
// Down navigation
if (selectMode == SELECT_MODE_NONE && keycode == getNavigationDownKey()) {
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() + scrollingVelocity);
return true;
} else if (keycode == getNavigationDownKey()) {
if (selectMode == SELECT_MODE_MULTI && moveFocusDown()) {
selectFocusedRow(ctrl, shift);
} else if (selectMode == SELECT_MODE_SINGLE && !shift
&& moveFocusDown()) {
selectFocusedRow(ctrl, shift);
}
return true;
}
// Up navigation
if (selectMode == SELECT_MODE_NONE && keycode == getNavigationUpKey()) {
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() - scrollingVelocity);
return true;
} else if (keycode == getNavigationUpKey()) {
if (selectMode == SELECT_MODE_MULTI && moveFocusUp()) {
selectFocusedRow(ctrl, shift);
} else if (selectMode == SELECT_MODE_SINGLE && !shift
&& moveFocusUp()) {
selectFocusedRow(ctrl, shift);
}
return true;
}
if (keycode == getNavigationLeftKey()) {
// Left navigation
scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
.getHorizontalScrollPosition() - scrollingVelocity);
return true;
} else if (keycode == getNavigationRightKey()) {
// Right navigation
scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
.getHorizontalScrollPosition() + scrollingVelocity);
return true;
}
// Select navigation
if (isSelectable() && keycode == getNavigationSelectKey()) {
if (selectMode == SELECT_MODE_SINGLE) {
boolean wasSelected = focusedRow.isSelected();
deselectAll();
if (!wasSelected || !nullSelectionAllowed) {
focusedRow.toggleSelection();
}
} else {
focusedRow.toggleSelection();
}
sendSelectedRows();
return true;
}
// Page Down navigation
if (keycode == getNavigationPageDownKey()) {
int rowHeight = (int) scrollBody.getRowHeight();
int offset = pageLength * rowHeight - rowHeight;
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() + offset);
if (isSelectable()) {
if (!moveFocusDown(pageLength - 2)) {
final int lastRendered = scrollBody.getLastRendered();
if (lastRendered == totalRows - 1) {
selectLastRenderedRow(false);
} else {
selectLastItemInNextRender = true;
}
} else {
selectFocusedRow(false, false);
sendSelectedRows();
}
}
return true;
}
// Page Up navigation
if (keycode == getNavigationPageUpKey()) {
int rowHeight = (int) scrollBody.getRowHeight();
int offset = pageLength * rowHeight - rowHeight;
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() - offset);
if (isSelectable()) {
if (!moveFocusUp(pageLength - 2)) {
final int firstRendered = scrollBody.getFirstRendered();
if (firstRendered == 0) {
selectFirstRenderedRow(false);
} else {
selectFirstItemInNextRender = true;
}
} else {
selectFocusedRow(false, false);
sendSelectedRows();
}
}
return true;
}
// Goto start navigation
if (keycode == getNavigationStartKey()) {
if (isSelectable()) {
final int firstRendered = scrollBody.getFirstRendered();
boolean focusOnly = ctrl;
if (firstRendered == 0) {
selectFirstRenderedRow(focusOnly);
} else if (focusOnly) {
focusFirstItemInNextRender = true;
} else {
selectFirstItemInNextRender = true;
}
}
scrollBodyPanel.setScrollPosition(0);
return true;
}
// Goto end navigation
if (keycode == getNavigationEndKey()) {
if (isSelectable()) {
final int lastRendered = scrollBody.getLastRendered();
boolean focusOnly = ctrl;
if (lastRendered == totalRows - 1) {
selectLastRenderedRow(focusOnly);
} else if (focusOnly) {
focusLastItemInNextRender = true;
} else {
selectLastItemInNextRender = true;
}
}
scrollBodyPanel.setScrollPosition(scrollBody.getOffsetHeight());
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.KeyPressHandler#onKeyPress(com.google
* .gwt.event.dom.client.KeyPressEvent)
*/
public void onKeyPress(KeyPressEvent event) {
if (hasFocus) {
if (handleNavigation(event.getNativeEvent().getKeyCode(),
event.isControlKeyDown() || event.isMetaKeyDown(),
event.isShiftKeyDown())) {
event.preventDefault();
}
// Start the velocityTimer
if (scrollingVelocityTimer == null) {
scrollingVelocityTimer = new Timer() {
@Override
public void run() {
scrollingVelocity++;
}
};
scrollingVelocityTimer.scheduleRepeating(100);
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
* .event.dom.client.KeyDownEvent)
*/
public void onKeyDown(KeyDownEvent event) {
if (hasFocus) {
if (handleNavigation(event.getNativeEvent().getKeyCode(),
event.isControlKeyDown() || event.isMetaKeyDown(),
event.isShiftKeyDown())) {
event.preventDefault();
}
// Start the velocityTimer
if (scrollingVelocityTimer == null) {
scrollingVelocityTimer = new Timer() {
@Override
public void run() {
scrollingVelocity++;
}
};
scrollingVelocityTimer.scheduleRepeating(100);
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
* .dom.client.FocusEvent)
*/
public void onFocus(FocusEvent event) {
if (isFocusable()) {
scrollBodyPanel.addStyleName("focused");
hasFocus = true;
// Focus a row if no row is in focus
if (focusedRow == null) {
setRowFocus((VScrollTableRow) scrollBody.iterator().next());
} else {
setRowFocus(focusedRow);
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
* .dom.client.BlurEvent)
*/
public void onBlur(BlurEvent event) {
scrollBodyPanel.removeStyleName("focused");
hasFocus = false;
// Unfocus any row
setRowFocus(null);
}
/**
* Removes a key from a range if the key is found in a selected range
*
* @param key
* The key to remove
*/
private void removeKeyFromSelectedRange(int key) {
for (SelectionRange range : selectedRowRanges) {
if (range.inRange(key)) {
int start = range.getStartKey();
int end = range.getEndKey();
if (start < key && end > key) {
selectedRowRanges.add(new SelectionRange(start, key - 1));
selectedRowRanges.add(new SelectionRange(key + 1, end));
} else if (start == key && start < end) {
selectedRowRanges.add(new SelectionRange(start + 1, end));
} else if (end == key && start < end) {
selectedRowRanges.add(new SelectionRange(start, end - 1));
}
selectedRowRanges.remove(range);
break;
}
}
}
/**
* Can the Table be focused?
*
* @return True if the table can be focused, else false
*/
public boolean isFocusable() {
if (scrollBody != null) {
boolean hasVerticalScrollbars = scrollBody.getOffsetHeight() > scrollBodyPanel
.getOffsetHeight();
boolean hasHorizontalScrollbars = scrollBody.getOffsetWidth() > scrollBodyPanel
.getOffsetWidth();
return !(!hasHorizontalScrollbars && !hasVerticalScrollbars && selectMode == SELECT_MODE_NONE);
}
return false;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.Focusable#focus()
*/
public void focus() {
scrollBodyPanel.focus();
}
/**
* Sets the proper tabIndex for scrollBodyPanel (the focusable elemen in the
* component).
*
* If the component has no explicit tabIndex a zero is given (default
* tabbing order based on dom hierarchy) or -1 if the component does not
* need to gain focus. The component needs no focus if it has no scrollabars
* (not scrollable) and not selectable. Note that in the future shortcut
* actions may need focus.
*
*/
private void setProperTabIndex() {
if (!isFocusable()) {
scrollBodyPanel.getElement().setTabIndex(-1);
} else {
// TODO tabindex from UIDL
scrollBodyPanel.getElement().setTabIndex(0);
}
}
}
|
fixes #5478
svn changeset:14597/svn branch:6.4
|
src/com/vaadin/terminal/gwt/client/ui/VScrollTable.java
|
fixes #5478
|
|
Java
|
apache-2.0
|
e539fad81290bd7c84206b9f4a459f2ee3e9a7a2
| 0
|
haroldcarr/rdf-triple-browser,haroldcarr/rdf-triple-browser
|
//
// Created : 2006 Jun 14 (Wed) 18:29:38 by Harold Carr.
// Last Modified : 2006 Jun 24 (Sat) 09:58:09 by Harold Carr.
//
/*
TODO:
- Query with fake server-side.
- Server-side
- Figure out how to make sov panels expand.
- Style
*/
package com.differentity.client;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.HistoryListener;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.VerticalPanel;
public class Main
implements
EntryPoint // Entry point classes define onModuleLoad()
{
public static String collapse = "collapse";
public static String collapseAllTags = "collapse all tags";
public static String copyright = "copyright 2006";
public static String differentityDotCom = "differentity.com";
public static String expand = "expand";
public static String expandAllTags = "expand all tags";
public static String minusSymbol = "-";
public static String object = "object";
public static String plusSymbol = "+";
public static String subject = "subject";
public static String subjectVerbObject = "subjectVerbObject";
public static String verb = "verb";
public static final Label lbl = new Label("XXX"); // XXX
// TODO: these should be final.
public static Server server;
public static MainPanel mainPanel;
/**
* This is the entry point method.
*/
public void onModuleLoad()
{
server = new Server();
mainPanel = new MainPanel();
}
public static String getExpandCollapseState(
final String expandCollapseState,
final boolean pending)
{
if (expandCollapseState.equals(Main.expand)) {
return (pending ? Main.collapse : Main.expand);
} else {
return (pending ? Main.expand : Main.collapse);
}
}
}
class MainPanel
{
final VerticalPanel subjectVerticalPanel;
final VerticalPanel verbVerticalPanel;
final VerticalPanel objectVerticalPanel;
final HorizontalPanel horizontalPanel;
final DockPanel dockPanel;
final HTML north;
final HTML south;
MainPanel() {
//
// Subject, Verb, Object panels.
//
subjectVerticalPanel = new SVOPanel(Main.subject).getPanel();
verbVerticalPanel = new SVOPanel(Main.verb).getPanel();
objectVerticalPanel = new SVOPanel(Main.object).getPanel();
horizontalPanel = new HorizontalPanel();
horizontalPanel.setVerticalAlignment(VerticalPanel.ALIGN_MIDDLE);
horizontalPanel.add(subjectVerticalPanel);
horizontalPanel.add(verbVerticalPanel);
horizontalPanel.add(objectVerticalPanel);
//
// Main panel.
//
dockPanel = new DockPanel();
dockPanel.setHorizontalAlignment(DockPanel.ALIGN_CENTER);
north = new HTML(Main.differentityDotCom, true);
south = new HTML(Main.copyright, true);
dockPanel.add(north, DockPanel.NORTH);
// NOTE: - if SOUTH added after CENTER does not show up.
dockPanel.add(south, DockPanel.SOUTH);
dockPanel.add(horizontalPanel, DockPanel.CENTER);
// Host HTML has elements with IDs are "slot1", "slot2".
// Better: Search for all elements with a particular CSS class
// and replace them with widgets.
RootPanel.get("slot2").add(dockPanel);
// XXX - Hyperlink test
RootPanel.get("slot1").add(Main.lbl);
// XXX - frame test
RootPanel.get("slot3").add(new Frame("http://www.google.com/"));
}
}
class SVOItem
{
final String svoCategory;
final String expandedName;
final String collapsedName;
String expandCollapseState;
final Button button;
final Hyperlink hyperlink;
final HorizontalPanel horizontalPanel;
final VerticalPanel verticalPanel;
SVOItem(String svoCategory, String expandedName, String collapsedName,
String expandCollapseState)
{
this.svoCategory = svoCategory;
this.expandedName = expandedName;
this.collapsedName = collapsedName;
this.expandCollapseState = expandCollapseState;
button = new Button(Main.plusSymbol);
hyperlink = new Hyperlink(expandedName,
svoCategory + " " + expandedName);
horizontalPanel = new HorizontalPanel();
verticalPanel = new VerticalPanel();
// Item layout.
horizontalPanel.add(button);
horizontalPanel.add(hyperlink);
verticalPanel.add(horizontalPanel);
if (expandCollapseState.equals(Main.collapse)){
hyperlink.setText(collapsedName);
} else {
button.setText(Main.minusSymbol);
verticalPanel.add(new Frame(expandedName));
}
}
String getSVOCategory() { return svoCategory; }
String getExpandedName() { return expandedName; }
String getCollapsedName() { return collapsedName; }
String getCurrentExpandCollapseState() {
return Main.getExpandCollapseState(expandCollapseState, false);
}
String getPendingExpandCollapseState() {
return Main.getExpandCollapseState(expandCollapseState, true);
}
void setExpandCollapseState(String x) { expandCollapseState = x; }
Button getButton() { return button; }
Hyperlink getHyperlink() { return hyperlink; }
HorizontalPanel getHorizontalPanel() { return horizontalPanel; }
VerticalPanel getVerticalPanel() { return verticalPanel; }
}
class SVOPanel
{
String expandCollapseState;
final String svoCategory; // For debug only.
final List contents; // The "raw" contents.
final VerticalPanel verticalInsideScroll;
final VerticalPanel topVerticalPanel;
final Button topButton;
final ScrollPanel scrollPanel;
SVOPanel(final String svoCategory)
{
this.expandCollapseState = Main.collapse;
this.svoCategory = svoCategory;
contents = Main.server.getInitialContents(svoCategory);
// Begin layout.
topVerticalPanel = new VerticalPanel();
topVerticalPanel.setHorizontalAlignment(VerticalPanel.ALIGN_LEFT);
topButton = new Button(getPendingExpandCollapseState());
topVerticalPanel.add(topButton);
// TODO: Would like a scroll or a cloud
verticalInsideScroll = new VerticalPanel();
scrollPanel = new ScrollPanel(verticalInsideScroll);
scrollPanel.setStyleName(Main.subjectVerbObject);
topVerticalPanel.add(scrollPanel);
initialContents();
// End layout.
topButton.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
final String newState = expandOrCollapse();
topButton.setText(newState);
}
});
}
VerticalPanel getPanel() { return topVerticalPanel; }
String getCurrentExpandCollapseState()
{
return Main.getExpandCollapseState(expandCollapseState, false);
}
String getPendingExpandCollapseState()
{
return Main.getExpandCollapseState(expandCollapseState, true);
}
private void initialContents()
{
verticalInsideScroll.clear();
final Iterator i = contents.iterator();
while (i.hasNext()) {
final SVOItem svoItem = (SVOItem) i.next();
verticalInsideScroll.add(svoItem.getVerticalPanel());
if (expandCollapseState.equals(Main.expand)) {
svoItem.getHyperlink().setText(svoItem.getExpandedName());
}
svoItem.getHyperlink().addClickListener(new ClickListener() {
public void onClick(final Widget sender) {
// TODO: Send to server. Receive updates for other panels.
Main.lbl.setText(((Hyperlink)sender).getTargetHistoryToken());
}
});
svoItem.getButton().addClickListener(new ClickListener() {
public void onClick(Widget sender) {
// TODO: Triple expand/collapse:
// + = expand to full URL and N "characters" of source.
// * = expand to full URL and all source.
// - = collapse to short URL and no source.
if (svoItem.getPendingExpandCollapseState().equals(Main.expand)) {
svoItem.getHyperlink().setText(svoItem.getExpandedName());
svoItem.getVerticalPanel().add(new Frame(svoItem.getExpandedName()));
svoItem.setExpandCollapseState(Main.expand);
svoItem.getButton().setText(Main.minusSymbol);
} else {
Widget w = svoItem.getVerticalPanel().getWidget(1);
svoItem.getVerticalPanel().remove(w);
svoItem.getHyperlink().setText(svoItem.getCollapsedName());
svoItem.setExpandCollapseState(Main.collapse);
svoItem.getButton().setText(Main.plusSymbol);
}
}});
}
}
String expandOrCollapse()
{
String pendingExpandCollapseState = getPendingExpandCollapseState();
final Iterator i = verticalInsideScroll.iterator();
final Iterator j = contents.iterator();
while (i.hasNext()) {
final VerticalPanel verticalPanel = (VerticalPanel) i.next();
final SVOItem svoItem = (SVOItem) j.next();
if (svoItem.getCurrentExpandCollapseState().equals(Main.collapse)){
if (pendingExpandCollapseState.equals(Main.expand)) {
svoItem.getHyperlink().setText(svoItem.getExpandedName());
} else {
svoItem.getHyperlink().setText(svoItem.getCollapsedName());
}
}
}
expandCollapseState = pendingExpandCollapseState;
return getPendingExpandCollapseState();
}
}
class Server
{
// TODO: Really interact with service.
public List getInitialContents(String svoCategory)
{
final Iterator i = svoList.iterator();
final List result = new ArrayList();
while (i.hasNext()) {
String uri = (String) i.next();
result.add(new SVOItem(svoCategory,
uri,
substringAfterLastSlash(uri),
// NOTE: during development change to
// Main.expand to test full range.
Main.collapse));
}
return result;
}
private String substringAfterLastSlash(final String x)
{
int indexOfLastSlash = 0;
int i;
for (i = 0; i < x.length(); ++i) {
if (x.charAt(i) == '/') {
indexOfLastSlash = i;
}
}
final String result = x.substring(indexOfLastSlash + 1);
// If it ends in a slash then remove the ending slash and try again.
if (result.length() == 0) {
return substringAfterLastSlash(x.substring(0, x.length()-1));
} else {
return result;
}
}
// TODO: replace with real list from server.
private List svoList = new ArrayList();
{ // NOTE: block needed for this to compile.
svoList.add("http://haroldcarr.com");
svoList.add("http://www.rojo.com/");
svoList.add("http://google.com");
svoList.add("http://del.icio.us/");
svoList.add("http://differentity.com/haroldcarr/author");
svoList.add("http://differentity.com/haroldcarr/authorPrefix");
svoList.add("http://differentity.com/haroldcarr/authorFirstName");
svoList.add("http://differentity.com/haroldcarr/authorMiddleName");
svoList.add("http://differentity.com/haroldcarr/authorLastName");
svoList.add("http://differentity.com/haroldcarr/authorSuffix");
svoList.add("http://differentity.com/haroldcarr/authorBorn");
svoList.add("http://differentity.com/haroldcarr/authorDied");
svoList.add("http://differentity.com/haroldcarr/authorIdea");
svoList.add("http://differentity.com/haroldcarr/author");
svoList.add("http://differentity.com/haroldcarr/ideaInCategory");
svoList.add("http://differentity.com/haroldcarr/work");
svoList.add("http://differentity.com/haroldcarr/workAuthor");
svoList.add("http://differentity.com/haroldcarr/workTitle");
svoList.add("http://differentity.com/haroldcarr/workPublished");
svoList.add("http://differentity.com/haroldcarr/workWritten");
svoList.add("http://differentity.com/haroldcarr/bataille");
svoList.add("http://differentity.com/haroldcarr/book");
svoList.add("http://differentity.com/haroldcarr/guilty");
svoList.add("http://differentity.com/haroldcarr/eroticism");
svoList.add("http://differentity.com/haroldcarr/blue_of_noon");
svoList.add("http://differentity.com/haroldcarr/inner_experience");
svoList.add("http://differentity.com/haroldcarr/similarTo");
svoList.add("http://differentity.com/haroldcarr/equalTo");
svoList.add("http://differentity.com/haroldcarr/contraryTo");
svoList.add("http://differentity.com/haroldcarr/contrarstWith");
svoList.add("http://differentity.com/haroldcarr/relatesTo");
svoList.add("http://differentity.com/haroldcarr/fate");
svoList.add("http://differentity.com/haroldcarr/formlessness");
svoList.add("http://differentity.com/haroldcarr/god");
svoList.add("http://differentity.com/haroldcarr/stability");
svoList.add("http://differentity.com/haroldcarr/reason");
svoList.add("http://differentity.com/haroldcarr/nothingness");
svoList.add("http://differentity.com/haroldcarr/chance");
svoList.add("http://differentity.com/haroldcarr/strength");
svoList.add("http://differentity.com/haroldcarr/death");
svoList.add("http://differentity.com/haroldcarr/anguish");
svoList.add("http://differentity.com/haroldcarr/silence");
svoList.add("http://differentity.com/haroldcarr/limit");
}
}
// End of file.
|
gwt/src/main/java/org/openhc/triplebrowser/gwt/client/Main.java
|
//
// Created : 2006 Jun 14 (Wed) 18:29:38 by Harold Carr.
// Last Modified : 2006 Jun 24 (Sat) 09:37:17 by Harold Carr.
//
/*
TODO:
- Server-side
- Figure out how to make sov panels expand.
- Style
*/
package com.differentity.client;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.HistoryListener;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.VerticalPanel;
public class Main
implements
EntryPoint // Entry point classes define onModuleLoad()
{
public static String collapse = "collapse";
public static String collapseAllTags = "collapse all tags";
public static String copyright = "copyright 2006";
public static String differentityDotCom = "differentity.com";
public static String expand = "expand";
public static String expandAllTags = "expand all tags";
public static String minusSymbol = "-";
public static String object = "object";
public static String plusSymbol = "+";
public static String subject = "subject";
public static String subjectVerbObject = "subjectVerbObject";
public static String verb = "verb";
public static final Label lbl = new Label("XXX"); // XXX
/**
* This is the entry point method.
*/
public void onModuleLoad()
{
MainPanel mainPanel = new MainPanel();
}
public static String getExpandCollapseState(
final String expandCollapseState,
final boolean pending)
{
if (expandCollapseState.equals(Main.expand)) {
return (pending ? Main.collapse : Main.expand);
} else {
return (pending ? Main.expand : Main.collapse);
}
}
}
class MainPanel
{
final VerticalPanel subjectVerticalPanel;
final VerticalPanel verbVerticalPanel;
final VerticalPanel objectVerticalPanel;
final HorizontalPanel horizontalPanel;
final DockPanel dockPanel;
final HTML north;
final HTML south;
MainPanel() {
//
// Subject, Verb, Object panels.
//
subjectVerticalPanel = new SVOPanel(Main.subject).getPanel();
verbVerticalPanel = new SVOPanel(Main.verb).getPanel();
objectVerticalPanel = new SVOPanel(Main.object).getPanel();
horizontalPanel = new HorizontalPanel();
horizontalPanel.setVerticalAlignment(VerticalPanel.ALIGN_MIDDLE);
horizontalPanel.add(subjectVerticalPanel);
horizontalPanel.add(verbVerticalPanel);
horizontalPanel.add(objectVerticalPanel);
//
// Main panel.
//
dockPanel = new DockPanel();
dockPanel.setHorizontalAlignment(DockPanel.ALIGN_CENTER);
north = new HTML(Main.differentityDotCom, true);
south = new HTML(Main.copyright, true);
dockPanel.add(north, DockPanel.NORTH);
// NOTE: - if SOUTH added after CENTER does not show up.
dockPanel.add(south, DockPanel.SOUTH);
dockPanel.add(horizontalPanel, DockPanel.CENTER);
// Host HTML has elements with IDs are "slot1", "slot2".
// Better: Search for all elements with a particular CSS class
// and replace them with widgets.
RootPanel.get("slot2").add(dockPanel);
// XXX - Hyperlink test
RootPanel.get("slot1").add(Main.lbl);
// XXX - frame test
RootPanel.get("slot3").add(new Frame("http://www.google.com/"));
}
}
class SVOItem
{
final String svoCategory;
final String expandedName;
final String collapsedName;
String expandCollapseState;
final Button button;
final Hyperlink hyperlink;
final HorizontalPanel horizontalPanel;
final VerticalPanel verticalPanel;
SVOItem(String svoCategory, String expandedName, String collapsedName,
String expandCollapseState)
{
this.svoCategory = svoCategory;
this.expandedName = expandedName;
this.collapsedName = collapsedName;
this.expandCollapseState = expandCollapseState;
button = new Button(Main.plusSymbol);
hyperlink = new Hyperlink(expandedName,
svoCategory + " " + expandedName);
horizontalPanel = new HorizontalPanel();
verticalPanel = new VerticalPanel();
// Item layout.
horizontalPanel.add(button);
horizontalPanel.add(hyperlink);
verticalPanel.add(horizontalPanel);
if (expandCollapseState.equals(Main.collapse)){
hyperlink.setText(collapsedName);
} else {
button.setText(Main.minusSymbol);
verticalPanel.add(new Frame(expandedName));
}
}
String getSVOCategory() { return svoCategory; }
String getExpandedName() { return expandedName; }
String getCollapsedName() { return collapsedName; }
String getCurrentExpandCollapseState() {
return Main.getExpandCollapseState(expandCollapseState, false);
}
String getPendingExpandCollapseState() {
return Main.getExpandCollapseState(expandCollapseState, true);
}
void setExpandCollapseState(String x) { expandCollapseState = x; }
Button getButton() { return button; }
Hyperlink getHyperlink() { return hyperlink; }
HorizontalPanel getHorizontalPanel() { return horizontalPanel; }
VerticalPanel getVerticalPanel() { return verticalPanel; }
}
class SVOPanel
{
String expandCollapseState;
final String svoCategory; // For debug only.
final List contents; // The "raw" contents.
final VerticalPanel verticalInsideScroll;
final VerticalPanel topVerticalPanel;
final Button topButton;
final ScrollPanel scrollPanel;
SVOPanel(final String svoCategory)
{
this.expandCollapseState = Main.collapse;
this.svoCategory = svoCategory;
// TODO: Get from service.
// NOTE: during development change to Main.expand to test full range.
contents = fakeServerInitialization(svoCategory, Main.collapse);
// Begin layout.
topVerticalPanel = new VerticalPanel();
topVerticalPanel.setHorizontalAlignment(VerticalPanel.ALIGN_LEFT);
topButton = new Button(getPendingExpandCollapseState());
topVerticalPanel.add(topButton);
// TODO: Would like a scroll or a cloud
verticalInsideScroll = new VerticalPanel();
scrollPanel = new ScrollPanel(verticalInsideScroll);
scrollPanel.setStyleName(Main.subjectVerbObject);
topVerticalPanel.add(scrollPanel);
initialContents();
// End layout.
topButton.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
final String newState = expandOrCollapse();
topButton.setText(newState);
}
});
}
VerticalPanel getPanel() { return topVerticalPanel; }
String getCurrentExpandCollapseState()
{
return Main.getExpandCollapseState(expandCollapseState, false);
}
String getPendingExpandCollapseState()
{
return Main.getExpandCollapseState(expandCollapseState, true);
}
private void initialContents()
{
verticalInsideScroll.clear();
final Iterator i = contents.iterator();
while (i.hasNext()) {
final SVOItem svoItem = (SVOItem) i.next();
verticalInsideScroll.add(svoItem.getVerticalPanel());
if (expandCollapseState.equals(Main.expand)) {
svoItem.getHyperlink().setText(svoItem.getExpandedName());
}
svoItem.getHyperlink().addClickListener(new ClickListener() {
public void onClick(final Widget sender) {
// TODO: Send to server. Receive updates for other panels.
Main.lbl.setText(((Hyperlink)sender).getTargetHistoryToken());
}
});
svoItem.getButton().addClickListener(new ClickListener() {
public void onClick(Widget sender) {
// TODO: Triple expand/collapse:
// + = expand to full URL and N "characters" of source.
// * = expand to full URL and all source.
// - = collapse to short URL and no source.
if (svoItem.getPendingExpandCollapseState().equals(Main.expand)) {
svoItem.getHyperlink().setText(svoItem.getExpandedName());
svoItem.getVerticalPanel().add(new Frame(svoItem.getExpandedName()));
svoItem.setExpandCollapseState(Main.expand);
svoItem.getButton().setText(Main.minusSymbol);
} else {
Widget w = svoItem.getVerticalPanel().getWidget(1);
svoItem.getVerticalPanel().remove(w);
svoItem.getHyperlink().setText(svoItem.getCollapsedName());
svoItem.setExpandCollapseState(Main.collapse);
svoItem.getButton().setText(Main.plusSymbol);
}
}});
}
}
String expandOrCollapse()
{
String pendingExpandCollapseState = getPendingExpandCollapseState();
final Iterator i = verticalInsideScroll.iterator();
final Iterator j = contents.iterator();
while (i.hasNext()) {
final VerticalPanel verticalPanel = (VerticalPanel) i.next();
final SVOItem svoItem = (SVOItem) j.next();
if (svoItem.getCurrentExpandCollapseState().equals(Main.collapse)){
if (pendingExpandCollapseState.equals(Main.expand)) {
svoItem.getHyperlink().setText(svoItem.getExpandedName());
} else {
svoItem.getHyperlink().setText(svoItem.getCollapsedName());
}
}
}
expandCollapseState = pendingExpandCollapseState;
return getPendingExpandCollapseState();
}
private String substringAfterLastSlash(final String x)
{
int indexOfLastSlash = 0;
int i;
for (i = 0; i < x.length(); ++i) {
if (x.charAt(i) == '/') {
indexOfLastSlash = i;
}
}
final String result = x.substring(indexOfLastSlash + 1);
// If it ends in a slash then remove the ending slash and try again.
if (result.length() == 0) {
return substringAfterLastSlash(x.substring(0, x.length()-1));
} else {
return result;
}
}
private List fakeServerInitialization(String svoCategory,
String expandOrCollapse)
{
final Iterator i = svoList.iterator();
final List result = new ArrayList();
while (i.hasNext()) {
String uri = (String) i.next();
result.add(new SVOItem(svoCategory,
uri,
substringAfterLastSlash(uri),
expandOrCollapse));
}
return result;
}
// TODO: replace with real list from server.
private List svoList = new ArrayList();
{ // NOTE: block needed for this to compile.
svoList.add("http://haroldcarr.com");
svoList.add("http://www.rojo.com/");
svoList.add("http://google.com");
svoList.add("http://del.icio.us/");
svoList.add("http://differentity.com/haroldcarr/author");
svoList.add("http://differentity.com/haroldcarr/authorPrefix");
svoList.add("http://differentity.com/haroldcarr/authorFirstName");
svoList.add("http://differentity.com/haroldcarr/authorMiddleName");
svoList.add("http://differentity.com/haroldcarr/authorLastName");
svoList.add("http://differentity.com/haroldcarr/authorSuffix");
svoList.add("http://differentity.com/haroldcarr/authorBorn");
svoList.add("http://differentity.com/haroldcarr/authorDied");
svoList.add("http://differentity.com/haroldcarr/authorIdea");
svoList.add("http://differentity.com/haroldcarr/author");
svoList.add("http://differentity.com/haroldcarr/ideaInCategory");
svoList.add("http://differentity.com/haroldcarr/work");
svoList.add("http://differentity.com/haroldcarr/workAuthor");
svoList.add("http://differentity.com/haroldcarr/workTitle");
svoList.add("http://differentity.com/haroldcarr/workPublished");
svoList.add("http://differentity.com/haroldcarr/workWritten");
svoList.add("http://differentity.com/haroldcarr/bataille");
svoList.add("http://differentity.com/haroldcarr/book");
svoList.add("http://differentity.com/haroldcarr/guilty");
svoList.add("http://differentity.com/haroldcarr/eroticism");
svoList.add("http://differentity.com/haroldcarr/blue_of_noon");
svoList.add("http://differentity.com/haroldcarr/inner_experience");
svoList.add("http://differentity.com/haroldcarr/similarTo");
svoList.add("http://differentity.com/haroldcarr/equalTo");
svoList.add("http://differentity.com/haroldcarr/contraryTo");
svoList.add("http://differentity.com/haroldcarr/contrarstWith");
svoList.add("http://differentity.com/haroldcarr/relatesTo");
svoList.add("http://differentity.com/haroldcarr/fate");
svoList.add("http://differentity.com/haroldcarr/formlessness");
svoList.add("http://differentity.com/haroldcarr/god");
svoList.add("http://differentity.com/haroldcarr/stability");
svoList.add("http://differentity.com/haroldcarr/reason");
svoList.add("http://differentity.com/haroldcarr/nothingness");
svoList.add("http://differentity.com/haroldcarr/chance");
svoList.add("http://differentity.com/haroldcarr/strength");
svoList.add("http://differentity.com/haroldcarr/death");
svoList.add("http://differentity.com/haroldcarr/anguish");
svoList.add("http://differentity.com/haroldcarr/silence");
svoList.add("http://differentity.com/haroldcarr/limit");
}
}
// End of file.
|
["working checkpoint.\n", ""]
|
gwt/src/main/java/org/openhc/triplebrowser/gwt/client/Main.java
|
["working checkpoint.\n", ""]
|
|
Java
|
apache-2.0
|
07e9f253325dfeb9c53aadce716bd99316cdf3e5
| 0
|
spotify/netty-zmtp,tempbottle/netty-zmtp
|
package com.spotify.netty4.handler.codec.zmtp;
import java.util.List;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.CombinedChannelDuplexHandler;
import io.netty.handler.codec.ReplayingDecoder;
/**
* An abstract base class for common functionality to the ZMTP codecs.
*/
abstract class CodecBase extends ReplayingDecoder<Void> {
protected final ZMTPSession session;
protected HandshakeListener listener;
private final ZMTPMessageEncoder encoder;
private final ZMTPMessageDecoder decoder;
CodecBase(final ZMTPSession session,
final ZMTPMessageEncoder encoder,
final ZMTPMessageDecoder decoder) {
this.session = session;
this.encoder = encoder;
this.decoder = decoder;
}
public CodecBase(final ZMTPSession session) {
this(session,
new DefaultZMTPMessageEncoder(session.isEnveloped()),
new ZMTPIncomingMessageDecoder(session.isEnveloped(), session.sizeLimit())
);
}
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
setListener(new HandshakeListener() {
@Override
public void handshakeDone(int protocolVersion, byte[] remoteIdentity) {
session.remoteIdentity(remoteIdentity);
session.actualVersion(protocolVersion);
updatePipeline(ctx.pipeline(), session);
ctx.fireChannelActive();
}
});
ctx.writeAndFlush(onConnect());
}
abstract ByteBuf onConnect();
abstract boolean inputOutput(final ByteBuf buffer, final ChannelHandlerContext ctx)
throws ZMTPException;
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
throws Exception {
in.markReaderIndex();
boolean done = inputOutput(in, ctx);
if (!done) {
return;
}
// This follows the pattern for dynamic pipelines documented in
// http://netty.io/4.0/api/io/netty/handler/codec/ReplayingDecoder.html
if (actualReadableBytes() > 0) {
out.add(in.readBytes(actualReadableBytes()));
}
}
void setListener(HandshakeListener listener) {
this.listener = listener;
}
private void updatePipeline(ChannelPipeline pipeline,
ZMTPSession session) {
final ZMTPMessageParser parser = ZMTPMessageParser.create(
session.actualVersion(), decoder);
pipeline.replace(
this, "zmtp-codec",
new CombinedChannelDuplexHandler<ZMTPFramingDecoder, ZMTPFramingEncoder>(
new ZMTPFramingDecoder(parser),
new ZMTPFramingEncoder(session, encoder)));
}
/**
* Parse and return the remote identity octets from a ZMTP/1.0 greeting.
*/
static byte[] readZMTP1RemoteIdentity(final ByteBuf buffer) throws ZMTPException {
final long len = ZMTPUtils.decodeZMTP1Length(buffer);
if (len > 256) {
// spec says the ident string can be up to 255 chars
throw new ZMTPException("Remote identity longer than the allowed 255 octets");
}
// skip the flags byte
buffer.skipBytes(1);
if (len == 1) {
return null;
}
final byte[] identity = new byte[(int) len - 1];
buffer.readBytes(identity);
return identity;
}
}
|
src/main/java/com/spotify/netty4/handler/codec/zmtp/CodecBase.java
|
package com.spotify.netty4.handler.codec.zmtp;
import java.util.List;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.CombinedChannelDuplexHandler;
import io.netty.handler.codec.ReplayingDecoder;
/**
* An abstract base class for common functionality to the ZMTP codecs.
*/
abstract class CodecBase extends ReplayingDecoder<Void> {
protected final ZMTPSession session;
protected HandshakeListener listener;
private final ZMTPMessageEncoder encoder;
private final ZMTPMessageDecoder decoder;
CodecBase(final ZMTPSession session,
final ZMTPMessageEncoder encoder,
final ZMTPMessageDecoder decoder) {
this.session = session;
this.encoder = encoder;
this.decoder = decoder;
}
public CodecBase(final ZMTPSession session) {
this(session,
new DefaultZMTPMessageEncoder(session.isEnveloped()),
new ZMTPIncomingMessageDecoder(session.isEnveloped(), session.sizeLimit())
);
}
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
setListener(new HandshakeListener() {
@Override
public void handshakeDone(int protocolVersion, byte[] remoteIdentity) {
session.remoteIdentity(remoteIdentity);
session.actualVersion(protocolVersion);
updatePipeline(ctx.pipeline(), session);
ctx.fireChannelActive();
}
});
ctx.writeAndFlush(onConnect());
}
abstract ByteBuf onConnect();
abstract boolean inputOutput(final ByteBuf buffer, final ChannelHandlerContext ctx)
throws ZMTPException;
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
throws Exception {
in.markReaderIndex();
boolean done = inputOutput(in, ctx);
if (!done) {
return;
}
// This follows the pattern for dynamic pipelines documented in
// http://netty.io/4.0/api/io/netty/handler/codec/ReplayingDecoder.html
if (actualReadableBytes() > 0) {
out.add(in.readBytes(actualReadableBytes()));
}
}
void setListener(HandshakeListener listener) {
this.listener = listener;
}
private void updatePipeline(ChannelPipeline pipeline,
ZMTPSession session) {
final ZMTPMessageParser parser = ZMTPMessageParser.create(
session.actualVersion(), decoder);
pipeline.replace(
this, "zmtp-codec",
new CombinedChannelDuplexHandler<ZMTPFramingDecoder, ZMTPFramingEncoder>(
new ZMTPFramingDecoder(parser),
new ZMTPFramingEncoder(session, encoder)));
}
/**
* Parse and return the remote identity octets from a ZMTP/1.0 greeting.
*/
static byte[] readZMTP1RemoteIdentity(final ByteBuf buffer) throws ZMTPException {
buffer.markReaderIndex();
final long len = ZMTPUtils.decodeZMTP1Length(buffer);
if (len > 256) {
// spec says the ident string can be up to 255 chars
throw new ZMTPException("Remote identity longer than the allowed 255 octets");
}
// skip the flags byte
buffer.skipBytes(1);
if (len == 1) {
return null;
}
final byte[] identity = new byte[(int) len - 1];
buffer.readBytes(identity);
return identity;
}
}
|
remove unused index mark
|
src/main/java/com/spotify/netty4/handler/codec/zmtp/CodecBase.java
|
remove unused index mark
|
|
Java
|
apache-2.0
|
3014663fd7c5ae72f031c36764b5b549193d7300
| 0
|
billy1380/blogwt,billy1380/blogwt,billy1380/blogwt
|
//
// PageApi.java
// blogwt
//
// Created by William Shakour on June 21, 2015.
// Copyright © 2015 WillShex Limited. All rights reserved.
//
package com.willshex.blogwt.server.api.page;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import com.willshex.blogwt.server.api.validation.ApiValidator;
import com.willshex.blogwt.server.api.validation.FormValidator;
import com.willshex.blogwt.server.api.validation.PageValidator;
import com.willshex.blogwt.server.api.validation.SessionValidator;
import com.willshex.blogwt.server.api.validation.UserValidator;
import com.willshex.blogwt.server.helper.EmailHelper;
import com.willshex.blogwt.server.helper.RecaptchaHelper;
import com.willshex.blogwt.server.service.PersistenceService;
import com.willshex.blogwt.server.service.page.PageServiceProvider;
import com.willshex.blogwt.server.service.permission.PermissionServiceProvider;
import com.willshex.blogwt.server.service.property.PropertyServiceProvider;
import com.willshex.blogwt.server.service.user.UserServiceProvider;
import com.willshex.blogwt.shared.api.datatype.Field;
import com.willshex.blogwt.shared.api.datatype.FieldTypeType;
import com.willshex.blogwt.shared.api.datatype.Page;
import com.willshex.blogwt.shared.api.datatype.PageSortType;
import com.willshex.blogwt.shared.api.datatype.Permission;
import com.willshex.blogwt.shared.api.datatype.Property;
import com.willshex.blogwt.shared.api.page.call.CreatePageRequest;
import com.willshex.blogwt.shared.api.page.call.CreatePageResponse;
import com.willshex.blogwt.shared.api.page.call.DeletePageRequest;
import com.willshex.blogwt.shared.api.page.call.DeletePageResponse;
import com.willshex.blogwt.shared.api.page.call.GetPageRequest;
import com.willshex.blogwt.shared.api.page.call.GetPageResponse;
import com.willshex.blogwt.shared.api.page.call.GetPagesRequest;
import com.willshex.blogwt.shared.api.page.call.GetPagesResponse;
import com.willshex.blogwt.shared.api.page.call.SubmitFormRequest;
import com.willshex.blogwt.shared.api.page.call.SubmitFormResponse;
import com.willshex.blogwt.shared.api.page.call.UpdatePageRequest;
import com.willshex.blogwt.shared.api.page.call.UpdatePageResponse;
import com.willshex.blogwt.shared.api.validation.ApiError;
import com.willshex.blogwt.shared.helper.PagerHelper;
import com.willshex.blogwt.shared.helper.PermissionHelper;
import com.willshex.blogwt.shared.helper.PostHelper;
import com.willshex.blogwt.shared.helper.PropertyHelper;
import com.willshex.blogwt.shared.helper.UserHelper;
import com.willshex.gson.json.service.server.ActionHandler;
import com.willshex.gson.json.service.server.InputValidationException;
import com.willshex.gson.json.service.server.ServiceException;
import com.willshex.gson.json.service.shared.StatusType;
public final class PageApi extends ActionHandler {
private static final Logger LOG = Logger.getLogger(Page.class.getName());
public SubmitFormResponse submitForm (SubmitFormRequest input) {
LOG.finer("Entering submitForm");
SubmitFormResponse output = new SubmitFormResponse();
try {
// send an email with the submitted fields
ApiValidator.notNull(input, UpdatePageRequest.class, "input");
ApiValidator.accessCode(input.accessCode, "input.accessCode");
if (input.session != null) {
output.session = input.session = SessionValidator
.lookupAndExtend(input.session, "input.session");
}
input.form = FormValidator.validate(input.form, "input.form");
Property email = PropertyServiceProvider.provide()
.getNamedProperty(PropertyHelper.OUTGOING_EMAIL);
Property title = PropertyServiceProvider.provide()
.getNamedProperty(PropertyHelper.TITLE);
StringBuffer body = new StringBuffer();
boolean isHuman = false;
Field captchaField = null;
for (Field field : input.form.fields) {
if (field.type == FieldTypeType.FieldTypeTypeCaptcha) {
captchaField = field;
} else {
body.append(field.name);
body.append(":");
body.append(field.value);
body.append("\n\n");
}
}
if (captchaField != null) {
Property reCaptchaKey = PropertyServiceProvider.provide()
.getNamedProperty(PropertyHelper.RECAPTCHA_API_KEY);
isHuman = RecaptchaHelper.isHuman(captchaField.value, reCaptchaKey.value);
}
if (captchaField == null || isHuman) {
if (!EmailHelper.sendEmail(email.value, title.value,
"Submit form", body.toString(), false))
ApiValidator.throwServiceError(ServiceException.class,
ApiError.FailedToSendEmail, "input.form");
}
UserHelper.stripPassword(output.session == null ? null
: output.session.user);
output.status = StatusType.StatusTypeSuccess;
} catch (Exception e) {
output.status = StatusType.StatusTypeFailure;
output.error = convertToErrorAndLog(LOG, e);
}
LOG.finer("Exiting submitForm");
return output;
}
public UpdatePageResponse updatePage (UpdatePageRequest input) {
LOG.finer("Entering updatePage");
UpdatePageResponse output = new UpdatePageResponse();
try {
ApiValidator.notNull(input, UpdatePageRequest.class, "input");
ApiValidator.accessCode(input.accessCode, "input.accessCode");
output.session = input.session = SessionValidator.lookupAndExtend(
input.session, "input.session");
List<Permission> permissions = new ArrayList<Permission>();
Permission postPermission = PermissionServiceProvider.provide()
.getCodePermission(PermissionHelper.MANAGE_PAGES);
permissions.add(postPermission);
input.session.user = UserServiceProvider.provide().getUser(
Long.valueOf(input.session.userKey.getId()));
UserValidator.authorisation(input.session.user, permissions,
"input.session.user");
Page updatedPage = input.page;
input.page = PageValidator.lookup(input.page, "input.page");
updatedPage = PageValidator.validate(updatedPage, "input.page");
input.page.hasChildren = updatedPage.hasChildren;
input.page.parent = updatedPage.parent;
input.page.posts = updatedPage.posts;
input.page.priority = updatedPage.priority;
input.page.title = updatedPage.title;
input.page.slug = PostHelper.slugify(input.page.title);
PageServiceProvider.provide().updatePage(input.page);
UserHelper.stripPassword(output.session == null ? null
: output.session.user);
output.status = StatusType.StatusTypeSuccess;
} catch (Exception e) {
output.status = StatusType.StatusTypeFailure;
output.error = convertToErrorAndLog(LOG, e);
}
LOG.finer("Exiting updatePage");
return output;
}
public DeletePageResponse deletePage (DeletePageRequest input) {
LOG.finer("Entering deletePage");
DeletePageResponse output = new DeletePageResponse();
try {
ApiValidator.notNull(input, DeletePageRequest.class, "input");
ApiValidator.accessCode(input.accessCode, "input.accessCode");
output.session = input.session = SessionValidator.lookupAndExtend(
input.session, "input.session");
input.session.user = UserServiceProvider.provide().getUser(
Long.valueOf(input.session.userKey.getId()));
UserValidator.authorisation(input.session.user, Arrays
.asList(PermissionServiceProvider.provide()
.getCodePermission(PermissionHelper.MANAGE_PAGES)),
"input.session.user");
input.page = PageValidator.lookup(input.page, "input.page");
PageServiceProvider.provide().deletePage(input.page);
UserHelper.stripPassword(output.session == null ? null
: output.session.user);
output.status = StatusType.StatusTypeSuccess;
} catch (Exception e) {
output.status = StatusType.StatusTypeFailure;
output.error = convertToErrorAndLog(LOG, e);
}
LOG.finer("Exiting deletePage");
return output;
}
public CreatePageResponse createPage (CreatePageRequest input) {
LOG.finer("Entering createPage");
CreatePageResponse output = new CreatePageResponse();
try {
ApiValidator.notNull(input, CreatePageRequest.class, "input");
ApiValidator.accessCode(input.accessCode, "input.accessCode");
output.session = input.session = SessionValidator.lookupAndExtend(
input.session, "input.session");
input.session.user = UserServiceProvider.provide().getUser(
Long.valueOf(input.session.userKey.getId()));
UserValidator.authorisation(input.session.user, Arrays
.asList(PermissionServiceProvider.provide()
.getCodePermission(PermissionHelper.MANAGE_PAGES)),
"input.session.user");
input.page = PageValidator.validate(input.page, "input.page");
input.page.slug = PostHelper.slugify(input.page.title);
output.page = PageServiceProvider.provide().addPage(input.page);
UserHelper.stripPassword(output.session == null ? null
: output.session.user);
output.status = StatusType.StatusTypeSuccess;
} catch (Exception e) {
output.status = StatusType.StatusTypeFailure;
output.error = convertToErrorAndLog(LOG, e);
}
LOG.finer("Exiting createPage");
return output;
}
public GetPagesResponse getPages (GetPagesRequest input) {
LOG.finer("Entering getPages");
GetPagesResponse output = new GetPagesResponse();
try {
ApiValidator.notNull(input, GetPagesRequest.class, "input");
ApiValidator.accessCode(input.accessCode, "input.accessCode");
output.session = input.session = SessionValidator.lookupAndExtend(
input.session, "input.session");
if (input.pager == null) {
input.pager = PagerHelper.createDefaultPager();
}
if (input.query == null || input.query.trim().length() == 0) {
output.pages = PageServiceProvider.provide().getPages(
input.includePosts, input.pager.start,
input.pager.count,
PageSortType.fromString(input.pager.sortBy),
input.pager.sortDirection);
} else {
output.pages = PageServiceProvider.provide()
.getPartialSlugPages(input.query, input.includePosts,
input.pager.start, input.pager.count,
PageSortType.fromString(input.pager.sortBy),
input.pager.sortDirection);
}
for (Page page : output.pages) {
page.owner = UserHelper
.stripPassword(UserServiceProvider.provide().getUser(
Long.valueOf(page.ownerKey.getId())));
}
output.pager = PagerHelper.moveForward(input.pager);
UserHelper.stripPassword(output.session == null ? null
: output.session.user);
output.status = StatusType.StatusTypeSuccess;
} catch (Exception e) {
output.status = StatusType.StatusTypeFailure;
output.error = convertToErrorAndLog(LOG, e);
}
LOG.finer("Exiting getPages");
return output;
}
public GetPageResponse getPage (GetPageRequest input) {
LOG.finer("Entering getPage");
GetPageResponse output = new GetPageResponse();
try {
ApiValidator.notNull(input, GetPageRequest.class, "input");
ApiValidator.accessCode(input.accessCode, "input.accessCode");
if (input.session != null) {
try {
output.session = input.session = SessionValidator
.lookupAndExtend(input.session, "input.session");
} catch (InputValidationException ex) {
output.session = input.session = null;
}
}
output.page = input.page = PageValidator.lookup(input.page,
"input.page");
if (output.page.parentKey != null) {
output.page.parent = PageValidator.lookup(PersistenceService
.dataType(Page.class, output.page.parentKey),
"input.page.parent");
}
if (Boolean.TRUE.equals(input.includePosts)) {
output.page = PageServiceProvider.provide().getPage(
input.page.id, input.includePosts);
}
output.page.owner = UserHelper.stripPassword(UserServiceProvider
.provide().getUser(
Long.valueOf(output.page.ownerKey.getId())));
UserHelper.stripPassword(output.session == null ? null
: output.session.user);
output.status = StatusType.StatusTypeSuccess;
} catch (Exception e) {
output.status = StatusType.StatusTypeFailure;
output.error = convertToErrorAndLog(LOG, e);
}
LOG.finer("Exiting getPage");
return output;
}
}
|
src/main/java/com/willshex/blogwt/server/api/page/PageApi.java
|
//
// PageApi.java
// blogwt
//
// Created by William Shakour on June 21, 2015.
// Copyright © 2015 WillShex Limited. All rights reserved.
//
package com.willshex.blogwt.server.api.page;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import com.willshex.blogwt.server.api.validation.ApiValidator;
import com.willshex.blogwt.server.api.validation.FormValidator;
import com.willshex.blogwt.server.api.validation.PageValidator;
import com.willshex.blogwt.server.api.validation.SessionValidator;
import com.willshex.blogwt.server.api.validation.UserValidator;
import com.willshex.blogwt.server.helper.EmailHelper;
import com.willshex.blogwt.server.service.PersistenceService;
import com.willshex.blogwt.server.service.page.PageServiceProvider;
import com.willshex.blogwt.server.service.permission.PermissionServiceProvider;
import com.willshex.blogwt.server.service.property.PropertyServiceProvider;
import com.willshex.blogwt.server.service.user.UserServiceProvider;
import com.willshex.blogwt.shared.api.datatype.Field;
import com.willshex.blogwt.shared.api.datatype.Page;
import com.willshex.blogwt.shared.api.datatype.PageSortType;
import com.willshex.blogwt.shared.api.datatype.Permission;
import com.willshex.blogwt.shared.api.datatype.Property;
import com.willshex.blogwt.shared.api.page.call.CreatePageRequest;
import com.willshex.blogwt.shared.api.page.call.CreatePageResponse;
import com.willshex.blogwt.shared.api.page.call.DeletePageRequest;
import com.willshex.blogwt.shared.api.page.call.DeletePageResponse;
import com.willshex.blogwt.shared.api.page.call.GetPageRequest;
import com.willshex.blogwt.shared.api.page.call.GetPageResponse;
import com.willshex.blogwt.shared.api.page.call.GetPagesRequest;
import com.willshex.blogwt.shared.api.page.call.GetPagesResponse;
import com.willshex.blogwt.shared.api.page.call.SubmitFormRequest;
import com.willshex.blogwt.shared.api.page.call.SubmitFormResponse;
import com.willshex.blogwt.shared.api.page.call.UpdatePageRequest;
import com.willshex.blogwt.shared.api.page.call.UpdatePageResponse;
import com.willshex.blogwt.shared.api.validation.ApiError;
import com.willshex.blogwt.shared.helper.PagerHelper;
import com.willshex.blogwt.shared.helper.PermissionHelper;
import com.willshex.blogwt.shared.helper.PostHelper;
import com.willshex.blogwt.shared.helper.PropertyHelper;
import com.willshex.blogwt.shared.helper.UserHelper;
import com.willshex.gson.json.service.server.ActionHandler;
import com.willshex.gson.json.service.server.InputValidationException;
import com.willshex.gson.json.service.server.ServiceException;
import com.willshex.gson.json.service.shared.StatusType;
public final class PageApi extends ActionHandler {
private static final Logger LOG = Logger.getLogger(Page.class.getName());
public SubmitFormResponse submitForm (SubmitFormRequest input) {
LOG.finer("Entering submitForm");
SubmitFormResponse output = new SubmitFormResponse();
try {
// send an email with the submitted fields
ApiValidator.notNull(input, UpdatePageRequest.class, "input");
ApiValidator.accessCode(input.accessCode, "input.accessCode");
output.session = input.session = SessionValidator.lookupAndExtend(
input.session, "input.session");
input.form = FormValidator.validate(input.form, "input.form");
Property email = PropertyServiceProvider.provide()
.getNamedProperty(PropertyHelper.OUTGOING_EMAIL);
Property title = PropertyServiceProvider.provide()
.getNamedProperty(PropertyHelper.TITLE);
StringBuffer body = new StringBuffer();
for (Field field : input.form.fields) {
body.append(field.name);
body.append(":");
body.append(field.value);
body.append("\n\n");
}
if (!EmailHelper.sendEmail(email.value, title.value, "Submit form",
body.toString(), false))
ApiValidator.throwServiceError(ServiceException.class,
ApiError.FailedToSendEmail, "input.form");
UserHelper.stripPassword(output.session == null ? null
: output.session.user);
output.status = StatusType.StatusTypeSuccess;
} catch (Exception e) {
output.status = StatusType.StatusTypeFailure;
output.error = convertToErrorAndLog(LOG, e);
}
LOG.finer("Exiting submitForm");
return output;
}
public UpdatePageResponse updatePage (UpdatePageRequest input) {
LOG.finer("Entering updatePage");
UpdatePageResponse output = new UpdatePageResponse();
try {
ApiValidator.notNull(input, UpdatePageRequest.class, "input");
ApiValidator.accessCode(input.accessCode, "input.accessCode");
output.session = input.session = SessionValidator.lookupAndExtend(
input.session, "input.session");
List<Permission> permissions = new ArrayList<Permission>();
Permission postPermission = PermissionServiceProvider.provide()
.getCodePermission(PermissionHelper.MANAGE_PAGES);
permissions.add(postPermission);
input.session.user = UserServiceProvider.provide().getUser(
Long.valueOf(input.session.userKey.getId()));
UserValidator.authorisation(input.session.user, permissions,
"input.session.user");
Page updatedPage = input.page;
input.page = PageValidator.lookup(input.page, "input.page");
updatedPage = PageValidator.validate(updatedPage, "input.page");
input.page.hasChildren = updatedPage.hasChildren;
input.page.parent = updatedPage.parent;
input.page.posts = updatedPage.posts;
input.page.priority = updatedPage.priority;
input.page.title = updatedPage.title;
input.page.slug = PostHelper.slugify(input.page.title);
PageServiceProvider.provide().updatePage(input.page);
UserHelper.stripPassword(output.session == null ? null
: output.session.user);
output.status = StatusType.StatusTypeSuccess;
} catch (Exception e) {
output.status = StatusType.StatusTypeFailure;
output.error = convertToErrorAndLog(LOG, e);
}
LOG.finer("Exiting updatePage");
return output;
}
public DeletePageResponse deletePage (DeletePageRequest input) {
LOG.finer("Entering deletePage");
DeletePageResponse output = new DeletePageResponse();
try {
ApiValidator.notNull(input, DeletePageRequest.class, "input");
ApiValidator.accessCode(input.accessCode, "input.accessCode");
output.session = input.session = SessionValidator.lookupAndExtend(
input.session, "input.session");
input.session.user = UserServiceProvider.provide().getUser(
Long.valueOf(input.session.userKey.getId()));
UserValidator.authorisation(input.session.user, Arrays
.asList(PermissionServiceProvider.provide()
.getCodePermission(PermissionHelper.MANAGE_PAGES)),
"input.session.user");
input.page = PageValidator.lookup(input.page, "input.page");
PageServiceProvider.provide().deletePage(input.page);
UserHelper.stripPassword(output.session == null ? null
: output.session.user);
output.status = StatusType.StatusTypeSuccess;
} catch (Exception e) {
output.status = StatusType.StatusTypeFailure;
output.error = convertToErrorAndLog(LOG, e);
}
LOG.finer("Exiting deletePage");
return output;
}
public CreatePageResponse createPage (CreatePageRequest input) {
LOG.finer("Entering createPage");
CreatePageResponse output = new CreatePageResponse();
try {
ApiValidator.notNull(input, CreatePageRequest.class, "input");
ApiValidator.accessCode(input.accessCode, "input.accessCode");
output.session = input.session = SessionValidator.lookupAndExtend(
input.session, "input.session");
input.session.user = UserServiceProvider.provide().getUser(
Long.valueOf(input.session.userKey.getId()));
UserValidator.authorisation(input.session.user, Arrays
.asList(PermissionServiceProvider.provide()
.getCodePermission(PermissionHelper.MANAGE_PAGES)),
"input.session.user");
input.page = PageValidator.validate(input.page, "input.page");
input.page.slug = PostHelper.slugify(input.page.title);
output.page = PageServiceProvider.provide().addPage(input.page);
UserHelper.stripPassword(output.session == null ? null
: output.session.user);
output.status = StatusType.StatusTypeSuccess;
} catch (Exception e) {
output.status = StatusType.StatusTypeFailure;
output.error = convertToErrorAndLog(LOG, e);
}
LOG.finer("Exiting createPage");
return output;
}
public GetPagesResponse getPages (GetPagesRequest input) {
LOG.finer("Entering getPages");
GetPagesResponse output = new GetPagesResponse();
try {
ApiValidator.notNull(input, GetPagesRequest.class, "input");
ApiValidator.accessCode(input.accessCode, "input.accessCode");
output.session = input.session = SessionValidator.lookupAndExtend(
input.session, "input.session");
if (input.pager == null) {
input.pager = PagerHelper.createDefaultPager();
}
if (input.query == null || input.query.trim().length() == 0) {
output.pages = PageServiceProvider.provide().getPages(
input.includePosts, input.pager.start,
input.pager.count,
PageSortType.fromString(input.pager.sortBy),
input.pager.sortDirection);
} else {
output.pages = PageServiceProvider.provide()
.getPartialSlugPages(input.query, input.includePosts,
input.pager.start, input.pager.count,
PageSortType.fromString(input.pager.sortBy),
input.pager.sortDirection);
}
for (Page page : output.pages) {
page.owner = UserHelper
.stripPassword(UserServiceProvider.provide().getUser(
Long.valueOf(page.ownerKey.getId())));
}
output.pager = PagerHelper.moveForward(input.pager);
UserHelper.stripPassword(output.session == null ? null
: output.session.user);
output.status = StatusType.StatusTypeSuccess;
} catch (Exception e) {
output.status = StatusType.StatusTypeFailure;
output.error = convertToErrorAndLog(LOG, e);
}
LOG.finer("Exiting getPages");
return output;
}
public GetPageResponse getPage (GetPageRequest input) {
LOG.finer("Entering getPage");
GetPageResponse output = new GetPageResponse();
try {
ApiValidator.notNull(input, GetPageRequest.class, "input");
ApiValidator.accessCode(input.accessCode, "input.accessCode");
if (input.session != null) {
try {
output.session = input.session = SessionValidator
.lookupAndExtend(input.session, "input.session");
} catch (InputValidationException ex) {
output.session = input.session = null;
}
}
output.page = input.page = PageValidator.lookup(input.page,
"input.page");
if (output.page.parentKey != null) {
output.page.parent = PageValidator.lookup(PersistenceService
.dataType(Page.class, output.page.parentKey),
"input.page.parent");
}
if (Boolean.TRUE.equals(input.includePosts)) {
output.page = PageServiceProvider.provide().getPage(
input.page.id, input.includePosts);
}
output.page.owner = UserHelper.stripPassword(UserServiceProvider
.provide().getUser(
Long.valueOf(output.page.ownerKey.getId())));
UserHelper.stripPassword(output.session == null ? null
: output.session.user);
output.status = StatusType.StatusTypeSuccess;
} catch (Exception e) {
output.status = StatusType.StatusTypeFailure;
output.error = convertToErrorAndLog(LOG, e);
}
LOG.finer("Exiting getPage");
return output;
}
}
|
if catcha field is found validate it
|
src/main/java/com/willshex/blogwt/server/api/page/PageApi.java
|
if catcha field is found validate it
|
|
Java
|
apache-2.0
|
34916aa602208633a676c7a2430af07a283a7e23
| 0
|
pwielgolaski/gatling,gatling/gatling,ryez/gatling,wiacekm/gatling,timve/gatling,thkluge/gatling,thkluge/gatling,GabrielPlassard/gatling,thkluge/gatling,gatling/gatling,MykolaB/gatling,ryez/gatling,wiacekm/gatling,wiacekm/gatling,MykolaB/gatling,thkluge/gatling,wiacekm/gatling,pwielgolaski/gatling,gatling/gatling,timve/gatling,MykolaB/gatling,ryez/gatling,ryez/gatling,wiacekm/gatling,GabrielPlassard/gatling,GabrielPlassard/gatling,GabrielPlassard/gatling,timve/gatling,pwielgolaski/gatling,MykolaB/gatling,gatling/gatling,pwielgolaski/gatling,timve/gatling,gatling/gatling
|
/**
* Copyright 2011-2013 eBusiness Information, Groupe Excilys (www.excilys.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.
*/
package io.gatling.mojo;
import static java.util.Arrays.asList;
import static org.codehaus.plexus.util.StringUtils.trim;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.exec.ExecuteException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.toolchain.Toolchain;
import org.apache.maven.toolchain.ToolchainManager;
import org.codehaus.plexus.util.DirectoryScanner;
import scala_maven_executions.JavaMainCaller;
import scala_maven_executions.MainHelper;
import scala_maven_executions.MainWithArgsInFile;
import io.gatling.app.CommandLineConstants;
import io.gatling.app.Gatling;
/**
* Mojo to execute Gatling.
*
* @goal execute
* @phase integration-test
* @description Gatling Maven Plugin
* @requiresDependencyResolution test
*/
public class GatlingMojo extends AbstractMojo {
public static final String[] DEFAULT_INCLUDES = { "**/*.scala" };
public static final String GATLING_MAIN_CLASS = "io.gatling.app.Gatling";
public static final String[] JVM_ARGS = new String[] { "-server", "-XX:+UseThreadPriorities", "-XX:ThreadPriorityPolicy=42", "-Xms512M", "-Xmx512M", "-Xmn100M", "-Xss2M", "-XX:+HeapDumpOnOutOfMemoryError", "-XX:+AggressiveOpts", "-XX:+OptimizeStringConcat",
"-XX:+UseFastAccessorMethods", "-XX:+UseParNewGC", "-XX:+UseConcMarkSweepGC", "-XX:+CMSParallelRemarkEnabled", "-XX:+CMSClassUnloadingEnabled", "-XX:CMSInitiatingOccupancyFraction=75", "-XX:+UseCMSInitiatingOccupancyOnly", "-XX:SurvivorRatio=8",
"-XX:MaxTenuringThreshold=1" };
/**
* Runs simulation but does not generate reports. By default false.
*
* @parameter expression="${gatling.noReports}" alias="nr" default-value="false"
* @description Runs simulation but does not generate reports
*/
private boolean noReports;
/**
* Generates the reports for the simulation in this folder.
*
* @parameter expression="${gatling.reportsOnly}" alias="ro"
* @description Generates the reports for the simulation in this folder
*/
private String reportsOnly;
/**
* Uses this file as the configuration file.
*
* @parameter expression="${gatling.configDir}" alias="cd" default-value="${basedir}/src/test/resources"
* @description Uses this file as the configuration directory
*/
private File configDir;
/**
* Uses this folder to discover simulations that could be run
*
* @parameter expression="${gatling.simulationsFolder}" alias="sf" default-value="${basedir}/src/test/scala"
* @description Uses this folder to discover simulations that could be run
*/
private File simulationsFolder;
/**
* Sets the list of include patterns to use in directory scan for simulations. Relative to simulationsFolder.
*
* @parameter
* @description Include patterns to use in directory scan for simulations
*/
private List<String> includes;
/**
* Sets the list of exclude patterns to use in directory scan for simulations. Relative to simulationsFolder.
*
* @parameter
* @description Exclude patterns to use in directory scan for simulations
*/
private List<String> excludes;
/**
* A name of a Simulation class to run. This takes precedence over the includes / excludes parameters.
*
* @parameter expression="${gatling.simulationClass}" alias="s"
* @description The name of the Simulation class to run
*/
private String simulationClass;
/**
* Uses this folder as the folder where feeders are stored
*
* @parameter expression="${gatling.dataFolder}" alias="df" default-value="${basedir}/src/test/resources/data"
* @description Uses this folder as the folder where feeders are stored
*/
private File dataFolder;
/**
* Uses this folder as the folder where request bodies are stored
*
* @parameter expression="${gatling.requestBodiesFolder}" alias="bf" default-value="${basedir}/src/test/resources/request-bodies"
* @description Uses this folder as the folder where request bodies are stored
*/
private File requestBodiesFolder;
/**
* Uses this folder as the folder where results are stored
*
* @parameter expression="${gatling.resultsFolder}" alias="rf" default-value="${basedir}/target/gatling/results"
* @description Uses this folder as the folder where results are stored
*/
private File resultsFolder;
/**
* Extra JVM arguments to pass when running Gatling.
*
* @parameter
*/
private List<String> jvmArgs;
/**
* Forks the execution of Gatling plugin into a separate JVM.
*
* @parameter expression="${gatling.fork}" default-value="true"
* @description Forks the execution of Gatling plugin into a separate JVM
*/
private boolean fork;
/**
* Will cause the project build to look successful, rather than fail, even if there are Gatling test failures. This can be useful on a continuous integration server, if your only option to be able to collect output files, is if the project builds successfully.
*
* @parameter expression="${gatling.failOnError}" default-value="true"
*/
private boolean failOnError;
/**
* Force the name of the directory generated for the results of the run
*
* @parameter expression="${gatling.outputName}" alias="on"
* @description Uses this as the base name of the results folder
*/
private String outputDirectoryBaseName;
/**
* Propagates System properties in fork mode to forked process
*
* @parameter expression="${gatling.propagateSystemProperties}" default-value="true"
* @description Propagates System properties in fork mode to forked process
*/
private boolean propagateSystemProperties;
/**
* Disable the plugin
*
* @parameter expression="${gatling.skip}" default-value="false"
* @description Disable the plugin
*/
private boolean skip;
/**
* The Maven Project
*
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject mavenProject;
/**
* The Maven Session Object
*
* @parameter expression="${session}"
* @required
* @readonly
*/
private MavenSession session;
/**
* The toolchain manager to use.
*
* @component
* @required
* @readonly
*/
private ToolchainManager toolchainManager;
/**
* Executes Gatling simulations.
*/
@Override
public void execute() throws MojoExecutionException {
// Create results directories
resultsFolder.mkdirs();
try {
executeGatling(jvmArgs().toArray(new String[0]), gatlingArgs().toArray(new String[0]));
} catch (Exception e) {
if (failOnError) {
throw new MojoExecutionException("Gatling failed.", e);
} else {
getLog().warn("There was some errors while running your simulation, but failOnError set to false won't fail your build.");
}
}
}
private void executeGatling(String[] jvmArgs, String[] gatlingArgs) throws Exception {
if (!skip) {
String testClasspath = buildTestClasspath();
if (fork) {
Toolchain toolchain = toolchainManager.getToolchainFromBuildContext("jdk", session);
JavaMainCaller caller = new GatlingJavaMainCallerByFork(this, GATLING_MAIN_CLASS, testClasspath, jvmArgs, gatlingArgs, false, toolchain, propagateSystemProperties);
try {
caller.run(false);
} catch (ExecuteException e) {
if (e.getExitValue() == Gatling.SIMULATION_ASSERTIONS_FAILED()) {
throw new GatlingSimulationAssertionsFailedException(e);
}
}
} else {
GatlingJavaMainCallerInProcess caller = new GatlingJavaMainCallerInProcess(this, GATLING_MAIN_CLASS, testClasspath, gatlingArgs);
int returnCode = caller.run();
if (returnCode == Gatling.SIMULATION_ASSERTIONS_FAILED()) {
throw new GatlingSimulationAssertionsFailedException();
}
}
} else {
getLog().info("Skipping gatling-maven-plugin");
}
}
private String buildTestClasspath() throws Exception {
@SuppressWarnings("unchecked")
List<String> testClasspathElements = (List<String>) mavenProject.getTestClasspathElements();
testClasspathElements.add(configDir.getPath());
// Find plugin jar and add it to classpath
testClasspathElements.add(MainHelper.locateJar(GatlingMojo.class));
// Jenkins seems to need scala-maven-plugin in the test classpath in order to work
testClasspathElements.add(MainHelper.locateJar(MainWithArgsInFile.class));
return MainHelper.toMultiPath(testClasspathElements);
}
private List<String> jvmArgs() {
List<String> jvmArguments = (jvmArgs != null) ? jvmArgs : new ArrayList<String>();
jvmArguments.addAll(Arrays.asList(JVM_ARGS));
return jvmArguments;
}
private List<String> gatlingArgs() throws Exception {
// Solves the simulations, if no simulation file is defined
if (simulationClass == null) {
List<String> simulations = resolveSimulations(simulationsFolder, includes, excludes);
if (simulations.isEmpty()) {
getLog().error("No simulations to run");
throw new MojoFailureException("No simulations to run");
} else if (simulations.size() > 1) {
getLog().error("More than 1 simulation to run, need to specify one");
throw new MojoFailureException("More than 1 simulation to run, need to specify one");
} else {
simulationClass = simulations.get(0);
}
}
// Arguments
List<String> args = new ArrayList<String>();
args.addAll(asList("-" + CommandLineConstants.CLI_DATA_FOLDER(), dataFolder.getCanonicalPath(),//
"-" + CommandLineConstants.CLI_RESULTS_FOLDER(), resultsFolder.getCanonicalPath(),// ;
"-" + CommandLineConstants.CLI_REQUEST_BODIES_FOLDER(), requestBodiesFolder.getCanonicalPath(),//
"-" + CommandLineConstants.CLI_SIMULATIONS_FOLDER(), simulationsFolder.getCanonicalPath(),//
"-" + CommandLineConstants.CLI_SIMULATION(), simulationClass));
if (noReports) {
args.add("-" + CommandLineConstants.CLI_NO_REPORTS());
}
if (reportsOnly != null) {
args.addAll(asList("-" + CommandLineConstants.CLI_REPORTS_ONLY(), reportsOnly));
}
if (outputDirectoryBaseName != null) {
args.addAll(asList("-" + CommandLineConstants.CLI_OUTPUT_DIRECTORY_BASE_NAME(), outputDirectoryBaseName));
}
return args;
}
public static String fileNameToClassName(String fileName) {
String trimmedFileName = trim(fileName);
int lastIndexOfExtensionDelim = trimmedFileName.lastIndexOf(".");
String strippedFileName = lastIndexOfExtensionDelim > 0 ? trimmedFileName.substring(0, lastIndexOfExtensionDelim) : trimmedFileName;
return strippedFileName.replace(File.separatorChar, '.');
}
/**
* Resolve simulation files to execute from the simulation folder and includes/excludes.
*
* @return a comma separated String of simulation class names.
*/
private List<String> resolveSimulations(File simulationsFolder, List<String> includes, List<String> excludes) {
DirectoryScanner scanner = new DirectoryScanner();
// Set Base Directory
getLog().debug("effective simulationsFolder: " + simulationsFolder.getPath());
scanner.setBasedir(simulationsFolder);
// Resolve includes
if (includes != null && !includes.isEmpty()) {
scanner.setIncludes(includes.toArray(new String[includes.size()]));
} else {
scanner.setIncludes(DEFAULT_INCLUDES);
}
// Resolve excludes
if (excludes != null && !excludes.isEmpty()) {
scanner.setExcludes(excludes.toArray(new String[excludes.size()]));
}
// Resolve simulations to execute
scanner.scan();
String[] includedFiles = scanner.getIncludedFiles();
List<String> includedClassNames = new ArrayList<String>();
for (String includedFile : includedFiles) {
includedClassNames.add(fileNameToClassName(includedFile));
}
getLog().debug("resolved simulation classes: " + includedClassNames);
return includedClassNames;
}
}
|
gatling-maven-plugin/src/main/java/io/gatling/mojo/GatlingMojo.java
|
/**
* Copyright 2011-2013 eBusiness Information, Groupe Excilys (www.excilys.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.
*/
package io.gatling.mojo;
import static java.util.Arrays.asList;
import static org.codehaus.plexus.util.StringUtils.trim;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.exec.ExecuteException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.toolchain.Toolchain;
import org.apache.maven.toolchain.ToolchainManager;
import org.codehaus.plexus.util.DirectoryScanner;
import scala_maven_executions.JavaMainCaller;
import scala_maven_executions.MainHelper;
import scala_maven_executions.MainWithArgsInFile;
import io.gatling.app.CommandLineConstants;
import io.gatling.app.Gatling;
/**
* Mojo to execute Gatling.
*
* @goal execute
* @phase integration-test
* @description Gatling Maven Plugin
* @requiresDependencyResolution test
*/
public class GatlingMojo extends AbstractMojo {
public static final String[] DEFAULT_INCLUDES = {"**/*.scala"};
public static final String GATLING_MAIN_CLASS = "io.gatling.app.Gatling";
public static final String[] JVM_ARGS = new String[]{"-server", "-XX:+UseThreadPriorities", "-XX:ThreadPriorityPolicy=42",
"-Xms512M", "-Xmx512M", "-Xmn100M", "-Xss2M", "-XX:+HeapDumpOnOutOfMemoryError", "-XX:+AggressiveOpts", "-XX:+OptimizeStringConcat",
"-XX:+UseFastAccessorMethods", "-XX:+UseParNewGC", "-XX:+UseConcMarkSweepGC", "-XX:+CMSParallelRemarkEnabled", "-XX:+CMSClassUnloadingEnabled",
"-XX:CMSInitiatingOccupancyFraction=75", "-XX:+UseCMSInitiatingOccupancyOnly", "-XX:SurvivorRatio=8", "-XX:MaxTenuringThreshold=1"};
/**
* Runs simulation but does not generate reports. By default false.
*
* @parameter expression="${gatling.noReports}" alias="nr"
* default-value="false"
* @description Runs simulation but does not generate reports
*/
private boolean noReports;
/**
* Generates the reports for the simulation in this folder.
*
* @parameter expression="${gatling.reportsOnly}" alias="ro"
* @description Generates the reports for the simulation in this folder
*/
private String reportsOnly;
/**
* Uses this file as the configuration file.
*
* @parameter expression="${gatling.configDir}" alias="cd"
* default-value="${basedir}/src/test/resources"
* @description Uses this file as the configuration directory
*/
private File configDir;
/**
* Uses this folder to discover simulations that could be run
*
* @parameter expression="${gatling.simulationsFolder}" alias="sf"
* default-value="${basedir}/src/test/scala"
* @description Uses this folder to discover simulations that could be run
*/
private File simulationsFolder;
/**
* Sets the list of include patterns to use in directory scan for
* simulations. Relative to simulationsFolder.
*
* @parameter
* @description Include patterns to use in directory scan for simulations
*/
private List<String> includes;
/**
* Sets the list of exclude patterns to use in directory scan for
* simulations. Relative to simulationsFolder.
*
* @parameter
* @description Exclude patterns to use in directory scan for simulations
*/
private List<String> excludes;
/**
* A name of a Simulation class to run. This takes precedence over the
* includes / excludes parameters.
*
* @parameter expression="${gatling.simulationClass}" alias="s"
* @description The name of the Simulation class to run
*/
private String simulationClass;
/**
* Uses this folder as the folder where feeders are stored
*
* @parameter expression="${gatling.dataFolder}" alias="df"
* default-value="${basedir}/src/test/resources/data"
* @description Uses this folder as the folder where feeders are stored
*/
private File dataFolder;
/**
* Uses this folder as the folder where request bodies are stored
*
* @parameter expression="${gatling.requestBodiesFolder}" alias="bf"
* default-value="${basedir}/src/test/resources/request-bodies"
* @description Uses this folder as the folder where request bodies are
* stored
*/
private File requestBodiesFolder;
/**
* Uses this folder as the folder where results are stored
*
* @parameter expression="${gatling.resultsFolder}" alias="rf"
* default-value="${basedir}/target/gatling/results"
* @description Uses this folder as the folder where results are stored
*/
private File resultsFolder;
/**
* Extra JVM arguments to pass when running Gatling.
*
* @parameter
*/
private List<String> jvmArgs;
/**
* Forks the execution of Gatling plugin into a separate JVM.
*
* @parameter expression="${gatling.fork}" default-value="true"
* @description Forks the execution of Gatling plugin into a separate JVM
*/
private boolean fork;
/**
* Will cause the project build to look successful, rather than fail, even
* if there are Gatling test failures. This can be useful on a continuous
* integration server, if your only option to be able to collect output
* files, is if the project builds successfully.
*
* @parameter expression="${gatling.failOnError}" default-value="true"
*/
private boolean failOnError;
/**
* Force the name of the directory generated for the results of the run
*
* @parameter expression="${gatling.outputName}" alias="on"
* @description Uses this as the base name of the results folder
*/
private String outputDirectoryBaseName;
/**
* Propagates System properties in fork mode to forked process
*
* @parameter expression="${gatling.propagateSystemProperties}" default-value="true"
* @description Propagates System properties in fork mode to forked process
*/
private boolean propagateSystemProperties;
/**
* The Maven Project
*
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject mavenProject;
/**
* The Maven Session Object
*
* @parameter expression="${session}"
* @required
* @readonly
*/
private MavenSession session;
/**
* The toolchain manager to use.
*
* @component
* @required
* @readonly
*/
private ToolchainManager toolchainManager;
/**
* Executes Gatling simulations.
*/
@Override
public void execute() throws MojoExecutionException {
// Create results directories
resultsFolder.mkdirs();
try {
executeGatling(jvmArgs().toArray(new String[0]), gatlingArgs().toArray(new String[0]));
} catch (Exception e) {
if (failOnError) {
throw new MojoExecutionException("Gatling failed.", e);
} else {
getLog().warn("There was some errors while running your simulation, but failOnError set to false won't fail your build.");
}
}
}
private void executeGatling(String[] jvmArgs, String[] gatlingArgs) throws Exception {
// Setup classpath
String testClasspath = buildTestClasspath();
// Setup toolchain
Toolchain toolchain = toolchainManager.getToolchainFromBuildContext("jdk", session);
if (fork) {
JavaMainCaller caller = new GatlingJavaMainCallerByFork(this, GATLING_MAIN_CLASS, testClasspath, jvmArgs, gatlingArgs, false, toolchain, propagateSystemProperties);
try {
caller.run(false);
} catch (ExecuteException e) {
if (e.getExitValue() == Gatling.SIMULATION_ASSERTIONS_FAILED()) {
throw new GatlingSimulationAssertionsFailedException(e);
}
}
} else {
GatlingJavaMainCallerInProcess caller = new GatlingJavaMainCallerInProcess(this, GATLING_MAIN_CLASS, testClasspath, gatlingArgs);
int returnCode = caller.run();
if (returnCode == Gatling.SIMULATION_ASSERTIONS_FAILED()) {
throw new GatlingSimulationAssertionsFailedException();
}
}
}
private String buildTestClasspath() throws Exception {
@SuppressWarnings("unchecked")
List<String> testClasspathElements = (List<String>) mavenProject.getTestClasspathElements();
testClasspathElements.add(configDir.getPath());
// Find plugin jar and add it to classpath
testClasspathElements.add(MainHelper.locateJar(GatlingMojo.class));
// Jenkins seems to need scala-maven-plugin in the test classpath in order to work
testClasspathElements.add(MainHelper.locateJar(MainWithArgsInFile.class));
return MainHelper.toMultiPath(testClasspathElements);
}
private List<String> jvmArgs() {
List<String> jvmArguments = (jvmArgs != null) ? jvmArgs : new ArrayList<String>();
jvmArguments.addAll(Arrays.asList(JVM_ARGS));
return jvmArguments;
}
private List<String> gatlingArgs() throws Exception {
// Solves the simulations, if no simulation file is defined
if (simulationClass == null) {
List<String> simulations = resolveSimulations(simulationsFolder, includes, excludes);
if (simulations.isEmpty()) {
getLog().error("No simulations to run");
throw new MojoFailureException("No simulations to run");
} else if (simulations.size() > 1) {
getLog().error("More than 1 simulation to run, need to specify one");
throw new MojoFailureException("More than 1 simulation to run, need to specify one");
} else {
simulationClass = simulations.get(0);
}
}
// Arguments
List<String> args = new ArrayList<String>();
args.addAll(asList("-" + CommandLineConstants.CLI_DATA_FOLDER(), dataFolder.getCanonicalPath(),//
"-" + CommandLineConstants.CLI_RESULTS_FOLDER(), resultsFolder.getCanonicalPath(),// ;
"-" + CommandLineConstants.CLI_REQUEST_BODIES_FOLDER(), requestBodiesFolder.getCanonicalPath(),//
"-" + CommandLineConstants.CLI_SIMULATIONS_FOLDER(), simulationsFolder.getCanonicalPath(),//
"-" + CommandLineConstants.CLI_SIMULATION(), simulationClass));
if (noReports) {
args.add("-" + CommandLineConstants.CLI_NO_REPORTS());
}
if (reportsOnly != null) {
args.addAll(asList("-" + CommandLineConstants.CLI_REPORTS_ONLY(), reportsOnly));
}
if (outputDirectoryBaseName != null) {
args.addAll(asList("-" + CommandLineConstants.CLI_OUTPUT_DIRECTORY_BASE_NAME(), outputDirectoryBaseName));
}
return args;
}
public static String fileNameToClassName(String fileName) {
String trimmedFileName = trim(fileName);
int lastIndexOfExtensionDelim = trimmedFileName.lastIndexOf(".");
String strippedFileName = lastIndexOfExtensionDelim > 0 ? trimmedFileName.substring(0, lastIndexOfExtensionDelim) : trimmedFileName;
return strippedFileName.replace(File.separatorChar, '.');
}
/**
* Resolve simulation files to execute from the simulation folder and
* includes/excludes.
*
* @return a comma separated String of simulation class names.
*/
private List<String> resolveSimulations(File simulationsFolder, List<String> includes, List<String> excludes) {
DirectoryScanner scanner = new DirectoryScanner();
// Set Base Directory
getLog().debug("effective simulationsFolder: " + simulationsFolder.getPath());
scanner.setBasedir(simulationsFolder);
// Resolve includes
if (includes != null && !includes.isEmpty()) {
scanner.setIncludes(includes.toArray(new String[includes.size()]));
} else {
scanner.setIncludes(DEFAULT_INCLUDES);
}
// Resolve excludes
if (excludes != null && !excludes.isEmpty()) {
scanner.setExcludes(excludes.toArray(new String[excludes.size()]));
}
// Resolve simulations to execute
scanner.scan();
String[] includedFiles = scanner.getIncludedFiles();
List<String> includedClassNames = new ArrayList<String>();
for (String includedFile : includedFiles) {
includedClassNames.add(fileNameToClassName(includedFile));
}
getLog().debug("resolved simulation classes: " + includedClassNames);
return includedClassNames;
}
}
|
Introduce gatling.skip property for disabling maven plugin, close #1063
|
gatling-maven-plugin/src/main/java/io/gatling/mojo/GatlingMojo.java
|
Introduce gatling.skip property for disabling maven plugin, close #1063
|
|
Java
|
apache-2.0
|
df43e3c460008984ebee092e0191971d23a376fb
| 0
|
CryptArc/templecoin-bither,neurocis/bither-android,leerduo/bither-android,bither/bither-android
|
/*
* Copyright 2014 http://Bither.net
*
* 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 net.bither.camera;
import android.annotation.SuppressLint;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PreviewCallback;
import android.view.SurfaceHolder;
import com.google.zxing.PlanarYUVLuminanceSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public final class CameraManager {
private static final int MIN_FRAME_SIZE = 320;
private static final int MAX_FRAME_SIZE = 1000;
private static final int MIN_PREVIEW_PIXELS = 470 * 320; // normal screen
private static final int MAX_PREVIEW_PIXELS = 1280 * 720;
private Camera camera;
private Camera.Size cameraResolution;
private Rect frame;
private Rect framePreview;
private static final Logger log = LoggerFactory
.getLogger(CameraManager.class);
public Rect getFrame() {
return frame;
}
public Rect getFramePreview() {
return framePreview;
}
public Camera open(final SurfaceHolder holder,
final boolean continuousAutoFocus) throws IOException {
// try back-facing camera
camera = Camera.open();
// fall back to using front-facing camera
if (camera == null) {
final int cameraCount = Camera.getNumberOfCameras();
final CameraInfo cameraInfo = new CameraInfo();
// search for front-facing camera
for (int i = 0; i < cameraCount; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
camera = Camera.open(i);
break;
}
}
}
camera.setDisplayOrientation(90);
camera.setPreviewDisplay(holder);
final Camera.Parameters parameters = camera.getParameters();
final Rect surfaceFrame = holder.getSurfaceFrame();
cameraResolution = findBestPreviewSizeValue(parameters, surfaceFrame);
final int surfaceWidth = surfaceFrame.width();
final int surfaceHeight = surfaceFrame.height();
final int rawSize = Math.min(surfaceWidth * 4 / 5,
surfaceHeight * 4 / 5);
final int frameSize = Math.max(MIN_FRAME_SIZE,
Math.min(MAX_FRAME_SIZE, rawSize));
final int leftOffset = (surfaceWidth - frameSize) / 2;
final int topOffset = (surfaceHeight - frameSize) / 2;
frame = new Rect(leftOffset, topOffset, leftOffset + frameSize,
topOffset + frameSize);
framePreview = new Rect(frame.left * cameraResolution.height
/ surfaceWidth, frame.top * cameraResolution.width
/ surfaceHeight, frame.right * cameraResolution.height
/ surfaceWidth, frame.bottom * cameraResolution.width
/ surfaceHeight);
final String savedParameters = parameters == null ? null : parameters
.flatten();
try {
setDesiredCameraParameters(camera, cameraResolution,
continuousAutoFocus);
} catch (final RuntimeException x) {
if (savedParameters != null) {
final Camera.Parameters parameters2 = camera.getParameters();
parameters2.unflatten(savedParameters);
try {
camera.setParameters(parameters2);
setDesiredCameraParameters(camera, cameraResolution,
continuousAutoFocus);
} catch (final RuntimeException x2) {
log.info("problem setting camera parameters", x2);
}
}
}
camera.startPreview();
return camera;
}
public void close() {
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}
private static final Comparator<Camera.Size> numPixelComparator = new Comparator<Camera.Size>() {
@Override
public int compare(final Camera.Size size1, final Camera.Size size2) {
final int pixels1 = size1.height * size1.width;
final int pixels2 = size2.height * size2.width;
if (pixels1 < pixels2)
return 1;
else if (pixels1 > pixels2)
return -1;
else
return 0;
}
};
private static Camera.Size findBestPreviewSizeValue(
final Camera.Parameters parameters, Rect surfaceResolution) {
if (surfaceResolution.height() > surfaceResolution.width())
surfaceResolution = new Rect(0, 0, surfaceResolution.height(),
surfaceResolution.width());
final float screenAspectRatio = (float) surfaceResolution.width()
/ (float) surfaceResolution.height();
final List<Camera.Size> rawSupportedSizes = parameters
.getSupportedPreviewSizes();
if (rawSupportedSizes == null)
return parameters.getPreviewSize();
// sort by size, descending
final List<Camera.Size> supportedPreviewSizes = new ArrayList<Camera.Size>(
rawSupportedSizes);
Collections.sort(supportedPreviewSizes, numPixelComparator);
Camera.Size bestSize = null;
float diff = Float.POSITIVE_INFINITY;
for (final Camera.Size supportedPreviewSize : supportedPreviewSizes) {
final int realWidth = supportedPreviewSize.width;
final int realHeight = supportedPreviewSize.height;
final int realPixels = realWidth * realHeight;
if (realPixels < MIN_PREVIEW_PIXELS
|| realPixels > MAX_PREVIEW_PIXELS)
continue;
final boolean isCandidatePortrait = realWidth < realHeight;
final int maybeFlippedWidth = isCandidatePortrait ? realHeight
: realWidth;
final int maybeFlippedHeight = isCandidatePortrait ? realWidth
: realHeight;
if (maybeFlippedWidth == surfaceResolution.width()
&& maybeFlippedHeight == surfaceResolution.height())
return supportedPreviewSize;
final float aspectRatio = (float) maybeFlippedWidth
/ (float) maybeFlippedHeight;
final float newDiff = Math.abs(aspectRatio - screenAspectRatio);
if (newDiff < diff) {
bestSize = supportedPreviewSize;
diff = newDiff;
}
}
if (bestSize != null)
return bestSize;
else
return parameters.getPreviewSize();
}
@SuppressLint("InlinedApi")
private static void setDesiredCameraParameters(final Camera camera,
final Camera.Size cameraResolution,
final boolean continuousAutoFocus) {
final Camera.Parameters parameters = camera.getParameters();
if (parameters == null)
return;
final List<String> supportedFocusModes = parameters
.getSupportedFocusModes();
final String focusMode = continuousAutoFocus ? findValue(
supportedFocusModes,
Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE,
Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO,
Camera.Parameters.FOCUS_MODE_AUTO,
Camera.Parameters.FOCUS_MODE_MACRO) : findValue(
supportedFocusModes, Camera.Parameters.FOCUS_MODE_AUTO,
Camera.Parameters.FOCUS_MODE_MACRO);
if (focusMode != null)
parameters.setFocusMode(focusMode);
parameters.setPreviewSize(cameraResolution.width,
cameraResolution.height);
camera.setParameters(parameters);
}
public void requestPreviewFrame(final PreviewCallback callback) {
camera.setOneShotPreviewCallback(callback);
}
public PlanarYUVLuminanceSource buildLuminanceSource(final byte[] data) {
return new PlanarYUVLuminanceSource(data, cameraResolution.width,
cameraResolution.height, framePreview.top, framePreview.left,
framePreview.height(), framePreview.width(), false);
}
public void setTorch(final boolean enabled) {
if(camera == null){
return;
}
if (enabled != getTorchEnabled(camera))
setTorchEnabled(camera, enabled);
}
public boolean torchEnabled() {
if(camera == null){
return false;
}
return getTorchEnabled(camera);
}
private static boolean getTorchEnabled(final Camera camera) {
final Camera.Parameters parameters = camera.getParameters();
if (parameters != null) {
final String flashMode = camera.getParameters().getFlashMode();
return flashMode != null
&& (Camera.Parameters.FLASH_MODE_ON.equals(flashMode) || Camera.Parameters.FLASH_MODE_TORCH
.equals(flashMode));
}
return false;
}
private static void setTorchEnabled(final Camera camera,
final boolean enabled) {
final Camera.Parameters parameters = camera.getParameters();
final List<String> supportedFlashModes = parameters
.getSupportedFlashModes();
if (supportedFlashModes != null) {
final String flashMode;
if (enabled)
flashMode = findValue(supportedFlashModes,
Camera.Parameters.FLASH_MODE_TORCH,
Camera.Parameters.FLASH_MODE_ON);
else
flashMode = findValue(supportedFlashModes,
Camera.Parameters.FLASH_MODE_OFF);
if (flashMode != null) {
camera.cancelAutoFocus(); // autofocus can cause conflict
parameters.setFlashMode(flashMode);
camera.setParameters(parameters);
}
}
}
private static String findValue(final Collection<String> values,
final String... valuesToFind) {
for (final String valueToFind : valuesToFind)
if (values.contains(valueToFind))
return valueToFind;
return null;
}
}
|
bither-android/src/net/bither/camera/CameraManager.java
|
/*
* Copyright 2014 http://Bither.net
*
* 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 net.bither.camera;
import android.annotation.SuppressLint;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PreviewCallback;
import android.view.SurfaceHolder;
import com.google.zxing.PlanarYUVLuminanceSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public final class CameraManager {
private static final int MIN_FRAME_SIZE = 320;
private static final int MAX_FRAME_SIZE = 1000;
private static final int MIN_PREVIEW_PIXELS = 470 * 320; // normal screen
private static final int MAX_PREVIEW_PIXELS = 1280 * 720;
private Camera camera;
private Camera.Size cameraResolution;
private Rect frame;
private Rect framePreview;
private static final Logger log = LoggerFactory
.getLogger(CameraManager.class);
public Rect getFrame() {
return frame;
}
public Rect getFramePreview() {
return framePreview;
}
public Camera open(final SurfaceHolder holder,
final boolean continuousAutoFocus) throws IOException {
// try back-facing camera
camera = Camera.open();
// fall back to using front-facing camera
if (camera == null) {
final int cameraCount = Camera.getNumberOfCameras();
final CameraInfo cameraInfo = new CameraInfo();
// search for front-facing camera
for (int i = 0; i < cameraCount; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
camera = Camera.open(i);
break;
}
}
}
camera.setDisplayOrientation(90);
camera.setPreviewDisplay(holder);
final Camera.Parameters parameters = camera.getParameters();
final Rect surfaceFrame = holder.getSurfaceFrame();
cameraResolution = findBestPreviewSizeValue(parameters, surfaceFrame);
final int surfaceWidth = surfaceFrame.width();
final int surfaceHeight = surfaceFrame.height();
final int rawSize = Math.min(surfaceWidth * 4 / 5,
surfaceHeight * 4 / 5);
final int frameSize = Math.max(MIN_FRAME_SIZE,
Math.min(MAX_FRAME_SIZE, rawSize));
final int leftOffset = (surfaceWidth - frameSize) / 2;
final int topOffset = (surfaceHeight - frameSize) / 2;
frame = new Rect(leftOffset, topOffset, leftOffset + frameSize,
topOffset + frameSize);
framePreview = new Rect(frame.left * cameraResolution.height
/ surfaceWidth, frame.top * cameraResolution.width
/ surfaceHeight, frame.right * cameraResolution.height
/ surfaceWidth, frame.bottom * cameraResolution.width
/ surfaceHeight);
final String savedParameters = parameters == null ? null : parameters
.flatten();
try {
setDesiredCameraParameters(camera, cameraResolution,
continuousAutoFocus);
} catch (final RuntimeException x) {
if (savedParameters != null) {
final Camera.Parameters parameters2 = camera.getParameters();
parameters2.unflatten(savedParameters);
try {
camera.setParameters(parameters2);
setDesiredCameraParameters(camera, cameraResolution,
continuousAutoFocus);
} catch (final RuntimeException x2) {
log.info("problem setting camera parameters", x2);
}
}
}
camera.startPreview();
return camera;
}
public void close() {
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}
private static final Comparator<Camera.Size> numPixelComparator = new Comparator<Camera.Size>() {
@Override
public int compare(final Camera.Size size1, final Camera.Size size2) {
final int pixels1 = size1.height * size1.width;
final int pixels2 = size2.height * size2.width;
if (pixels1 < pixels2)
return 1;
else if (pixels1 > pixels2)
return -1;
else
return 0;
}
};
private static Camera.Size findBestPreviewSizeValue(
final Camera.Parameters parameters, Rect surfaceResolution) {
if (surfaceResolution.height() > surfaceResolution.width())
surfaceResolution = new Rect(0, 0, surfaceResolution.height(),
surfaceResolution.width());
final float screenAspectRatio = (float) surfaceResolution.width()
/ (float) surfaceResolution.height();
final List<Camera.Size> rawSupportedSizes = parameters
.getSupportedPreviewSizes();
if (rawSupportedSizes == null)
return parameters.getPreviewSize();
// sort by size, descending
final List<Camera.Size> supportedPreviewSizes = new ArrayList<Camera.Size>(
rawSupportedSizes);
Collections.sort(supportedPreviewSizes, numPixelComparator);
Camera.Size bestSize = null;
float diff = Float.POSITIVE_INFINITY;
for (final Camera.Size supportedPreviewSize : supportedPreviewSizes) {
final int realWidth = supportedPreviewSize.width;
final int realHeight = supportedPreviewSize.height;
final int realPixels = realWidth * realHeight;
if (realPixels < MIN_PREVIEW_PIXELS
|| realPixels > MAX_PREVIEW_PIXELS)
continue;
final boolean isCandidatePortrait = realWidth < realHeight;
final int maybeFlippedWidth = isCandidatePortrait ? realHeight
: realWidth;
final int maybeFlippedHeight = isCandidatePortrait ? realWidth
: realHeight;
if (maybeFlippedWidth == surfaceResolution.width()
&& maybeFlippedHeight == surfaceResolution.height())
return supportedPreviewSize;
final float aspectRatio = (float) maybeFlippedWidth
/ (float) maybeFlippedHeight;
final float newDiff = Math.abs(aspectRatio - screenAspectRatio);
if (newDiff < diff) {
bestSize = supportedPreviewSize;
diff = newDiff;
}
}
if (bestSize != null)
return bestSize;
else
return parameters.getPreviewSize();
}
@SuppressLint("InlinedApi")
private static void setDesiredCameraParameters(final Camera camera,
final Camera.Size cameraResolution,
final boolean continuousAutoFocus) {
final Camera.Parameters parameters = camera.getParameters();
if (parameters == null)
return;
final List<String> supportedFocusModes = parameters
.getSupportedFocusModes();
final String focusMode = continuousAutoFocus ? findValue(
supportedFocusModes,
Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE,
Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO,
Camera.Parameters.FOCUS_MODE_AUTO,
Camera.Parameters.FOCUS_MODE_MACRO) : findValue(
supportedFocusModes, Camera.Parameters.FOCUS_MODE_AUTO,
Camera.Parameters.FOCUS_MODE_MACRO);
if (focusMode != null)
parameters.setFocusMode(focusMode);
parameters.setPreviewSize(cameraResolution.width,
cameraResolution.height);
camera.setParameters(parameters);
}
public void requestPreviewFrame(final PreviewCallback callback) {
camera.setOneShotPreviewCallback(callback);
}
public PlanarYUVLuminanceSource buildLuminanceSource(final byte[] data) {
return new PlanarYUVLuminanceSource(data, cameraResolution.width,
cameraResolution.height, framePreview.top, framePreview.left,
framePreview.height(), framePreview.width(), false);
}
public void setTorch(final boolean enabled) {
if (enabled != getTorchEnabled(camera))
setTorchEnabled(camera, enabled);
}
public boolean torchEnabled() {
return getTorchEnabled(camera);
}
private static boolean getTorchEnabled(final Camera camera) {
final Camera.Parameters parameters = camera.getParameters();
if (parameters != null) {
final String flashMode = camera.getParameters().getFlashMode();
return flashMode != null
&& (Camera.Parameters.FLASH_MODE_ON.equals(flashMode) || Camera.Parameters.FLASH_MODE_TORCH
.equals(flashMode));
}
return false;
}
private static void setTorchEnabled(final Camera camera,
final boolean enabled) {
final Camera.Parameters parameters = camera.getParameters();
final List<String> supportedFlashModes = parameters
.getSupportedFlashModes();
if (supportedFlashModes != null) {
final String flashMode;
if (enabled)
flashMode = findValue(supportedFlashModes,
Camera.Parameters.FLASH_MODE_TORCH,
Camera.Parameters.FLASH_MODE_ON);
else
flashMode = findValue(supportedFlashModes,
Camera.Parameters.FLASH_MODE_OFF);
if (flashMode != null) {
camera.cancelAutoFocus(); // autofocus can cause conflict
parameters.setFlashMode(flashMode);
camera.setParameters(parameters);
}
}
}
private static String findValue(final Collection<String> values,
final String... valuesToFind) {
for (final String valueToFind : valuesToFind)
if (values.contains(valueToFind))
return valueToFind;
return null;
}
}
|
check null for camera
|
bither-android/src/net/bither/camera/CameraManager.java
|
check null for camera
|
|
Java
|
apache-2.0
|
630e2d08c2d4d6e09b3f2e5a01501ebcb1c0abc4
| 0
|
walles/exactype
|
/*
* Copyright 2015 Johan Walles <johan.walles@gmail.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.
*/
package com.gmail.walles.johan.exactype;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.inputmethodservice.InputMethodService;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.widget.PopupWindow;
import com.gmail.walles.johan.exactype.stats.StatsTracker;
import com.gmail.walles.johan.exactype.util.LoggingUtils;
import com.gmail.walles.johan.exactype.util.Timer;
import com.gmail.walles.johan.exactype.util.VibrationUtils;
import java.util.HashMap;
import java.util.Map;
import androidx.annotation.Nullable;
import timber.log.Timber;
public class Exactype
extends InputMethodService
implements SharedPreferences.OnSharedPreferenceChangeListener
{
private static final String PERF_EVENT = "Perf";
private int vibrate_duration_ms = SettingsActivity.DEFAULT_VIBRATE_DURATION_MS;
/**
* While doing word-by-word deletion, how far back should we look when attempting to find the
* previous word?
*/
private static final int DELETE_LOOKBACK = 22;
private static final String[] UNSHIFTED = new String[] {
"qwertyuiopå",
"asdfghjklöä",
"zxcvbnm" // ⇧ = SHIFT, ⌫ = Backspace
};
private static final String[] SHIFTED = new String[] {
"QWERTYUIOPÅ",
"ASDFGHJKLÖÄ",
"ZXCVBNM" // ⇧ = SHIFT, ⌫ = Backspace
};
// Default protection for testing purposes
static final String[] NUMERIC = new String[] {
"1234567890",
"@&/:;()-+$",
"'\"*%#?!,."
};
private final Map<Character, String> popupKeysForKey;
private PopupKeyboardView popupKeyboardView;
private PopupWindow popupKeyboardWindow;
// Protected for testing purposes, should otherwise be private
protected FeedbackWindow feedbackWindow;
private final ExactypeMode mode;
private ExactypeView view;
private float popupX0;
private float popupY0;
@Nullable
private Vibrator vibrator;
private ExactypeExecutor inputConnectionExecutor;
private StatsTracker statsTracker;
// We override this method only to add the @Nullable annotation and get the corresponding
// warnings
@Override
@Nullable
public InputConnection getCurrentInputConnection() {
return super.getCurrentInputConnection();
}
@Override
public void onCreate() {
LoggingUtils.setUpLogging();
super.onCreate();
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.registerOnSharedPreferenceChangeListener(this);
vibrate_duration_ms =
preferences.getInt(SettingsActivity.VIBRATE_DURATION_MS_KEY,
SettingsActivity.DEFAULT_VIBRATE_DURATION_MS);
inputConnectionExecutor = new ExactypeExecutor();
statsTracker = new StatsTracker(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
if (SettingsActivity.VIBRATE_DURATION_MS_KEY.equals(key)) {
vibrate_duration_ms =
preferences.getInt(SettingsActivity.VIBRATE_DURATION_MS_KEY,
SettingsActivity.DEFAULT_VIBRATE_DURATION_MS);
}
}
public Exactype() {
popupKeysForKey = new HashMap<>();
// FIXME: Maybe we should implicitly have the base key at the end of each of these lists?
// Since we already have å and ä on the primary keyboard, they shouldn't be part of the
// popup keys for a
popupKeysForKey.put('a', "@áàa");
popupKeysForKey.put('A', "@ÁÀA");
popupKeysForKey.put('e', "éèëe");
popupKeysForKey.put('E', "ÉÈË€E");
mode = new ExactypeMode(UNSHIFTED, SHIFTED, NUMERIC);
}
@Override
public View onCreateInputView() {
popupKeyboardView = new PopupKeyboardView(this);
popupKeyboardWindow = new PopupWindow(popupKeyboardView);
view = new ExactypeView(this);
mode.addModeChangeListener(view);
feedbackWindow = new FeedbackWindow(this, view);
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
return view;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// Make sure we don't leave stray popup windows behind that are impossible to get rid of
if (feedbackWindow != null) {
feedbackWindow.close();
}
if (popupKeyboardWindow != null) {
popupKeyboardWindow.dismiss();
}
super.onConfigurationChanged(newConfig);
}
@Override
public void onStartInputView(EditorInfo editorInfo, boolean restarting) {
if (restarting) {
return;
}
// The initialCapsMode docs say that you should generally just take a non-zero value to mean
// "start out in caps mode":
// http://developer.android.com/reference/android/view/inputmethod/EditorInfo.html#initialCapsMode
mode.setShifted(editorInfo.initialCapsMode != 0);
if ((editorInfo.inputType & InputType.TYPE_MASK_CLASS) != InputType.TYPE_CLASS_TEXT) {
mode.setNumeric();
}
}
public void onLongPress(float x, float y) {
feedbackWindow.show(x, y);
mode.register(ExactypeMode.Event.LONG_PRESS);
}
protected void enqueue(Runnable inputConnectionAction) {
inputConnectionExecutor.execute(inputConnectionAction);
}
public void onKeyTapped(final char tappedKey) {
popupKeyboardWindow.dismiss();
enqueue(() -> {
Timer timer = new Timer();
final InputConnection inputConnection = getCurrentInputConnection();
if (inputConnection == null) {
return;
}
statsTracker.countCharacter(tappedKey);
inputConnection.commitText(Character.toString(tappedKey), 1);
LoggingUtils.logCustom(new LoggingUtils.CustomEvent(PERF_EVENT).putCustomAttribute(
"Commit char ms", timer.getMs()));
});
mode.register(ExactypeMode.Event.INSERT_CHAR);
}
public void onDeleteTapped() {
enqueue(() -> {
Timer timer = new Timer();
final InputConnection inputConnection = getCurrentInputConnection();
if (inputConnection == null) {
return;
}
timer.addLeg("get selection");
CharSequence selection = inputConnection.getSelectedText(0);
if (TextUtils.isEmpty(selection)) {
// Nothing selected, just backspace
timer.addLeg("backspace");
// FIXME: Add this to the stats tracker?
inputConnection.deleteSurroundingText(1, 0);
} else {
// Delete selection
timer.addLeg("delete selection");
// FIXME: Add this to the stats tracker?
inputConnection.commitText("", 1);
}
LoggingUtils.logCustom(new LoggingUtils.CustomEvent(PERF_EVENT).putCustomAttribute(
"Delete char ms", timer.getMs()));
});
}
/**
* To remove the last word, how many chars would that be?
* @param before Text before cursor
* @return How many characters we should remove
*/
private int countCharsToDelete(CharSequence before) {
int index = before.length() - 1;
// Count non-alphanumeric characters from the end
while (index >=0 && !Character.isLetterOrDigit(before.charAt(index))) {
index--;
}
// Count the number of alphanumeric characters preceding those
while (index >=0 && Character.isLetterOrDigit(before.charAt(index))) {
index--;
}
return before.length() - 1 - index;
}
protected boolean queueIsEmpty() {
return inputConnectionExecutor.isEmpty();
}
public void onDeleteHeld() {
feedbackWindow.close();
if (!queueIsEmpty()) {
// Don't enqueue new things repeatedly if there are already outstanding entries. This is
// best practices from HyperKey on my DOS machine ages ago. I still miss it.
return;
}
enqueue(() -> {
Timer timer = new Timer();
final InputConnection inputConnection = getCurrentInputConnection();
if (inputConnection == null) {
return;
}
timer.addLeg("get selection");
CharSequence selection = inputConnection.getSelectedText(0);
if (selection == null || selection.length() == 0) {
// Nothing selected, delete words
timer.addLeg("get preceding text");
CharSequence before = inputConnection.getTextBeforeCursor(DELETE_LOOKBACK, 0);
timer.addLeg("analyze text");
int to_delete = countCharsToDelete(before);
timer.addLeg("delete word");
inputConnection.deleteSurroundingText(to_delete, 0);
LoggingUtils.logCustom(new LoggingUtils.CustomEvent(PERF_EVENT).putCustomAttribute(
"Delete word ms", timer.getMs()));
} else {
// Delete selection
timer.addLeg("delete selection");
inputConnection.commitText("", 1);
LoggingUtils.logCustom(new LoggingUtils.CustomEvent(PERF_EVENT).putCustomAttribute(
"Delete selection ms", timer.getMs()));
}
});
VibrationUtils.vibrate(vibrator, vibrate_duration_ms);
}
public void onKeyboardModeSwitchRequested() {
mode.register(ExactypeMode.Event.NEXT_MODE);
}
public void onActionTapped() {
final EditorInfo editorInfo = getCurrentInputEditorInfo();
enqueue(() -> {
Timer timer = new Timer();
final InputConnection inputConnection = getCurrentInputConnection();
if (inputConnection == null) {
return;
}
if ((editorInfo.imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
inputConnection.commitText("\n", 1);
// FIXME: Add this to the stats tracker?
LoggingUtils.logCustom(new LoggingUtils.CustomEvent(PERF_EVENT).putCustomAttribute(
"Commit newline ms", timer.getMs()));
mode.register(ExactypeMode.Event.INSERT_CHAR);
return;
}
inputConnection.
performEditorAction(editorInfo.imeOptions & EditorInfo.IME_MASK_ACTION);
LoggingUtils.logCustom(new LoggingUtils.CustomEvent(PERF_EVENT).putCustomAttribute(
"Perform editor action ms", timer.getMs()));
});
}
public void onRequestPopupKeyboard(char baseKey, float x, float y) {
String popupKeys = popupKeysForKey.get(baseKey);
if (popupKeys == null) {
// No popup keys available for this keypress
return;
}
popupKeyboardView.setKeys(popupKeys);
popupKeyboardView.setTextSize(view.getTextSize());
popupKeyboardWindow.setWidth(popupKeyboardView.getMeasuredWidth());
popupKeyboardWindow.setHeight(popupKeyboardView.getMeasuredHeight());
// Without this the popup window will be constrained to the inside of the keyboard view
popupKeyboardWindow.setClippingEnabled(false);
Timber.d("Popup keyboard window size set to %dx%d",
popupKeyboardView.getWidth(),
popupKeyboardView.getHeight());
popupX0 = x;
if (popupX0 + popupKeyboardWindow.getWidth() > view.getWidth()) {
// Make sure the popup keyboard is left enough to not extend outside of the screen
popupX0 = view.getWidth() - popupKeyboardWindow.getWidth();
}
popupY0 = y;
// Note that the gravity here decides *where the popup window anchors inside its parent*.
//
// This means that if we want the popup window anywhere but to the bottom right of where
// the user touched, we'll need do the math ourselves.
popupKeyboardWindow.showAtLocation(view, Gravity.NO_GRAVITY, (int)popupX0, (int)popupY0);
}
public boolean isPopupKeyboardShowing() {
return popupKeyboardWindow.isShowing();
}
@Override
public boolean onEvaluateFullscreenMode() {
// Johan finds the full screen mode ugly and confusing
return false;
}
public void onPopupKeyboardTapped(float x, float y) {
// FIXME: Are we even on the popup keyboard? Abort otherwise.
float popupX = x - popupX0;
float popupY = y - popupY0;
onKeyTapped(popupKeyboardView.getClosestKey(popupX, popupY));
}
public void onTouchStart() {
VibrationUtils.vibrate(vibrator, vibrate_duration_ms);
}
public void onTouchMove(float x, float y) {
feedbackWindow.update(x, y);
}
public void onTouchEnd() {
feedbackWindow.close();
}
@Override
public void onWindowHidden() {
feedbackWindow.close();
}
}
|
app/src/main/java/com/gmail/walles/johan/exactype/Exactype.java
|
/*
* Copyright 2015 Johan Walles <johan.walles@gmail.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.
*/
package com.gmail.walles.johan.exactype;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.inputmethodservice.InputMethodService;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import androidx.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.widget.PopupWindow;
import com.gmail.walles.johan.exactype.util.LoggingUtils;
import com.gmail.walles.johan.exactype.util.Timer;
import com.gmail.walles.johan.exactype.util.VibrationUtils;
import java.util.HashMap;
import java.util.Map;
import timber.log.Timber;
public class Exactype
extends InputMethodService
implements SharedPreferences.OnSharedPreferenceChangeListener
{
private static final String PERF_EVENT = "Perf";
private int vibrate_duration_ms = SettingsActivity.DEFAULT_VIBRATE_DURATION_MS;
/**
* While doing word-by-word deletion, how far back should we look when attempting to find the
* previous word?
*/
private static final int DELETE_LOOKBACK = 22;
private static final String[] UNSHIFTED = new String[] {
"qwertyuiopå",
"asdfghjklöä",
"zxcvbnm" // ⇧ = SHIFT, ⌫ = Backspace
};
private static final String[] SHIFTED = new String[] {
"QWERTYUIOPÅ",
"ASDFGHJKLÖÄ",
"ZXCVBNM" // ⇧ = SHIFT, ⌫ = Backspace
};
// Default protection for testing purposes
static final String[] NUMERIC = new String[] {
"1234567890",
"@&/:;()-+$",
"'\"*%#?!,."
};
private final Map<Character, String> popupKeysForKey;
private PopupKeyboardView popupKeyboardView;
private PopupWindow popupKeyboardWindow;
// Protected for testing purposes, should otherwise be private
protected FeedbackWindow feedbackWindow;
private final ExactypeMode mode;
private ExactypeView view;
private float popupX0;
private float popupY0;
@Nullable
private Vibrator vibrator;
private ExactypeExecutor inputConnectionExecutor;
// We override this method only to add the @Nullable annotation and get the corresponding
// warnings
@Override
@Nullable
public InputConnection getCurrentInputConnection() {
return super.getCurrentInputConnection();
}
@Override
public void onCreate() {
LoggingUtils.setUpLogging();
super.onCreate();
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.registerOnSharedPreferenceChangeListener(this);
vibrate_duration_ms =
preferences.getInt(SettingsActivity.VIBRATE_DURATION_MS_KEY,
SettingsActivity.DEFAULT_VIBRATE_DURATION_MS);
inputConnectionExecutor = new ExactypeExecutor();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
if (SettingsActivity.VIBRATE_DURATION_MS_KEY.equals(key)) {
vibrate_duration_ms =
preferences.getInt(SettingsActivity.VIBRATE_DURATION_MS_KEY,
SettingsActivity.DEFAULT_VIBRATE_DURATION_MS);
}
}
public Exactype() {
popupKeysForKey = new HashMap<>();
// FIXME: Maybe we should implicitly have the base key at the end of each of these lists?
// Since we already have å and ä on the primary keyboard, they shouldn't be part of the
// popup keys for a
popupKeysForKey.put('a', "@áàa");
popupKeysForKey.put('A', "@ÁÀA");
popupKeysForKey.put('e', "éèëe");
popupKeysForKey.put('E', "ÉÈË€E");
mode = new ExactypeMode(UNSHIFTED, SHIFTED, NUMERIC);
}
@Override
public View onCreateInputView() {
popupKeyboardView = new PopupKeyboardView(this);
popupKeyboardWindow = new PopupWindow(popupKeyboardView);
view = new ExactypeView(this);
mode.addModeChangeListener(view);
feedbackWindow = new FeedbackWindow(this, view);
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
return view;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// Make sure we don't leave stray popup windows behind that are impossible to get rid of
if (feedbackWindow != null) {
feedbackWindow.close();
}
if (popupKeyboardWindow != null) {
popupKeyboardWindow.dismiss();
}
super.onConfigurationChanged(newConfig);
}
@Override
public void onStartInputView(EditorInfo editorInfo, boolean restarting) {
if (restarting) {
return;
}
// The initialCapsMode docs say that you should generally just take a non-zero value to mean
// "start out in caps mode":
// http://developer.android.com/reference/android/view/inputmethod/EditorInfo.html#initialCapsMode
mode.setShifted(editorInfo.initialCapsMode != 0);
if ((editorInfo.inputType & InputType.TYPE_MASK_CLASS) != InputType.TYPE_CLASS_TEXT) {
mode.setNumeric();
}
}
public void onLongPress(float x, float y) {
feedbackWindow.show(x, y);
mode.register(ExactypeMode.Event.LONG_PRESS);
}
protected void enqueue(Runnable inputConnectionAction) {
inputConnectionExecutor.execute(inputConnectionAction);
}
public void onKeyTapped(final char tappedKey) {
popupKeyboardWindow.dismiss();
enqueue(() -> {
Timer timer = new Timer();
final InputConnection inputConnection = getCurrentInputConnection();
if (inputConnection == null) {
return;
}
inputConnection.commitText(Character.toString(tappedKey), 1);
LoggingUtils.logCustom(new LoggingUtils.CustomEvent(PERF_EVENT).putCustomAttribute(
"Commit char ms", timer.getMs()));
});
mode.register(ExactypeMode.Event.INSERT_CHAR);
}
public void onDeleteTapped() {
enqueue(() -> {
Timer timer = new Timer();
final InputConnection inputConnection = getCurrentInputConnection();
if (inputConnection == null) {
return;
}
timer.addLeg("get selection");
CharSequence selection = inputConnection.getSelectedText(0);
if (TextUtils.isEmpty(selection)) {
// Nothing selected, just backspace
timer.addLeg("backspace");
inputConnection.deleteSurroundingText(1, 0);
} else {
// Delete selection
timer.addLeg("delete selection");
inputConnection.commitText("", 1);
}
LoggingUtils.logCustom(new LoggingUtils.CustomEvent(PERF_EVENT).putCustomAttribute(
"Delete char ms", timer.getMs()));
});
}
/**
* To remove the last word, how many chars would that be?
* @param before Text before cursor
* @return How many characters we should remove
*/
private int countCharsToDelete(CharSequence before) {
int index = before.length() - 1;
// Count non-alphanumeric characters from the end
while (index >=0 && !Character.isLetterOrDigit(before.charAt(index))) {
index--;
}
// Count the number of alphanumeric characters preceding those
while (index >=0 && Character.isLetterOrDigit(before.charAt(index))) {
index--;
}
return before.length() - 1 - index;
}
protected boolean queueIsEmpty() {
return inputConnectionExecutor.isEmpty();
}
public void onDeleteHeld() {
feedbackWindow.close();
if (!queueIsEmpty()) {
// Don't enqueue new things repeatedly if there are already outstanding entries. This is
// best practices from HyperKey on my DOS machine ages ago. I still miss it.
return;
}
enqueue(() -> {
Timer timer = new Timer();
final InputConnection inputConnection = getCurrentInputConnection();
if (inputConnection == null) {
return;
}
timer.addLeg("get selection");
CharSequence selection = inputConnection.getSelectedText(0);
if (selection == null || selection.length() == 0) {
// Nothing selected, delete words
timer.addLeg("get preceding text");
CharSequence before = inputConnection.getTextBeforeCursor(DELETE_LOOKBACK, 0);
timer.addLeg("analyze text");
int to_delete = countCharsToDelete(before);
timer.addLeg("delete word");
inputConnection.deleteSurroundingText(to_delete, 0);
LoggingUtils.logCustom(new LoggingUtils.CustomEvent(PERF_EVENT).putCustomAttribute(
"Delete word ms", timer.getMs()));
} else {
// Delete selection
timer.addLeg("delete selection");
inputConnection.commitText("", 1);
LoggingUtils.logCustom(new LoggingUtils.CustomEvent(PERF_EVENT).putCustomAttribute(
"Delete selection ms", timer.getMs()));
}
});
VibrationUtils.vibrate(vibrator, vibrate_duration_ms);
}
public void onKeyboardModeSwitchRequested() {
mode.register(ExactypeMode.Event.NEXT_MODE);
}
public void onActionTapped() {
final EditorInfo editorInfo = getCurrentInputEditorInfo();
enqueue(() -> {
Timer timer = new Timer();
final InputConnection inputConnection = getCurrentInputConnection();
if (inputConnection == null) {
return;
}
if ((editorInfo.imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
inputConnection.commitText("\n", 1);
LoggingUtils.logCustom(new LoggingUtils.CustomEvent(PERF_EVENT).putCustomAttribute(
"Commit newline ms", timer.getMs()));
mode.register(ExactypeMode.Event.INSERT_CHAR);
return;
}
inputConnection.
performEditorAction(editorInfo.imeOptions & EditorInfo.IME_MASK_ACTION);
LoggingUtils.logCustom(new LoggingUtils.CustomEvent(PERF_EVENT).putCustomAttribute(
"Perform editor action ms", timer.getMs()));
});
}
public void onRequestPopupKeyboard(char baseKey, float x, float y) {
String popupKeys = popupKeysForKey.get(baseKey);
if (popupKeys == null) {
// No popup keys available for this keypress
return;
}
popupKeyboardView.setKeys(popupKeys);
popupKeyboardView.setTextSize(view.getTextSize());
popupKeyboardWindow.setWidth(popupKeyboardView.getMeasuredWidth());
popupKeyboardWindow.setHeight(popupKeyboardView.getMeasuredHeight());
// Without this the popup window will be constrained to the inside of the keyboard view
popupKeyboardWindow.setClippingEnabled(false);
Timber.d("Popup keyboard window size set to %dx%d",
popupKeyboardView.getWidth(),
popupKeyboardView.getHeight());
popupX0 = x;
if (popupX0 + popupKeyboardWindow.getWidth() > view.getWidth()) {
// Make sure the popup keyboard is left enough to not extend outside of the screen
popupX0 = view.getWidth() - popupKeyboardWindow.getWidth();
}
popupY0 = y;
// Note that the gravity here decides *where the popup window anchors inside its parent*.
//
// This means that if we want the popup window anywhere but to the bottom right of where
// the user touched, we'll need do the math ourselves.
popupKeyboardWindow.showAtLocation(view, Gravity.NO_GRAVITY, (int)popupX0, (int)popupY0);
}
public boolean isPopupKeyboardShowing() {
return popupKeyboardWindow.isShowing();
}
@Override
public boolean onEvaluateFullscreenMode() {
// Johan finds the full screen mode ugly and confusing
return false;
}
public void onPopupKeyboardTapped(float x, float y) {
// FIXME: Are we even on the popup keyboard? Abort otherwise.
float popupX = x - popupX0;
float popupY = y - popupY0;
onKeyTapped(popupKeyboardView.getClosestKey(popupX, popupY));
}
public void onTouchStart() {
VibrationUtils.vibrate(vibrator, vibrate_duration_ms);
}
public void onTouchMove(float x, float y) {
feedbackWindow.update(x, y);
}
public void onTouchEnd() {
feedbackWindow.close();
}
@Override
public void onWindowHidden() {
feedbackWindow.close();
}
}
|
Add initial stats counting code
|
app/src/main/java/com/gmail/walles/johan/exactype/Exactype.java
|
Add initial stats counting code
|
|
Java
|
bsd-2-clause
|
442ca812b95d835ff1f5b6bac3054cb837b004d0
| 0
|
mudalov/safe-service
|
package com.mudalov.safe.config;
import com.mudalov.safe.cache.ehcache.EhCacheFactory;
import com.mudalov.safe.util.Pair;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
/**
* User: mudalov
* Date: 24/01/15
* Time: 21:10
*/
public class Configuration {
public static final String DEFAULT_CONFIG_FILE = "safe-service";
private static Configuration rootConfig = load();
/**
* Supported configuration properties and their default values
*/
private static class Props {
final static Pair<String, Integer> ThreadsPerGroup = new Pair<String, Integer>("threadsPerGroup", 5);
final static Pair<String, Integer> MaxWorkQueueSize = new Pair<String, Integer>("maxWorkQueueSize", -1);
final static Pair<String, String> CacheFactory = new Pair<String, String>("cacheFactory", EhCacheFactory.class.getName());
final static Pair<String, String> CacheConfigLocation = new Pair<String, String>("cacheConfigLocation", "/safe-service-ehcache.xml");
final static Pair<String, Integer> TimeOut = new Pair<String, Integer>("timeOut", 1000);
}
private Configuration(){
this(null, null);
}
private final Config baseConfig;
private final String basePath;
private Configuration(Config baseConfig) {
this(baseConfig, null);
}
private Configuration(Config baseConfig, String basePath) {
this.baseConfig = baseConfig;
this.basePath = basePath != null ? basePath + "." : null;
}
public static Configuration root() {
return rootConfig;
}
public String getCacheFactory() {
return getValue(Props.CacheFactory);
}
public String getCacheConfigLocation() {
return getValue(Props.CacheConfigLocation);
}
public Integer getThreadsPerGroup() {
return getValue(Props.ThreadsPerGroup);
}
public Configuration forGroup(String groupName) {
return new Configuration(this.baseConfig, groupName);
}
private <T> T getValue(Pair<String, T> prop) {
String key = prop.getFirst();
if (basePath != null
&& this.baseConfig.hasPath(basePath + key)) {
return (T)this.baseConfig.getAnyRef(basePath + key);
} else {
return this.baseConfig.hasPath(key)
? (T)this.baseConfig.getAnyRef(key) : prop.getSecond();
}
}
public Integer getMaxWorkQueueSize() {
return getValue(Props.MaxWorkQueueSize);
}
public Integer getTimeOut() {
return getValue(Props.TimeOut);
}
public static Configuration load() {
return load(DEFAULT_CONFIG_FILE);
}
private static Configuration load(String baseName) {
Config baseConfig = ConfigFactory.load(baseName);
Configuration configuration = new Configuration(baseConfig);
return configuration;
}
}
|
src/main/java/com/mudalov/safe/config/Configuration.java
|
package com.mudalov.safe.config;
import com.mudalov.safe.cache.ehcache.EhCacheFactory;
import com.mudalov.safe.util.Pair;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
/**
* User: mudalov
* Date: 24/01/15
* Time: 21:10
*/
public class Configuration {
public static final String DefaultConfigFile = "safe-service";
private static Configuration rootConfig = load();
/**
* Supported configuration properties and their default values
*/
private static class Props {
final static Pair<String, Integer> ThreadsPerGroup = new Pair<String, Integer>("threadsPerGroup", 5);
final static Pair<String, Integer> MaxWorkQueueSize = new Pair<String, Integer>("maxWorkQueueSize", -1);
final static Pair<String, String> CacheFactory = new Pair<String, String>("cacheFactory", EhCacheFactory.class.getName());
final static Pair<String, String> CacheConfigLocation = new Pair<String, String>("cacheConfigLocation", "/safe-service-ehcache.xml");
final static Pair<String, Integer> TimeOut = new Pair<String, Integer>("timeOut", 1000);
}
private Configuration(){
this(null, null);
}
private final Config baseConfig;
private final String basePath;
private Configuration(Config baseConfig) {
this(baseConfig, null);
}
private Configuration(Config baseConfig, String basePath) {
this.baseConfig = baseConfig;
this.basePath = basePath != null ? basePath + "." : null;
}
public static Configuration root() {
return rootConfig;
}
public String getCacheFactory() {
return getValue(Props.CacheFactory);
}
public String getCacheConfigLocation() {
return getValue(Props.CacheConfigLocation);
}
public Integer getThreadsPerGroup() {
return getValue(Props.ThreadsPerGroup);
}
public Configuration forGroup(String groupName) {
return new Configuration(this.baseConfig, groupName);
}
private <T> T getValue(Pair<String, T> prop) {
String key = prop.getFirst();
if (basePath != null
&& this.baseConfig.hasPath(basePath + key)) {
return (T)this.baseConfig.getAnyRef(basePath + key);
} else {
return this.baseConfig.hasPath(key)
? (T)this.baseConfig.getAnyRef(key) : prop.getSecond();
}
}
public Integer getMaxWorkQueueSize() {
return getValue(Props.MaxWorkQueueSize);
}
public Integer getTimeOut() {
return getValue(Props.TimeOut);
}
public static Configuration load() {
return load(DefaultConfigFile);
}
private static Configuration load(String baseName) {
Config baseConfig = ConfigFactory.load(baseName);
Configuration configuration = new Configuration(baseConfig);
return configuration;
}
}
|
Rename default config
|
src/main/java/com/mudalov/safe/config/Configuration.java
|
Rename default config
|
|
Java
|
bsd-3-clause
|
86e4e9c56c3cd6467dd34307df3f522e280ef89a
| 0
|
Kalbintion/Kdkbot,Kalbintion/Kdkbot,Kalbintion/Kdkbot
|
package kdkbot.channel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import kdkbot.*;
import kdkbot.commands.*;
import kdkbot.commands.filters.Filter;
import kdkbot.commands.filters.Filters;
import kdkbot.filemanager.Config;
public class Channel {
public Commands commands;
public String channel;
// private Economy economy;
public ArrayList<Forwarder> forwarders = new ArrayList<Forwarder>();
public String commandPrefix = "|";
public Filters filters;
public Stats stats;
// Path & Config locations (set by Channel() init)
public String baseConfigLocation;
public Config cfgPerms;
public Config cfgChan;
public Config cfgTokens;
public HashMap<String, Integer> senderRanks = new HashMap<String, Integer>();
// Other Vars
public HashMap<String, Integer> filterBypass = new HashMap<String, Integer>();
public boolean commandProcessing = true;
public boolean logChat = true;
/**
* Constructs a new channel instance with no references
*/
public Channel() {
this(null, null);
}
/**
* Constructs a new channel instance
* @param instance the instance of the bot to be assigned for this channel
* @param channel the channel name in which to join and reign control over
*/
public Channel(Kdkbot instance, String channel) {
try {
this.channel = channel;
this.baseConfigLocation = "./cfg/" + channel + "/";
cfgChan = new Config(this.baseConfigLocation + "channel.cfg");
cfgChan.verifyExists();
cfgChan.loadConfigContents();
cfgTokens = new Config(this.baseConfigLocation + "tokens.cfg");
cfgTokens.verifyExists();
cfgTokens.loadConfigContents();
// Command Processing?
if(cfgChan.getSetting("commandProcessing") == null) {
cfgChan.setSetting("commandProcessing", Boolean.TRUE.toString());
}
this.commandProcessing = Boolean.parseBoolean(cfgChan.getSetting("commandProcessing"));
// Command Prefix?
if(cfgChan.getSetting("commandPrefix") == null) {
cfgChan.setSetting("commandPrefix", "|");
}
this.commandPrefix = cfgChan.getSetting("commandPrefix");
// Log Chat?
if(cfgChan.getSetting("logChat") == null) {
cfgChan.setSetting("logChat", "true");
}
this.logChat = Boolean.parseBoolean(cfgChan.getSetting("logChat"));
// Message Prefix?
if(cfgChan.getSetting("msgPrefix") == null) {
cfgChan.setSetting("msgPrefix", "");
}
// Mesage Suffix?
if(cfgChan.getSetting("msgSuffix") == null) {
cfgChan.setSetting("msgSuffix", "");
}
// Filters, Stats, etc
this.filters = new Filters(channel);
this.filters.loadFilters();
this.stats = new Stats(this);
this.stats.loadStats();
this.joinChannel();
instance.dbg.writeln(this, "Attempting to load config ranks.");
cfgPerms = new Config("./cfg/" + channel + "/perms.cfg");
this.loadSenderRanks();
this.commands = new Commands(channel, this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void joinChannel() {
Kdkbot.instance.joinChannel(this.channel);
}
public void leaveChannel() {
Kdkbot.instance.partChannel(this.channel);
}
public String getChannel() {
return this.channel;
}
public void leaveChannel(String reason) {
Kdkbot.instance.partChannel(this.channel, reason);
}
public void kickUser(String nick) {
Kdkbot.instance.kick(this.channel, nick);
}
public void kickUser(String nick, String reason) {
Kdkbot.instance.kick(this.channel, nick, reason);
}
public String getCommandPrefix() {
return this.commandPrefix;
}
public void setCommandPrefix(String commandPrefix) {
this.commandPrefix = commandPrefix;
}
public int getUserRank(String user) {
return this.senderRanks.get(user);
}
/**
* Gets a particular users rank for this channel.
* @param sender The sender to lookup
* @return An integer value representing the users rank for this channel.
*/
public int getSenderRank(String sender) {
if(this.senderRanks.containsKey(sender.toLowerCase())) {
return this.senderRanks.get(sender.toLowerCase());
} else {
return 0;
}
}
/**
* Gets all of this channels ranks
* @return An Array List of users and their ranks
*/
public ArrayList<String> getSenderRanks() {
ArrayList<String> strings = null;
try {
strings = (ArrayList<String>) cfgPerms.getConfigContents();
} catch(Exception e) {
e.printStackTrace();
}
return strings;
}
/**
* Sets a particular users rank for this channel
* @param target The users name to set a rank to
* @param rank The rank to set the target to
*/
public void setSenderRank(String target, int rank) {
senderRanks.put(target.toLowerCase(), rank);
this.saveSenderRanks(true);
}
/**
* Loads the channels ranks for users.
*/
public void loadSenderRanks() {
try {
List<String> strings = cfgPerms.getConfigContents();
Iterator<String> string = strings.iterator();
while(string.hasNext()) {
Kdkbot.instance.dbg.writeln(this, "Parsing next line of perm list.");
String[] args = string.next().split("=");
Kdkbot.instance.dbg.writeln(this, "Size of args is " + args.length + ". a value of 2 is expected.");
this.senderRanks.put(args[0], Integer.parseInt(args[1]));
}
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* Saves the channels ranks for users.
*/
public void saveSenderRanks() {
cfgPerms.saveSettings();
}
/**
*
* @param sendReferenceMap
*/
public void saveSenderRanks(boolean sendReferenceMap) {
cfgPerms.saveSettings(this.senderRanks);
}
public void sendMessage(String message) {
String msgPrefix = cfgChan.getSetting("msgPrefix");
String msgSuffix = cfgChan.getSetting("msgSuffix");
if(msgPrefix.length() > 0) { msgPrefix += " "; } // Append a space
if(msgSuffix.length() > 0) { msgSuffix = " " + msgSuffix; } // Prepend a space
Kdkbot.instance.sendMessage(channel, msgPrefix + message + msgSuffix);
}
public void sendRawMessage(String message) {
Kdkbot.instance.sendMessage(channel, message);
}
/**
*
* @param info
*/
public void messageHandler(MessageInfo info) {
// User Stats
stats.handleMessage(info);
// Begin filtering first before checking for command validity
ArrayList<Filter> fList = this.filters.getFilters();
Iterator<Filter> fIter = fList.iterator();
int filterIndex = 0;
while(fIter.hasNext()) {
Filter filter = fIter.next();
filterIndex++;
if(filter.contains(info.message)) {
if(filter.ignoresPermit == false && this.filterBypass.containsKey(info.sender)) {
if(filterBypass.get(info.sender).intValue() > 0) {
Kdkbot.instance.dbg.writeln(this, "Decreased " + info.sender + " permit bypass by 1");
filterBypass.put(info.sender, filterBypass.get(info.sender).intValue() - 1);
break;
}
}
switch(filter.action) {
case 1:
Kdkbot.instance.dbg.writeln(this, "Attempting to purge user due to filter");
Kdkbot.instance.log("Attempting to purge user " + info.sender + " due to filter #" + filterIndex);
Kdkbot.instance.sendMessage(info.channel, "/timeout " + info.sender + " 1");
break;
case 2:
Kdkbot.instance.dbg.writeln(this, "Attempting to timeout user due to filter");
Kdkbot.instance.log("Attempting to timeout user " + info.sender + " due to filter #" + filterIndex);
Kdkbot.instance.sendMessage(info.channel, "/timeout " + info.sender);
break;
case 3:
Kdkbot.instance.dbg.writeln(this, "Attempting to ban user due to filter");
Kdkbot.instance.log("Attempting to ban user " + info.sender + " due to filter #" + filterIndex);
Kdkbot.instance.sendMessage(info.channel, "/ban " + info.sender);
break;
case 4:
Kdkbot.instance.dbg.writeln(this, "Attempting to respond to user due to filter");
Kdkbot.instance.log("Attempting to respond to user " + info.sender + " due to filter #" + filterIndex);
Kdkbot.instance.sendChanMessage(info.channel, MessageParser.parseMessage(filter.actionInfo, info));
break;
}
}
}
// Do we have any message forwarders
if(forwarders != null && forwarders.size() > 0) {
// We do! Lets check that they're validated forwarders
Iterator<Forwarder> fwdIter = forwarders.iterator();
while(fwdIter.hasNext()) {
Forwarder fwder = fwdIter.next();
if(fwder.isAuthorized()) {
Kdkbot.instance.getChannel(fwder.getChannel()).sendMessage(fwder.formatMessage(info));
}
}
}
// ORDER IMPORTANT HERE: Channel starting giveaway through the command caused this to add the person starting the giveaway to add themselves to it automatically
// Do we have a giveaway active? If so, does the message contain the keyword?
if(this.commands.giveaway.hasStarted() && info.message.toLowerCase().contains(this.commands.giveaway.getTriggerWord().toLowerCase())) {
if(!this.commands.giveaway.hasEntry(info.sender)) {
this.commands.giveaway.addEntry(info.sender);
}
}
// Send the message off to the channels command processor
if(info.message.startsWith(this.commandPrefix)){
this.commands.commandHandler(info);
}
}
public void extraHandler(MessageInfo info) {
// User Stats
stats.handleMessage(info);
}
/**
* Authorizes a forwarder for this channel
* @param fromChannel The channel to accept the request from
*/
public void authorizeForwarder(String fromChannel) {
setForwarderAuthorization(fromChannel, true);
}
/**
* Denies a forwarder for this channel
* @param fromChannel The channel to deny the request from
*/
public void denyForwarder(String fromChannel) {
setForwarderAuthorization(fromChannel, false);
removeForwarder(fromChannel);
}
/**
* Sets authorization status for a forwarder based on the channel accepting or denying the forwarder
* @param fromChannel The channel to accept/deny the request from
* @param status The authorization status. True for accept, False for deny.
*/
private void setForwarderAuthorization(String fromChannel, boolean status) {
Iterator<Forwarder> fwdIter = this.forwarders.iterator();
while(fwdIter.hasNext()) {
Forwarder nxt = fwdIter.next();
if(nxt.getChannel().equalsIgnoreCase(fromChannel)) {
if(status) { nxt.authorize(); } else { nxt.unauthorize(); }
}
}
}
/**
* Removes a forwarder from this channel
* @param fromChannel The channel to remove the forwarder to
*/
public void removeForwarder(String fromChannel) {
Iterator<Forwarder> fwdIter = this.forwarders.iterator();
while(fwdIter.hasNext()) {
Forwarder nxt = fwdIter.next();
if(nxt.getChannel().equalsIgnoreCase(fromChannel)) {
fwdIter.remove();
}
}
}
/**
* Gets this channels access token if its available
* @return Twitch access token in unencrypted form
*/
public String getAccessToken() {
String token = cfgTokens.getSetting("accessToken");
if(token == null) {
sendMessage("This channel has not authorized kdkbot to access stream information!");
return "";
}
return cfgTokens.getSetting("accessToken");
}
/**
* Gets the channel owners user ID. If it does not exist, it will retrieve and store it before returning the value.
* @return The ID of the channel's owner.
*/
public String getUserID() {
String userID = cfgTokens.getSetting("userID");
if(userID == null || userID.equalsIgnoreCase("null")) {
userID = kdkbot.api.twitch.APIv5.getUserID(Kdkbot.instance.getClientID(), channel.replace("#", ""));
cfgTokens.setSetting("userID", userID);
}
return userID;
}
}
|
src/kdkbot/channel/Channel.java
|
package kdkbot.channel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import kdkbot.*;
import kdkbot.commands.*;
import kdkbot.commands.filters.Filter;
import kdkbot.commands.filters.Filters;
import kdkbot.filemanager.Config;
public class Channel {
public Commands commands;
public String channel;
// private Economy economy;
public ArrayList<Forwarder> forwarders = new ArrayList<Forwarder>();
public String commandPrefix = "|";
public Filters filters;
public Stats stats;
// Path & Config locations (set by Channel() init)
public String baseConfigLocation;
public Config cfgPerms;
public Config cfgChan;
public Config cfgTokens;
public HashMap<String, Integer> senderRanks = new HashMap<String, Integer>();
// Other Vars
public HashMap<String, Integer> filterBypass = new HashMap<String, Integer>();
public boolean commandProcessing = true;
public boolean logChat = true;
/**
* Constructs a new channel instance with no references
*/
public Channel() {
this(null, null);
}
/**
* Constructs a new channel instance
* @param instance the instance of the bot to be assigned for this channel
* @param channel the channel name in which to join and reign control over
*/
public Channel(Kdkbot instance, String channel) {
try {
this.channel = channel;
this.baseConfigLocation = "./cfg/" + channel + "/";
cfgChan = new Config(this.baseConfigLocation + "channel.cfg");
cfgChan.verifyExists();
cfgChan.loadConfigContents();
cfgTokens = new Config(this.baseConfigLocation + "tokens.cfg");
cfgTokens.verifyExists();
cfgTokens.loadConfigContents();
// Command Processing?
if(cfgChan.getSetting("commandProcessing") == null) {
cfgChan.setSetting("commandProcessing", Boolean.TRUE.toString());
}
this.commandProcessing = Boolean.parseBoolean(cfgChan.getSetting("commandProcessing"));
// Command Prefix?
if(cfgChan.getSetting("commandPrefix") == null) {
cfgChan.setSetting("commandPrefix", "|");
}
this.commandPrefix = cfgChan.getSetting("commandPrefix");
// Log Chat?
if(cfgChan.getSetting("logChat") == null) {
cfgChan.setSetting("logChat", "true");
}
this.logChat = Boolean.parseBoolean(cfgChan.getSetting("logChat"));
// Message Prefix?
if(cfgChan.getSetting("msgPrefix") == null) {
cfgChan.setSetting("msgPrefix", "");
}
// Mesage Suffix?
if(cfgChan.getSetting("msgSuffix") == null) {
cfgChan.setSetting("msgSuffix", "");
}
// Filters, Stats, etc
this.filters = new Filters(channel);
this.filters.loadFilters();
this.stats = new Stats(this);
this.stats.loadStats();
this.joinChannel();
instance.dbg.writeln(this, "Attempting to load config ranks.");
cfgPerms = new Config("./cfg/" + channel + "/perms.cfg");
this.loadSenderRanks();
this.commands = new Commands(channel, this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void joinChannel() {
Kdkbot.instance.joinChannel(this.channel);
}
public void leaveChannel() {
Kdkbot.instance.partChannel(this.channel);
}
public String getChannel() {
return this.channel;
}
public void leaveChannel(String reason) {
Kdkbot.instance.partChannel(this.channel, reason);
}
public void kickUser(String nick) {
Kdkbot.instance.kick(this.channel, nick);
}
public void kickUser(String nick, String reason) {
Kdkbot.instance.kick(this.channel, nick, reason);
}
public String getCommandPrefix() {
return this.commandPrefix;
}
public void setCommandPrefix(String commandPrefix) {
this.commandPrefix = commandPrefix;
}
public int getUserRank(String user) {
return this.senderRanks.get(user);
}
/**
* Gets a particular users rank for this channel.
* @param sender The sender to lookup
* @return An integer value representing the users rank for this channel.
*/
public int getSenderRank(String sender) {
if(this.senderRanks.containsKey(sender.toLowerCase())) {
return this.senderRanks.get(sender.toLowerCase());
} else {
return 0;
}
}
/**
* Gets all of this channels ranks
* @return An Array List of users and their ranks
*/
public ArrayList<String> getSenderRanks() {
ArrayList<String> strings = null;
try {
strings = (ArrayList<String>) cfgPerms.getConfigContents();
} catch(Exception e) {
e.printStackTrace();
}
return strings;
}
/**
* Sets a particular users rank for this channel
* @param target The users name to set a rank to
* @param rank The rank to set the target to
*/
public void setSenderRank(String target, int rank) {
senderRanks.put(target.toLowerCase(), rank);
this.saveSenderRanks(true);
}
/**
* Loads the channels ranks for users.
*/
public void loadSenderRanks() {
try {
List<String> strings = cfgPerms.getConfigContents();
Iterator<String> string = strings.iterator();
while(string.hasNext()) {
Kdkbot.instance.dbg.writeln(this, "Parsing next line of perm list.");
String[] args = string.next().split("=");
Kdkbot.instance.dbg.writeln(this, "Size of args is " + args.length + ". a value of 2 is expected.");
this.senderRanks.put(args[0], Integer.parseInt(args[1]));
}
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* Saves the channels ranks for users.
*/
public void saveSenderRanks() {
cfgPerms.saveSettings();
}
/**
*
* @param sendReferenceMap
*/
public void saveSenderRanks(boolean sendReferenceMap) {
cfgPerms.saveSettings(this.senderRanks);
}
public void sendMessage(String message) {
String msgPrefix = cfgChan.getSetting("msgPrefix");
String msgSuffix = cfgChan.getSetting("msgSuffix");
if(msgPrefix.length() > 0) { msgPrefix += " "; } // Append a space
if(msgSuffix.length() > 0) { msgSuffix = " " + msgSuffix; } // Prepend a space
Kdkbot.instance.sendMessage(channel, msgPrefix + message + msgSuffix);
}
public void sendRawMessage(String message) {
Kdkbot.instance.sendMessage(channel, message);
}
/**
*
* @param info
*/
public void messageHandler(MessageInfo info) {
// User Stats
stats.handleMessage(info);
// Begin filtering first before checking for command validity
ArrayList<Filter> fList = this.filters.getFilters();
Iterator<Filter> fIter = fList.iterator();
int filterIndex = 0;
while(fIter.hasNext()) {
Filter filter = fIter.next();
filterIndex++;
if(filter.contains(info.message)) {
if(filter.ignoresPermit == false && this.filterBypass.containsKey(info.sender)) {
if(filterBypass.get(info.sender).intValue() > 0) {
Kdkbot.instance.dbg.writeln(this, "Decreased " + info.sender + " permit bypass by 1");
filterBypass.put(info.sender, filterBypass.get(info.sender).intValue() - 1);
break;
}
}
switch(filter.action) {
case 1:
Kdkbot.instance.dbg.writeln(this, "Attempting to purge user due to filter");
Kdkbot.instance.log("Attempting to purge user " + info.sender + " due to filter #" + filterIndex);
Kdkbot.instance.sendMessage(info.channel, "/timeout " + info.sender + " 1");
break;
case 2:
Kdkbot.instance.dbg.writeln(this, "Attempting to timeout user due to filter");
Kdkbot.instance.log("Attempting to timeout user " + info.sender + " due to filter #" + filterIndex);
Kdkbot.instance.sendMessage(info.channel, "/timeout " + info.sender);
break;
case 3:
Kdkbot.instance.dbg.writeln(this, "Attempting to ban user due to filter");
Kdkbot.instance.log("Attempting to ban user " + info.sender + " due to filter #" + filterIndex);
Kdkbot.instance.sendMessage(info.channel, "/ban " + info.sender);
break;
case 4:
Kdkbot.instance.dbg.writeln(this, "Attempting to respond to user due to filter");
Kdkbot.instance.log("Attempting to respond to user " + info.sender + " due to filter #" + filterIndex);
Kdkbot.instance.sendMessage(info.channel, MessageParser.parseMessage(filter.actionInfo, info));
break;
}
}
}
// Do we have any message forwarders
if(forwarders != null && forwarders.size() > 0) {
// We do! Lets check that they're validated forwarders
Iterator<Forwarder> fwdIter = forwarders.iterator();
while(fwdIter.hasNext()) {
Forwarder fwder = fwdIter.next();
if(fwder.isAuthorized()) {
Kdkbot.instance.getChannel(fwder.getChannel()).sendMessage(fwder.formatMessage(info));
}
}
}
// ORDER IMPORTANT HERE: Channel starting giveaway through the command caused this to add the person starting the giveaway to add themselves to it automatically
// Do we have a giveaway active? If so, does the message contain the keyword?
if(this.commands.giveaway.hasStarted() && info.message.toLowerCase().contains(this.commands.giveaway.getTriggerWord().toLowerCase())) {
if(!this.commands.giveaway.hasEntry(info.sender)) {
this.commands.giveaway.addEntry(info.sender);
}
}
// Send the message off to the channels command processor
if(info.message.startsWith(this.commandPrefix)){
this.commands.commandHandler(info);
}
}
public void extraHandler(MessageInfo info) {
// User Stats
stats.handleMessage(info);
}
/**
* Authorizes a forwarder for this channel
* @param fromChannel The channel to accept the request from
*/
public void authorizeForwarder(String fromChannel) {
setForwarderAuthorization(fromChannel, true);
}
/**
* Denies a forwarder for this channel
* @param fromChannel The channel to deny the request from
*/
public void denyForwarder(String fromChannel) {
setForwarderAuthorization(fromChannel, false);
removeForwarder(fromChannel);
}
/**
* Sets authorization status for a forwarder based on the channel accepting or denying the forwarder
* @param fromChannel The channel to accept/deny the request from
* @param status The authorization status. True for accept, False for deny.
*/
private void setForwarderAuthorization(String fromChannel, boolean status) {
Iterator<Forwarder> fwdIter = this.forwarders.iterator();
while(fwdIter.hasNext()) {
Forwarder nxt = fwdIter.next();
if(nxt.getChannel().equalsIgnoreCase(fromChannel)) {
if(status) { nxt.authorize(); } else { nxt.unauthorize(); }
}
}
}
/**
* Removes a forwarder from this channel
* @param fromChannel The channel to remove the forwarder to
*/
public void removeForwarder(String fromChannel) {
Iterator<Forwarder> fwdIter = this.forwarders.iterator();
while(fwdIter.hasNext()) {
Forwarder nxt = fwdIter.next();
if(nxt.getChannel().equalsIgnoreCase(fromChannel)) {
fwdIter.remove();
}
}
}
/**
* Gets this channels access token if its available
* @return Twitch access token in unencrypted form
*/
public String getAccessToken() {
String token = cfgTokens.getSetting("accessToken");
if(token == null) {
sendMessage("This channel has not authorized kdkbot to access stream information!");
return "";
}
return cfgTokens.getSetting("accessToken");
}
/**
* Gets the channel owners user ID. If it does not exist, it will retrieve and store it before returning the value.
* @return The ID of the channel's owner.
*/
public String getUserID() {
String userID = cfgTokens.getSetting("userID");
if(userID == null || userID.equalsIgnoreCase("null")) {
userID = kdkbot.api.twitch.APIv5.getUserID(Kdkbot.instance.getClientID(), channel.replace("#", ""));
cfgTokens.setSetting("userID", userID);
}
return userID;
}
}
|
Filter msg responses now apply channel prefix and suffix.
|
src/kdkbot/channel/Channel.java
|
Filter msg responses now apply channel prefix and suffix.
|
|
Java
|
mit
|
322251bf6c29f04aa508fe46943a0407318afdbe
| 0
|
pram/data-analysis,pram/data-analysis
|
package com.naughtyzombie.dataanalysis.wordcount;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import java.io.IOException;
import java.util.StringTokenizer;
public class WordCount {
public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
@Override
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
@Override
public void reduce(Text key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: wordcount <in> <out>");
System.exit(2);
}
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(TokenizerMapper.class);
/**** Uncomment the following line to enable the Combiner ****/
//job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
|
src/main/java/com/naughtyzombie/dataanalysis/wordcount/WordCount.java
|
package com.naughtyzombie.dataanalysis.wordcount;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import java.io.IOException;
import java.util.StringTokenizer;
public class WordCount {
public static class TokenizerMapper
extends Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
public static class IntSumReducer
extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values,
Context context
) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: wordcount <in> <out>");
System.exit(2);
}
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(TokenizerMapper.class);
/**** Uncomment the following line to enable the Combiner ****/
//job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
|
formatting
|
src/main/java/com/naughtyzombie/dataanalysis/wordcount/WordCount.java
|
formatting
|
|
Java
|
mit
|
9c4b804aab2637cc48fa1102c189487763188005
| 0
|
wrapp/WebImage-Android,wrapp/WebImage-Android
|
package com.wrapp.android.webimage;
import android.graphics.drawable.Drawable;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class ImageLoader {
private static final int NUM_WORKERS = 2;
private static ImageLoader staticInstance;
private final Queue<ImageRequest> pendingRequests = new LinkedList<ImageRequest>();
private final Worker[] workerPool = new Worker[NUM_WORKERS];
private final ImageRequest[] runningRequests = new ImageRequest[NUM_WORKERS];
private static class Worker extends Thread {
private int index;
public Worker(int index) {
this.index = index;
}
@Override
public void run() {
final Queue<ImageRequest> requestQueue = getInstance().pendingRequests;
ImageRequest request;
while(true) {
synchronized(requestQueue) {
while(requestQueue.isEmpty()) {
try {
requestQueue.wait();
}
catch(InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
request = requestQueue.poll();
}
processRequest(request);
}
}
private void processRequest(ImageRequest request) {
final ImageRequest[] runningRequests = getInstance().runningRequests;
Drawable drawable;
synchronized(runningRequests) {
runningRequests[index] = request;
drawable = ImageCache.loadImage(request);
}
synchronized(runningRequests) {
if(request != null) {
request.listener.onDrawableLoaded(drawable);
runningRequests[index] = null;
}
else {
LogWrapper.logMessage("Interrupted, returning");
}
}
}
}
private static ImageLoader getInstance() {
if(staticInstance == null) {
staticInstance = new ImageLoader();
}
return staticInstance;
}
private ImageLoader() {
for(int i = 0; i < NUM_WORKERS; i++) {
workerPool[i] = new Worker(i);
workerPool[i].start();
}
}
public static void load(URL imageUrl, ImageRequest.Listener listener, boolean cacheInMemory) {
Queue<ImageRequest> requestQueue = getInstance().pendingRequests;
synchronized(requestQueue) {
for(ImageRequest request : requestQueue) {
if(request.listener.equals(listener)) {
if(request.imageUrl.equals(imageUrl)) {
return;
}
else {
// TODO: Check for same request but with different URL
}
}
}
final ImageRequest[] runningRequests = getInstance().runningRequests;
synchronized(runningRequests) {
for(int i = 0; i < runningRequests.length; i++) {
ImageRequest request = runningRequests[i];
if(request != null) {
if(request.listener.equals(listener)) {
if(request.imageUrl.equals(imageUrl)) {
// Ignore duplicate requests. This is common when doing view recycling in list adapters
return;
}
else {
// Null out the running request in this index. The job will continue running, but when
// it returns it will skip notifying the listener and start processing the next job in
// the pending request queue.
runningRequests[i] = null;
}
}
}
}
}
// TODO: Check running tasks for duplicate jobs
}
synchronized(requestQueue) {
requestQueue.add(new ImageRequest(imageUrl, listener, cacheInMemory));
// TODO: Use notifyAll() instead?
requestQueue.notify();
}
}
public static void enableLogging(String tag, int level) {
LogWrapper.tag = tag;
LogWrapper.level = level;
}
}
|
src/com/wrapp/android/webimage/ImageLoader.java
|
package com.wrapp.android.webimage;
import java.net.URL;
import java.util.LinkedList;
import java.util.Queue;
public class ImageLoader {
private static final int NUM_WORKERS = 2;
private static ImageLoader staticInstance;
private final Queue<ImageRequest> pendingRequests = new LinkedList<ImageRequest>();
private final Worker[] workerPool = new Worker[NUM_WORKERS];
private static class Worker extends Thread {
@Override
public void run() {
final Queue<ImageRequest> requestQueue = getInstance().pendingRequests;
ImageRequest request;
while(true) {
synchronized(requestQueue) {
while(requestQueue.isEmpty()) {
try {
requestQueue.wait();
}
catch(InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
request = requestQueue.poll();
}
processRequest(request);
}
}
private void processRequest(ImageRequest request) {
request.listener.onDrawableLoaded(ImageCache.loadImage(request));
}
}
private static ImageLoader getInstance() {
if(staticInstance == null) {
staticInstance = new ImageLoader();
}
return staticInstance;
}
private ImageLoader() {
for(int i = 0; i < NUM_WORKERS; i++) {
workerPool[i] = new Worker();
workerPool[i].start();
}
}
public static void load(URL imageUrl, ImageRequest.Listener listener, boolean cacheInMemory) {
Queue<ImageRequest> requestQueue = getInstance().pendingRequests;
synchronized(requestQueue) {
for(ImageRequest request : requestQueue) {
if(request.listener.equals(listener)) {
if(request.imageUrl.equals(imageUrl)) {
return;
}
else {
// TODO: Check for same request but with different URL
}
}
}
// TODO: Check running tasks for duplicate jobs
}
synchronized(requestQueue) {
requestQueue.add(new ImageRequest(imageUrl, listener, cacheInMemory));
// TODO: Use notifyAll() instead?
requestQueue.notify();
}
}
public static void enableLogging(String tag, int level) {
LogWrapper.tag = tag;
LogWrapper.level = level;
}
}
|
Check for already running requests, remove/return
|
src/com/wrapp/android/webimage/ImageLoader.java
|
Check for already running requests, remove/return
|
|
Java
|
mit
|
5cdf75f224ea34a7ea1fd0e33fb2efca818fdbe5
| 0
|
t28hub/DraggableView
|
package com.t28.draggablelistview;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class DraggableListView extends RecyclerView {
private static final int NO_DEF_STYLE = 0;
private static final int INITIAL_POINTER_INDEX = 0;
private final Point mTouchDownPoint;
private final Point mTouchMovePoint;
private int mDragPointerId = MotionEvent.INVALID_POINTER_ID;
private long mDraggingItemId = NO_ID;
private View mDraggingView;
private ShadowBuilder mShadowBuilder;
public DraggableListView(Context context) {
this(context, null, NO_DEF_STYLE);
}
public DraggableListView(Context context, AttributeSet attrs) {
this(context, attrs, NO_DEF_STYLE);
}
public DraggableListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mTouchDownPoint = new Point();
mTouchMovePoint = new Point();
mDragPointerId = MotionEvent.INVALID_POINTER_ID;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
final boolean isHandled = handleTouchEvent(event);
if (isHandled) {
return false;
}
return super.onInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
final boolean isHandled = handleTouchEvent(event);
if (isHandled) {
return false;
}
return super.onTouchEvent(event);
}
@Override
protected void dispatchDraw(@NonNull Canvas canvas) {
super.dispatchDraw(canvas);
if (mShadowBuilder != null) {
mShadowBuilder.onDraw(canvas);
}
}
@Override
public void setAdapter(RecyclerView.Adapter adapter) {
if (!(adapter instanceof Adapter)) {
final String message = String.format("'adapter' must be an instance of %s", Adapter.class.getCanonicalName());
throw new IllegalArgumentException(message);
}
super.setAdapter(adapter);
}
@Override
public Adapter getAdapter() {
return (Adapter) super.getAdapter();
}
public boolean isDragging() {
return mDraggingView != null;
}
public void startDrag(View view, ShadowBuilder shadowBuilder) {
if (view == null) {
throw new NullPointerException("'view == null'");
}
if (shadowBuilder == null) {
throw new NullPointerException("'shadowBuilder == null'");
}
final ViewHolder viewHolder = getChildViewHolder(view);
if (viewHolder == null) {
final String message = String.format("View(%s) is not found in %s", view, this);
throw new IllegalArgumentException(message);
}
if (isDragging()) {
final String message = String.format("Another view(%s) is dragging", mDraggingView);
throw new IllegalStateException(message);
}
final int adapterPosition = viewHolder.getAdapterPosition();
mDraggingItemId = getAdapter().getItemId(adapterPosition);
mDraggingView = view;
mShadowBuilder = shadowBuilder;
invalidate();
}
private boolean handleTouchEvent(MotionEvent event) {
final int action = event.getActionMasked();
if (action == MotionEvent.ACTION_DOWN) {
return onTouchDown(event);
}
if (action == MotionEvent.ACTION_UP) {
return onTouchUp(event);
}
if (action == MotionEvent.ACTION_MOVE) {
return onTouchMove(event);
}
if (action == MotionEvent.ACTION_CANCEL) {
return onTouchCancel(event);
}
if (action == MotionEvent.ACTION_POINTER_UP) {
return onTouchPointerUp(event);
}
return false;
}
private boolean onTouchDown(MotionEvent event) {
mDragPointerId = event.getPointerId(INITIAL_POINTER_INDEX);
mTouchDownPoint.x = (int) event.getX(mDragPointerId);
mTouchDownPoint.y = (int) event.getY(mDragPointerId);
return false;
}
private boolean onTouchUp(MotionEvent event) {
if (!isDragging()) {
return false;
}
mTouchMovePoint.x = (int) event.getX(mDragPointerId);
mTouchMovePoint.y = (int) event.getY(mDragPointerId);
reset();
return false;
}
private boolean onTouchMove(MotionEvent event) {
if (!isDragging()) {
return false;
}
mTouchMovePoint.x = (int) event.getX(mDragPointerId);
mTouchMovePoint.y = (int) event.getY(mDragPointerId);
if (mShadowBuilder.onMove(new Point(mTouchMovePoint))) {
invalidate();
}
final View underView = findChildViewUnder(mTouchMovePoint.x, mTouchMovePoint.y);
if (moveTo(underView)) {
mDraggingView = underView;
}
handleScroll();
return true;
}
private boolean onTouchCancel(MotionEvent event) {
if (!isDragging()) {
return false;
}
mTouchMovePoint.x = (int) event.getX(mDragPointerId);
mTouchMovePoint.y = (int) event.getY(mDragPointerId);
reset();
return false;
}
private boolean onTouchPointerUp(MotionEvent event) {
return onTouchUp(event);
}
private void reset() {
mDragPointerId = MotionEvent.INVALID_POINTER_ID;
mDraggingItemId = NO_ID;
mDraggingView = null;
mShadowBuilder = null;
invalidate();
}
private boolean moveTo(View underView) {
if (underView == null) {
return false;
}
final int fromPosition = findPositionForItemId(mDraggingItemId);
final int toPosition = getChildAdapterPosition(underView);
if (fromPosition < 0 || toPosition < 0) {
return false;
}
final boolean isMoved = getAdapter().move(fromPosition, toPosition);
if (!isMoved) {
return false;
}
if (fromPosition == 0 || toPosition == 0) {
scrollToPosition(0);
}
return true;
}
private int findPositionForItemId(long itemId) {
final Adapter adapter = getAdapter();
final int itemCount = adapter.getItemCount();
for (int position = 0; position < itemCount; position++) {
if (adapter.getItemId(position) == itemId) {
return position;
}
}
return NO_POSITION;
}
private void handleScroll() {
final boolean isScrolled = scrollIfNeeded();
if (!isScrolled) {
return;
}
postDelayed(new Runnable() {
@Override
public void run() {
if (!isDragging()) {
return;
}
handleScroll();
}
}, 50);
}
private boolean scrollIfNeeded() {
final Rect shadowBounds = mShadowBuilder.getShadow().getBounds();
if (canScrollVertically(-1) && mTouchMovePoint.y < (getTop() + shadowBounds.height())) {
scrollBy(0, -1);
return true;
}
if (canScrollVertically(1) && (getBottom() - shadowBounds.height()) < mTouchMovePoint.y) {
scrollBy(0, 1);
return true;
}
return false;
}
public static abstract class Adapter<VH extends ViewHolder> extends RecyclerView.Adapter<VH> {
public abstract long getItemId(int position);
public abstract boolean move(int position1, int position2);
}
public static class ShadowBuilder {
private final Drawable mShadow;
public ShadowBuilder(View view) {
if (view == null) {
throw new NullPointerException("view == null");
}
mShadow = createShadow(view);
mShadow.setBounds(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
}
protected Drawable createShadow(@NonNull View view) {
final Bitmap.Config config = Bitmap.Config.ARGB_8888;
final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), config);
final Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return new BitmapDrawable(view.getResources(), bitmap.copy(config, false));
}
protected Drawable getShadow() {
return mShadow;
}
protected void onDraw(@NonNull Canvas canvas) {
mShadow.draw(canvas);
}
protected boolean onMove(@NonNull Point newPoint) {
final Rect oldBounds = mShadow.getBounds();
final int halfWidth = oldBounds.width() / 2;
final int halfHeight = oldBounds.height() / 2;
final Rect newBounds = new Rect();
newBounds.left = newPoint.x - halfWidth;
newBounds.top = newPoint.y - halfHeight;
newBounds.right = newPoint.x + halfWidth;
newBounds.bottom = newPoint.y + halfHeight;
mShadow.setBounds(newBounds);
return oldBounds.equals(newBounds);
}
}
}
|
library/src/main/java/com/t28/draggablelistview/DraggableListView.java
|
package com.t28.draggablelistview;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class DraggableListView extends RecyclerView {
private static final int NO_DEF_STYLE = 0;
private static final int INITIAL_POINTER_INDEX = 0;
private final Point mTouchDownPoint;
private final Point mTouchMovePoint;
private int mDragPointerId = MotionEvent.INVALID_POINTER_ID;
private long mDraggingItemId = NO_ID;
private View mDraggingView;
private ShadowBuilder mShadowBuilder;
public DraggableListView(Context context) {
this(context, null, NO_DEF_STYLE);
}
public DraggableListView(Context context, AttributeSet attrs) {
this(context, attrs, NO_DEF_STYLE);
}
public DraggableListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mTouchDownPoint = new Point();
mTouchMovePoint = new Point();
mDragPointerId = MotionEvent.INVALID_POINTER_ID;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
final boolean isHandled = handleTouchEvent(event);
if (isHandled) {
return false;
}
return super.onInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
final boolean isHandled = handleTouchEvent(event);
if (isHandled) {
return false;
}
return super.onTouchEvent(event);
}
@Override
protected void dispatchDraw(@NonNull Canvas canvas) {
super.dispatchDraw(canvas);
if (mShadowBuilder != null) {
mShadowBuilder.onDraw(canvas);
}
}
@Override
public void setAdapter(RecyclerView.Adapter adapter) {
if (!(adapter instanceof Adapter)) {
final String message = String.format("'adapter' must be an instance of %s", Adapter.class.getCanonicalName());
throw new IllegalArgumentException(message);
}
super.setAdapter(adapter);
}
@Override
public Adapter getAdapter() {
return (Adapter) super.getAdapter();
}
public boolean isDragging() {
return mDraggingView != null;
}
public void startDrag(View view, ShadowBuilder shadowBuilder) {
if (view == null) {
throw new NullPointerException("'view == null'");
}
if (shadowBuilder == null) {
throw new NullPointerException("'shadowBuilder == null'");
}
final ViewHolder viewHolder = getChildViewHolder(view);
if (viewHolder == null) {
final String message = String.format("View(%s) is not found in %s", view, this);
throw new IllegalArgumentException(message);
}
if (isDragging()) {
final String message = String.format("Another view(%s) is dragging", mDraggingView);
throw new IllegalStateException(message);
}
final int adapterPosition = viewHolder.getAdapterPosition();
mDraggingItemId = getAdapter().getItemId(adapterPosition);
mDraggingView = view;
mShadowBuilder = shadowBuilder;
invalidate();
}
private boolean handleTouchEvent(MotionEvent event) {
final int action = event.getActionMasked();
if (action == MotionEvent.ACTION_DOWN) {
return onTouchDown(event);
}
if (action == MotionEvent.ACTION_UP) {
return onTouchUp(event);
}
if (action == MotionEvent.ACTION_MOVE) {
return onTouchMove(event);
}
if (action == MotionEvent.ACTION_CANCEL) {
return onTouchCancel(event);
}
if (action == MotionEvent.ACTION_POINTER_UP) {
return onTouchPointerUp(event);
}
return false;
}
private boolean onTouchDown(MotionEvent event) {
mDragPointerId = event.getPointerId(INITIAL_POINTER_INDEX);
mTouchDownPoint.x = (int) event.getX(mDragPointerId);
mTouchDownPoint.y = (int) event.getY(mDragPointerId);
return false;
}
private boolean onTouchUp(MotionEvent event) {
if (!isDragging()) {
return false;
}
mTouchMovePoint.x = (int) event.getX(mDragPointerId);
mTouchMovePoint.y = (int) event.getY(mDragPointerId);
reset();
return false;
}
private boolean onTouchMove(MotionEvent event) {
if (!isDragging()) {
return false;
}
mTouchMovePoint.x = (int) event.getX(mDragPointerId);
mTouchMovePoint.y = (int) event.getY(mDragPointerId);
if (mShadowBuilder.onMove(new Point(mTouchMovePoint))) {
invalidate();
}
final View underView = findChildViewUnder(mTouchMovePoint.x, mTouchMovePoint.y);
if (moveTo(underView)) {
mDraggingView = underView;
}
handleScroll();
return true;
}
private boolean onTouchCancel(MotionEvent event) {
if (!isDragging()) {
return false;
}
mTouchMovePoint.x = (int) event.getX(mDragPointerId);
mTouchMovePoint.y = (int) event.getY(mDragPointerId);
reset();
return false;
}
private boolean onTouchPointerUp(MotionEvent event) {
return onTouchUp(event);
}
private void reset() {
mDragPointerId = MotionEvent.INVALID_POINTER_ID;
mDraggingItemId = NO_ID;
mDraggingView = null;
mShadowBuilder = null;
invalidate();
}
private boolean moveTo(View underView) {
if (underView == null) {
return false;
}
final int fromPosition = findPositionForItemId(mDraggingItemId);
final int toPosition = getChildAdapterPosition(underView);
if (fromPosition < 0 || toPosition < 0) {
return false;
}
final boolean isMoved = getAdapter().move(fromPosition, toPosition);
if (!isMoved) {
return false;
}
if (fromPosition == 0 || toPosition == 0) {
scrollToPosition(0);
}
return true;
}
private int findPositionForItemId(long itemId) {
final Adapter adapter = getAdapter();
final int itemCount = adapter.getItemCount();
for (int position = 0; position < itemCount; position++) {
if (adapter.getItemId(position) == itemId) {
return position;
}
}
return NO_POSITION;
}
private void handleScroll() {
final boolean isScrolled = scrollIfNeeded();
postDelayed(new Runnable() {
@Override
public void run() {
if (!isDragging() || !isScrolled) {
return;
}
handleScroll();
}
}, 100);
}
private boolean scrollIfNeeded() {
final Rect shadowBounds = mShadowBuilder.getShadow().getBounds();
if (canScrollVertically(-1) && mTouchMovePoint.y < (getTop() + shadowBounds.height())) {
scrollBy(0, -1);
return true;
}
if (canScrollVertically(1) && (getBottom() - shadowBounds.height()) < mTouchMovePoint.y) {
scrollBy(0, 1);
return true;
}
return false;
}
public static abstract class Adapter<VH extends ViewHolder> extends RecyclerView.Adapter<VH> {
public abstract long getItemId(int position);
public abstract boolean move(int position1, int position2);
}
public static class ShadowBuilder {
private final Drawable mShadow;
public ShadowBuilder(View view) {
if (view == null) {
throw new NullPointerException("view == null");
}
mShadow = createShadow(view);
mShadow.setBounds(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
}
protected Drawable createShadow(@NonNull View view) {
final Bitmap.Config config = Bitmap.Config.ARGB_8888;
final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), config);
final Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return new BitmapDrawable(view.getResources(), bitmap.copy(config, false));
}
protected Drawable getShadow() {
return mShadow;
}
protected void onDraw(@NonNull Canvas canvas) {
mShadow.draw(canvas);
}
protected boolean onMove(@NonNull Point newPoint) {
final Rect oldBounds = mShadow.getBounds();
final int halfWidth = oldBounds.width() / 2;
final int halfHeight = oldBounds.height() / 2;
final Rect newBounds = new Rect();
newBounds.left = newPoint.x - halfWidth;
newBounds.top = newPoint.y - halfHeight;
newBounds.right = newPoint.x + halfWidth;
newBounds.bottom = newPoint.y + halfHeight;
mShadow.setBounds(newBounds);
return oldBounds.equals(newBounds);
}
}
}
|
スクロール判定で無駄にRunnableをpostする処理を変更
|
library/src/main/java/com/t28/draggablelistview/DraggableListView.java
|
スクロール判定で無駄にRunnableをpostする処理を変更
|
|
Java
|
mit
|
bac24559ae1f882d1ef347d2dddee0acd3f234db
| 0
|
conveyal/analyst,conveyal/analysis-backend,conveyal/analyst,conveyal/analyst,conveyal/analysis-backend,conveyal/analysis-backend
|
package com.conveyal.taui.controllers;
import com.amazonaws.HttpMethod;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.conveyal.r5.analyst.Grid;
import com.conveyal.r5.util.S3Util;
import com.conveyal.r5.util.ShapefileReader;
import com.conveyal.taui.AnalysisServerConfig;
import com.conveyal.taui.grids.SeamlessCensusGridExtractor;
import com.conveyal.taui.models.AggregationArea;
import com.conveyal.taui.persistence.Persistence;
import com.conveyal.taui.util.JsonUtil;
import com.conveyal.taui.util.WrappedURL;
import com.google.common.io.Files;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.operation.union.UnaryUnionOp;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.Request;
import spark.Response;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;
import static com.conveyal.taui.util.SparkUtil.haltWithJson;
import static spark.Spark.get;
import static spark.Spark.post;
/**
* Stores vector aggregationAreas (used to define the region of a weighted average accessibility metric).
*/
public class AggregationAreaController {
private static final Logger LOG = LoggerFactory.getLogger(AggregationAreaController.class);
private static final AmazonS3 s3 = new AmazonS3Client();
private static final FileItemFactory fileItemFactory = new DiskFileItemFactory();
public static AggregationArea createAggregationArea (Request req, Response res) throws Exception {
ServletFileUpload sfu = new ServletFileUpload(fileItemFactory);
Map<String, List<FileItem>> query = sfu.parseParameterMap(req.raw());
// extract relevant files: .shp, .prj, .dbf, and .shx.
// We need the SHX even though we're looping over every feature as they might be sparse.
Map<String, FileItem> filesByName = query.get("files").stream()
.collect(Collectors.toMap(FileItem::getName, f -> f));
String fileName = filesByName.keySet().stream().filter(f -> f.endsWith(".shp")).findAny().orElse(null);
if (fileName == null) {
haltWithJson(400, "Shapefile upload must contain .shp, .prj, and .dbf. Please verify the contents of your data before trying again.");
}
String baseName = fileName.substring(0, fileName.length() - 4);
if (!filesByName.containsKey(baseName + ".shp") ||
!filesByName.containsKey(baseName + ".prj") ||
!filesByName.containsKey(baseName + ".dbf")) {
haltWithJson(400, "Shapefile upload must contain .shp, .prj, and .dbf. Please verify the contents of your data before trying again.");
}
String projectId = req.params("projectId");
String maskName = query.get("name").get(0).getString("UTF-8");
File tempDir = Files.createTempDir();
File shpFile = new File(tempDir, "grid.shp");
filesByName.get(baseName + ".shp").write(shpFile);
File prjFile = new File(tempDir, "grid.prj");
filesByName.get(baseName + ".prj").write(prjFile);
File dbfFile = new File(tempDir, "grid.dbf");
filesByName.get(baseName + ".dbf").write(dbfFile);
// shx is optional, not needed for dense shapefiles
if (filesByName.containsKey(baseName + ".shx")) {
File shxFile = new File(tempDir, "grid.shx");
filesByName.get(baseName + ".shx").write(shxFile);
}
ShapefileReader reader = new ShapefileReader(shpFile);
List<Geometry> geometries = reader.stream().map(f -> (Geometry) f.getDefaultGeometry()).collect(Collectors.toList());
UnaryUnionOp union = new UnaryUnionOp(geometries);
Geometry merged = union.union();
Envelope env = merged.getEnvelopeInternal();
Grid maskGrid = new Grid(SeamlessCensusGridExtractor.ZOOM, env.getMaxY(), env.getMaxX(), env.getMinY(), env.getMinX());
// Store the percentage each cell overlaps the mask, scaled as 0 to 100,000
List<Grid.PixelWeight> weights = maskGrid.getPixelWeights(merged, true);
weights.forEach(pixel -> maskGrid.grid[pixel.x][pixel.y] = pixel.weight * 100_000);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentEncoding("gzip");
metadata.setContentType("application/octet-stream");
AggregationArea aggregationArea = new AggregationArea();
aggregationArea.name = maskName;
aggregationArea.id = UUID.randomUUID().toString();
aggregationArea.projectId = projectId;
File gridFile = new File(tempDir, "weights.grid");
OutputStream os = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(gridFile)));
maskGrid.write(os);
os.close();
InputStream is = new BufferedInputStream(new FileInputStream(gridFile));
// can't use putObject with File when we have metadata . . .
S3Util.s3.putObject(AnalysisServerConfig.gridBucket, aggregationArea.getS3Key(), is, metadata);
is.close();
Persistence.aggregationAreas.put(aggregationArea.id, aggregationArea);
tempDir.delete();
return aggregationArea;
}
public static Object getAggregationArea (Request req, Response res) {
String maskId = req.params("maskId");
String projectId = req.params("projectId");
boolean redirect = true;
try {
String redirectParam = req.queryParams("redirect");
if (redirectParam != null) redirect = Boolean.parseBoolean(redirectParam);
} catch (Exception e) {
// do nothing
}
AggregationArea aggregationArea = Persistence.aggregationAreas.get(maskId);
Date expiration = new Date();
expiration.setTime(expiration.getTime() + 60 * 1000);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(AnalysisServerConfig.gridBucket, aggregationArea.getS3Key(), HttpMethod.GET);
request.setExpiration(expiration);
URL url = s3.generatePresignedUrl(request);
if (redirect) {
res.redirect(url.toString());
res.status(302); // temporary redirect, this URL will soon expire
res.type("text/plain"); // override application/json default
return res;
} else {
return new WrappedURL(url);
}
}
public static void register () {
get("/api/project/:projectId/aggregationArea/:maskId", AggregationAreaController::getAggregationArea, JsonUtil.objectMapper::writeValueAsString);
post("/api/project/:projectId/aggregationArea", AggregationAreaController::createAggregationArea, JsonUtil.objectMapper::writeValueAsString);
}
}
|
src/main/java/com/conveyal/taui/controllers/AggregationAreaController.java
|
package com.conveyal.taui.controllers;
import com.amazonaws.HttpMethod;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.conveyal.r5.analyst.Grid;
import com.conveyal.r5.util.S3Util;
import com.conveyal.r5.util.ShapefileReader;
import com.conveyal.taui.AnalysisServerConfig;
import com.conveyal.taui.grids.SeamlessCensusGridExtractor;
import com.conveyal.taui.models.AggregationArea;
import com.conveyal.taui.persistence.Persistence;
import com.conveyal.taui.util.JsonUtil;
import com.conveyal.taui.util.WrappedURL;
import com.google.common.io.Files;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.operation.union.UnaryUnionOp;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.Request;
import spark.Response;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;
import static com.conveyal.taui.util.SparkUtil.haltWithJson;
import static spark.Spark.get;
import static spark.Spark.post;
/**
* Stores vector aggregationAreas (used to define the region of a weighted average accessibility metric).
*/
public class AggregationAreaController {
private static final Logger LOG = LoggerFactory.getLogger(AggregationAreaController.class);
private static final AmazonS3 s3 = new AmazonS3Client();
private static final FileItemFactory fileItemFactory = new DiskFileItemFactory();
public static AggregationArea createAggregationArea (Request req, Response res) throws Exception {
ServletFileUpload sfu = new ServletFileUpload(fileItemFactory);
Map<String, List<FileItem>> query = sfu.parseParameterMap(req.raw());
// extract relevant files: .shp, .prj, .dbf, and .shx.
// We need the SHX even though we're looping over every feature as they might be sparse.
Map<String, FileItem> filesByName = query.get("files").stream()
.collect(Collectors.toMap(FileItem::getName, f -> f));
String fileName = filesByName.keySet().stream().filter(f -> f.endsWith(".shp")).findAny().orElse(null);
if (fileName == null) {
haltWithJson(400, "Shapefile upload must contain .shp, .prj, and .dbf. Please verify the contents of your data before trying again.");
}
String baseName = fileName.substring(0, fileName.length() - 4);
if (!filesByName.containsKey(baseName + ".shp") ||
!filesByName.containsKey(baseName + ".prj") ||
!filesByName.containsKey(baseName + ".dbf")) {
haltWithJson(400, "Shapefile upload must contain .shp, .prj, and .dbf. Please verify the contents of your data before trying again.");
}
String projectId = req.params("projectId");
String maskName = query.get("name").get(0).getString("UTF-8");
File tempDir = Files.createTempDir();
File shpFile = new File(tempDir, "grid.shp");
filesByName.get(baseName + ".shp").write(shpFile);
File prjFile = new File(tempDir, "grid.prj");
filesByName.get(baseName + ".prj").write(prjFile);
File dbfFile = new File(tempDir, "grid.dbf");
filesByName.get(baseName + ".dbf").write(dbfFile);
// shx is optional, not needed for dense shapefiles
if (filesByName.containsKey(baseName + ".shx")) {
File shxFile = new File(tempDir, "grid.shx");
filesByName.get(baseName + ".shx").write(shxFile);
}
ShapefileReader reader = new ShapefileReader(shpFile);
List<Geometry> geometries = reader.stream().map(f -> (Geometry) f.getDefaultGeometry()).collect(Collectors.toList());
UnaryUnionOp union = new UnaryUnionOp(geometries);
Geometry merged = union.union();
Envelope env = merged.getEnvelopeInternal();
Grid maskGrid = new Grid(SeamlessCensusGridExtractor.ZOOM, env.getMaxY(), env.getMaxX(), env.getMinY(), env.getMinX());
// Store the percentage each cell overlaps the mask, scaled as 0 to 100,000
maskGrid.streamPixelWeights(merged, true, (int x, int y, double weight) -> maskGrid.grid[x][y] = weight);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentEncoding("gzip");
metadata.setContentType("application/octet-stream");
AggregationArea aggregationArea = new AggregationArea();
aggregationArea.name = maskName;
aggregationArea.id = UUID.randomUUID().toString();
aggregationArea.projectId = projectId;
File gridFile = new File(tempDir, "weights.grid");
OutputStream os = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(gridFile)));
maskGrid.write(os);
os.close();
InputStream is = new BufferedInputStream(new FileInputStream(gridFile));
// can't use putObject with File when we have metadata . . .
S3Util.s3.putObject(AnalysisServerConfig.gridBucket, aggregationArea.getS3Key(), is, metadata);
is.close();
Persistence.aggregationAreas.put(aggregationArea.id, aggregationArea);
tempDir.delete();
return aggregationArea;
}
public static Object getAggregationArea (Request req, Response res) {
String maskId = req.params("maskId");
String projectId = req.params("projectId");
boolean redirect = true;
try {
String redirectParam = req.queryParams("redirect");
if (redirectParam != null) redirect = Boolean.parseBoolean(redirectParam);
} catch (Exception e) {
// do nothing
}
AggregationArea aggregationArea = Persistence.aggregationAreas.get(maskId);
Date expiration = new Date();
expiration.setTime(expiration.getTime() + 60 * 1000);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(AnalysisServerConfig.gridBucket, aggregationArea.getS3Key(), HttpMethod.GET);
request.setExpiration(expiration);
URL url = s3.generatePresignedUrl(request);
if (redirect) {
res.redirect(url.toString());
res.status(302); // temporary redirect, this URL will soon expire
res.type("text/plain"); // override application/json default
return res;
} else {
return new WrappedURL(url);
}
}
public static void register () {
get("/api/project/:projectId/aggregationArea/:maskId", AggregationAreaController::getAggregationArea, JsonUtil.objectMapper::writeValueAsString);
post("/api/project/:projectId/aggregationArea", AggregationAreaController::createAggregationArea, JsonUtil.objectMapper::writeValueAsString);
}
}
|
refactor(rasterization): use in-memory pixwelWeight, don't stream
|
src/main/java/com/conveyal/taui/controllers/AggregationAreaController.java
|
refactor(rasterization): use in-memory pixwelWeight, don't stream
|
|
Java
|
mit
|
b8a5999343fc6b982d66ea6a7006f20dc4015013
| 0
|
chrislo27/Stray-core
|
package stray;
import stray.ui.LevelSelectButton;
import stray.ui.NextLevelButton;
import stray.ui.RetryLevelButton;
import stray.util.Utils;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.math.MathUtils;
public class ResultsScreen extends Updateable {
public ResultsScreen(Main m) {
super(m);
container.elements.add(new LevelSelectButton(Gdx.graphics.getWidth() / 2 - 24 - 8 - 48, Gdx.graphics.getHeight() / 4){
@Override
public boolean onLeftClick() {
main.setScreen(Main.LEVELSELECT);
return true;
}
});
container.elements.add(new RetryLevelButton(Gdx.graphics.getWidth() / 2 - 24, Gdx.graphics.getHeight() / 4){
@Override
public boolean onLeftClick() {
Main.LEVELSELECT.goToLevel(levelname);
return true;
}
});
container.elements.add(new NextLevelButton(Gdx.graphics.getWidth() / 2 - 24 + 8 + 48, Gdx.graphics.getHeight() / 4){
@Override
public boolean onLeftClick() {
Main.LEVELSELECT.goToLevel(Math.round(Main.LEVELSELECT.wanted));
return true;
}
});
}
private String levelfile = null;
private int levelname = 0;
private boolean voidPresent = false;
private int resultsPick = MathUtils.random(0, 3);
private int deaths = 0;
public ResultsScreen setData(String levelf, int levelid, boolean voidChasing, int deaths) {
levelfile = levelf;
levelname = levelid;
voidPresent = voidChasing;
this.deaths = deaths;
int old = resultsPick;
while(resultsPick == old){
resultsPick = MathUtils.random(0, 3);
}
return this;
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
main.batch.begin();
if (levelfile != null) {
main.font.setColor(1, 1, 1, 1);
main.font.setScale(2);
main.drawCentered(
Levels.getLevelName(levelname),
Gdx.graphics.getWidth() / 2, Main.convertY(225));
main.font.setScale(1);
main.drawCentered(
Translator.getMsg("menu.results.latesttime")
+ Utils.formatMs(main.progress.getLong(levelfile + "-latesttime")),
Gdx.graphics.getWidth() / 2, Main.convertY(275));
main.drawCentered(
Translator.getMsg("menu.results.besttime")
+ Utils.formatMs(main.progress.getLong(levelfile + "-latesttime")),
Gdx.graphics.getWidth() / 2, Main.convertY(300));
main.drawCentered(
Translator.getMsg("menu.results.deaths")
+ deaths,
Gdx.graphics.getWidth() / 2, Main.convertY(325));
main.drawCentered(
Translator.getMsg("menu.results.verdict"),
Gdx.graphics.getWidth() / 2, Main.convertY(380));
if(voidPresent){
if(main.progress.getLong(levelfile + "-latesttime") <= Levels.instance().levels.get(levelname).bestTime){
main.drawCentered(
"\"" + Translator.getMsg("menu.results.good" + resultsPick) + "\"",
Gdx.graphics.getWidth() / 2, Main.convertY(400));
}else{
main.drawCentered(
"\"" + Translator.getMsg("menu.results.bad" + resultsPick) + "\"",
Gdx.graphics.getWidth() / 2, Main.convertY(400));
}
}else{
main.drawCentered(
"\"" + Translator.getMsg("menu.results.good" + resultsPick) + "\"",
Gdx.graphics.getWidth() / 2, Main.convertY(400));
}
}
container.render(main);
main.batch.end();
}
@Override
public void renderUpdate() {
}
@Override
public void tickUpdate() {
}
@Override
public void renderDebug(int starting) {
}
@Override
public void resize(int width, int height) {
}
@Override
public void show() {
}
@Override
public void hide() {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void dispose() {
}
}
|
src/stray/ResultsScreen.java
|
package stray;
import stray.ui.LevelSelectButton;
import stray.ui.NextLevelButton;
import stray.ui.RetryLevelButton;
import stray.util.Utils;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.math.MathUtils;
public class ResultsScreen extends Updateable {
public ResultsScreen(Main m) {
super(m);
container.elements.add(new LevelSelectButton(Gdx.graphics.getWidth() / 2 - 24 - 8 - 48, Gdx.graphics.getHeight() / 4){
@Override
public boolean onLeftClick() {
main.setScreen(Main.LEVELSELECT);
return true;
}
});
container.elements.add(new RetryLevelButton(Gdx.graphics.getWidth() / 2 - 24, Gdx.graphics.getHeight() / 4){
@Override
public boolean onLeftClick() {
Main.LEVELSELECT.goToLevel(levelname);
return true;
}
});
container.elements.add(new NextLevelButton(Gdx.graphics.getWidth() / 2 - 24 + 8 + 48, Gdx.graphics.getHeight() / 4){
@Override
public boolean onLeftClick() {
Main.LEVELSELECT.goToLevel(Math.round(Main.LEVELSELECT.wanted));
return true;
}
});
}
private String levelfile = null;
private int levelname = 0;
private boolean voidPresent = false;
private int resultsPick = MathUtils.random(0, 3);
private int deaths = 0;
public ResultsScreen setData(String levelf, int levelid, boolean voidChasing, int deaths) {
levelfile = levelf;
levelname = levelid;
voidPresent = voidChasing;
this.deaths = deaths;
int old = resultsPick;
while(resultsPick != old){
resultsPick = MathUtils.random(0, 3);
}
return this;
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
main.batch.begin();
if (levelfile != null) {
main.font.setColor(1, 1, 1, 1);
main.font.setScale(2);
main.drawCentered(
Levels.getLevelName(levelname),
Gdx.graphics.getWidth() / 2, Main.convertY(225));
main.font.setScale(1);
main.drawCentered(
Translator.getMsg("menu.results.latesttime")
+ Utils.formatMs(main.progress.getLong(levelfile + "-latesttime")),
Gdx.graphics.getWidth() / 2, Main.convertY(275));
main.drawCentered(
Translator.getMsg("menu.results.besttime")
+ Utils.formatMs(main.progress.getLong(levelfile + "-latesttime")),
Gdx.graphics.getWidth() / 2, Main.convertY(300));
main.drawCentered(
Translator.getMsg("menu.results.deaths")
+ deaths,
Gdx.graphics.getWidth() / 2, Main.convertY(325));
main.drawCentered(
Translator.getMsg("menu.results.verdict"),
Gdx.graphics.getWidth() / 2, Main.convertY(380));
if(voidPresent){
if(main.progress.getLong(levelfile + "-latesttime") <= Levels.instance().levels.get(levelname).bestTime){
main.drawCentered(
"\"" + Translator.getMsg("menu.results.good" + resultsPick) + "\"",
Gdx.graphics.getWidth() / 2, Main.convertY(400));
}else{
main.drawCentered(
"\"" + Translator.getMsg("menu.results.bad" + resultsPick) + "\"",
Gdx.graphics.getWidth() / 2, Main.convertY(400));
}
}else{
main.drawCentered(
"\"" + Translator.getMsg("menu.results.good" + resultsPick) + "\"",
Gdx.graphics.getWidth() / 2, Main.convertY(400));
}
}
container.render(main);
main.batch.end();
}
@Override
public void renderUpdate() {
}
@Override
public void tickUpdate() {
}
@Override
public void renderDebug(int starting) {
}
@Override
public void resize(int width, int height) {
}
@Override
public void show() {
}
@Override
public void hide() {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void dispose() {
}
}
|
Stupid results verdict chooser with the wrong operator
|
src/stray/ResultsScreen.java
|
Stupid results verdict chooser with the wrong operator
|
|
Java
|
mit
|
7eb0f24ee8c4ec93462d40ccf1f394eb2ec9dd09
| 0
|
sormuras/bach,sormuras/bach
|
package com.github.sormuras.bach;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
public record Grabber(Bach bach) {
public Directory newExternalToolLayerDirectory(String name, Asset... assets) {
return new Directory(bach.path().externalToolLayers(), name, List.of(assets));
}
public Directory newExternalToolProgramDirectory(String name, Asset... assets) {
return new Directory(bach.path().externalToolPrograms(), name, List.of(assets));
}
public void grab(Object... args) {
bach.run("grab", args);
}
public void grab(Path directory, Asset asset) {
var target = directory.resolve(asset.name());
var source = asset.source();
bach.run("grab", target.toString().replace('\\', '/') + '=' + source);
}
public void grab(Directory... directories) {
for (var directory : directories) {
var root = directory.parent().resolve(directory.name());
for (var asset : directory.assets()) grab(root, asset);
}
}
public void grabExternalModules(ModuleLocator locator, String... modules) {
grabExternalModules(ModuleLocators.of(locator), modules);
}
public void grabExternalModules(ModuleLocators locators, String... modules) {
var directory = bach.path().externalModules();
module_loop:
for (var module : modules) {
for (var locator : locators.list()) {
var location = locator.find(module);
if (location.isEmpty()) continue;
bach.log("DEBUG:Located module `%s` via %s".formatted(module, locator.caption()));
grab(directory, new Asset(module + ".jar", location.get()));
continue module_loop;
}
throw new RuntimeException("Can not locate module: " + module);
}
}
public void grabMissingExternalModules(ModuleLocator locator) {
grabMissingExternalModules(ModuleLocators.of(locator));
}
public void grabMissingExternalModules(ModuleLocators locators) {
bach.log("DEBUG:Grab missing external modules");
var explorer = bach.explorer();
var loaded = new TreeSet<String>();
var difference = new TreeSet<String>();
while (true) {
var missing = explorer.listMissingExternalModules();
if (missing.isEmpty()) break;
difference.retainAll(missing);
if (!difference.isEmpty()) throw new Error("Still missing?! " + difference);
difference.addAll(missing);
grabExternalModules(locators, missing.toArray(String[]::new));
loaded.addAll(missing);
}
bach.log("DEBUG:Grabbed %d module%s".formatted(loaded.size(), loaded.size() == 1 ? "" : "s"));
}
public record Asset(String name, String source) {}
public record Directory(Path parent, String name, List<Asset> assets) {
public Directory withAsset(String target, String source) {
var assets = new ArrayList<>(assets());
assets.add(new Asset(target, source));
return new Directory(parent, name, assets);
}
}
}
|
com.github.sormuras.bach/main/java/com/github/sormuras/bach/Grabber.java
|
package com.github.sormuras.bach;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
public record Grabber(Bach bach) {
public Directory newExternalToolLayerDirectory(String name, Asset... assets) {
return new Directory(bach.path().externalToolLayers(), name, List.of(assets));
}
public Directory newExternalToolProgramDirectory(String name, Asset... assets) {
return new Directory(bach.path().externalToolPrograms(), name, List.of(assets));
}
public void grab(Object... args) {
bach.run("grab", args);
}
public void grab(Path directory, Asset asset) {
var target = directory.resolve(asset.name());
var source = asset.source();
bach.run("grab", target.toString().replace('\\', '/') + '=' + source);
}
public void grab(Directory... directories) {
for (var directory : directories) {
var root = directory.parent().resolve(directory.name());
for (var asset : directory.assets()) grab(root, asset);
}
}
public void grabExternalModules(ModuleLocator locator, String... modules) {
grabExternalModules(ModuleLocators.of(locator), modules);
}
public void grabExternalModules(ModuleLocators locators, String... modules) {
var directory = bach.path().externalModules();
module_loop:
for (var module : modules) {
for (var locator : locators.list()) {
var location = locator.find(module);
if (location.isEmpty()) continue;
bach.log("DEBUG:Located module `%s` via %s".formatted(module, locator.caption()));
grab(directory, new Asset(module + ".jar", location.get()));
continue module_loop;
}
throw new RuntimeException("Can not locate module: " + module);
}
}
public void grabMissingExternalModules(ModuleLocator locator) {
grabMissingExternalModules(ModuleLocators.of(locator));
}
public void grabMissingExternalModules(ModuleLocators locators) {
bach.log("INFO:Grab missing external modules");
var explorer = bach.explorer();
var loaded = new TreeSet<String>();
var difference = new TreeSet<String>();
while (true) {
var missing = explorer.listMissingExternalModules();
if (missing.isEmpty()) break;
difference.retainAll(missing);
if (!difference.isEmpty()) throw new Error("Still missing?! " + difference);
difference.addAll(missing);
grabExternalModules(locators, missing.toArray(String[]::new));
loaded.addAll(missing);
}
bach.log("Grabbed %d missing module%s".formatted(loaded.size(), loaded.size() == 1 ? "" : "s"));
}
public record Asset(String name, String source) {}
public record Directory(Path parent, String name, List<Asset> assets) {
public Directory withAsset(String target, String source) {
var assets = new ArrayList<>(assets());
assets.add(new Asset(target, source));
return new Directory(parent, name, assets);
}
}
}
|
Tune-down logging message level
|
com.github.sormuras.bach/main/java/com/github/sormuras/bach/Grabber.java
|
Tune-down logging message level
|
|
Java
|
mpl-2.0
|
6aadd6187e47d10872c26baa263dc2089e3ce543
| 0
|
JustBru00/RenamePlugin
|
/**
* @author Justin "JustBru00" Brubaker
*
* This is licensed under the MPL Version 2.0. See license info in LICENSE.txt
*/
package com.gmail.justbru00.epic.rename.main.v3;
import java.io.IOException;
import java.util.Calendar;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import com.gmail.justbru00.epic.rename.commands.v3.EpicRename;
import com.gmail.justbru00.epic.rename.commands.v3.Export;
import com.gmail.justbru00.epic.rename.commands.v3.Glow;
import com.gmail.justbru00.epic.rename.commands.v3.Import;
import com.gmail.justbru00.epic.rename.commands.v3.Lore;
import com.gmail.justbru00.epic.rename.commands.v3.RemoveGlow;
import com.gmail.justbru00.epic.rename.commands.v3.RemoveLoreLine;
import com.gmail.justbru00.epic.rename.commands.v3.Rename;
import com.gmail.justbru00.epic.rename.commands.v3.SetLoreLine;
import com.gmail.justbru00.epic.rename.enums.v3.MCVersion;
import com.gmail.justbru00.epic.rename.listeners.v3.OnJoin;
import com.gmail.justbru00.epic.rename.main.v3.Metrics.Graph;
import com.gmail.justbru00.epic.rename.main.v3.bstats.BStats;
import com.gmail.justbru00.epic.rename.utils.v3.Debug;
import com.gmail.justbru00.epic.rename.utils.v3.Messager;
import com.gmail.justbru00.epic.rename.utils.v3.PluginFile;
import net.milkbowl.vault.economy.Economy;
public class Main extends JavaPlugin {
public static boolean debug = false;
public static String PLUGIN_VERISON = null;
/**
* Default to the method for getting items in hand for MC version 1.9.x+
*/
public static boolean USE_NEW_GET_HAND = true;
/**
* Version is set in checkServerVerison()
*/
public static MCVersion MC_VERSION;
public static Main plugin;
public static PluginFile messages = null;
/**
* Vault economy.
*/
public static Economy econ = null;
public static boolean USE_ECO = false;
public static final int CONFIG_VERSION = 6;
public static final int MESSAGES_VERSION = 9;
public static ConsoleCommandSender clogger = Bukkit.getServer().getConsoleSender();
public static Logger log = Bukkit.getLogger();
public static String prefix = Messager.color("&8[&bEpic&fRename&8] &f");
@Override
public void onDisable() {
Messager.msgConsole("&cPlugin Disabled.");
plugin = null; // Fix memory leak.
}
@Override
public void onEnable() {
plugin = this;
this.saveDefaultConfig();
messages = new PluginFile(this, "messages.yml", "messages.yml");
PLUGIN_VERISON = Main.getInstance().getDescription().getVersion();
checkServerVerison();
Messager.msgConsole("&bVersion: &c" + PLUGIN_VERISON + " &bMC Version: &c" + MC_VERSION.toString());
Messager.msgConsole("&cThis plugin is Copyright (c) " + Calendar.getInstance().get(Calendar.YEAR)
+ " Justin \"JustBru00\" Brubaker. This plugin is licensed under the MPL v2.0. "
+ "You can view a copy of it at: http://bit.ly/2eMknxx");
Messager.msgConsole("&aStarting to enable plugin...");
checkConfigVersions();
if (Main.getInstance().getConfig().getBoolean("economy.use")) {
USE_ECO = true;
Messager.msgConsole("&aEconomy is enabled in the config.");
}
if (!setupEconomy()) {
// Message now handled in setupEconomy()
Messager.msgConsole("&cDisabling support for economy features.");
USE_ECO = false;
}
// Register Listeners
Bukkit.getServer().getPluginManager().registerEvents(new OnJoin(), this);
// Command Executors
getCommand("rename").setExecutor(new Rename());
getCommand("epicrename").setExecutor(new EpicRename());
getCommand("lore").setExecutor(new Lore());
getCommand("setloreline").setExecutor(new SetLoreLine());
getCommand("removeloreline").setExecutor(new RemoveLoreLine());
getCommand("glow").setExecutor(new Glow());
getCommand("removeglow").setExecutor(new RemoveGlow());
getCommand("import").setExecutor(new Import());;
getCommand("export").setExecutor(new Export());
// Start Metrics
try {
Metrics metrics = new Metrics(plugin);
Graph ecoEnabledGraph = metrics.createGraph("Economy Features");
ecoEnabledGraph.addPlotter(new Metrics.Plotter("Enabled") {
@Override
public int getValue() {
if (Main.USE_ECO) {
return 1; // True
} else {
return 0; // False
}
}
});
ecoEnabledGraph.addPlotter(new Metrics.Plotter("Disabled") {
@Override
public int getValue() {
if (Main.USE_ECO) {
return 0; // True
} else {
return 1; // False
}
}
});
metrics.start();
} catch (IOException e) {
Messager.msgConsole("&cMCSTATS FAILED TO SUBMIT STATS.");
}
// Start bstats
BStats bstats = new BStats(this);
bstats.addCustomChart(new BStats.SimplePie("economy_features") {
@Override
public String getValue() {
return Boolean.toString(Main.USE_ECO);
}
});
// Prefix
if (Main.getInstance().getConfig().getString("prefix") != null) {
prefix = Messager.color(Main.getInstance().getConfig().getString("prefix"));
} else {
Messager.msgConsole("&cThe prefix in the config is null. Keeping default instead.");
}
Messager.msgConsole("&aPrefix set to: '" + prefix + "&a'");
Messager.msgConsole("&aPlugin Enabled!");
}
/**
*
* @param path
* Path to the message in messages.yml
* @return The colored string from messages.yml
*/
public static String getMsgFromConfig(String path) {
if (messages.getString(path) == null) {
Debug.send("[Main#getMsgFromConfig()] A message from messages.yml was NULL. The path to the message is: " + path);
return "[ERROR] Message from config is null. Ask a server admin to enable /epicrename debug to find the broken value. [ERROR]";
}
return messages.getString(path); // Removed duplicate Messager.color(); Messager#msgXXXX colors the message.
}
public static boolean getBooleanFromConfig(String path) {
return Main.getInstance().getConfig().getBoolean(path);
}
public static Main getInstance() {
return plugin;
}
public static void reloadConfigs() {
getInstance().reloadConfig();
messages.reload();
if (Main.getInstance().getConfig().getBoolean("economy.use")) {
USE_ECO = true;
Messager.msgConsole("&aEconomy is enabled in the config.");
}
}
public static void checkServerVerison() {
// Check Server Version
if ((Bukkit.getVersion().contains("1.7")) || (Bukkit.getVersion().contains("1.8"))) {
USE_NEW_GET_HAND = false;
MC_VERSION = MCVersion.OLDER_THAN_ONE_DOT_NINE;
Debug.send("[Main#checkServerVersion()] Using methods for version 1.7 or 1.8");
} else if ((Bukkit.getVersion().contains("1.9")) || (Bukkit.getVersion().contains("1.10"))
|| (Bukkit.getVersion().contains("1.11")) || Bukkit.getVersion().contains("1.12") ||
Bukkit.getVersion().contains("1.13") || Bukkit.getVersion().contains("1.14")) {
USE_NEW_GET_HAND = true;
MC_VERSION = MCVersion.NEWER_THAN_ONE_DOT_EIGHT;
Debug.send("[Main#checkServerVersion()] Using methods for version 1.9+");
} else {
USE_NEW_GET_HAND = true;
MC_VERSION = MCVersion.NEWER_THAN_ONE_DOT_EIGHT;
Messager.msgConsole("[Main#checkServerVersion()] Server running unknown version. Assuming newer than 1.13");
} // End of Server Version Check
}
public static void checkConfigVersions() {
if (getInstance().getConfig().getInt("config_version") != CONFIG_VERSION) {
Messager.msgConsole(
"&cWARNING -> config.yml is outdated. Please delete it and restart the server. The plugin may not work as intended.");
}
if (messages.getInt("messages_yml_version") != MESSAGES_VERSION) {
Messager.msgConsole(
"&cWARNING -> messages.yml is outdated. Please delete it and restart the server. The plugin may not work as intended.");
}
}
/**
* Sets up vault economy.
*
* @return
*/
private boolean setupEconomy() {
if (getServer().getPluginManager().getPlugin("Vault") == null) {
Messager.msgConsole("&cVault not found! If you would like to use economy features download Vault at: "
+ "http://dev.bukkit.org/bukkit-plugins/vault/");
return false;
}
RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null) {
Messager.msgConsole("&cFailed to get the economy details from Vault. Is there a Vault compatible economy plugin installed?");
return false;
}
econ = rsp.getProvider();
return econ != null;
}
}
|
src/com/gmail/justbru00/epic/rename/main/v3/Main.java
|
/**
* @author Justin "JustBru00" Brubaker
*
* This is licensed under the MPL Version 2.0. See license info in LICENSE.txt
*/
package com.gmail.justbru00.epic.rename.main.v3;
import java.io.IOException;
import java.util.Calendar;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import com.gmail.justbru00.epic.rename.commands.v3.EpicRename;
import com.gmail.justbru00.epic.rename.commands.v3.Export;
import com.gmail.justbru00.epic.rename.commands.v3.Glow;
import com.gmail.justbru00.epic.rename.commands.v3.Import;
import com.gmail.justbru00.epic.rename.commands.v3.Lore;
import com.gmail.justbru00.epic.rename.commands.v3.RemoveGlow;
import com.gmail.justbru00.epic.rename.commands.v3.RemoveLoreLine;
import com.gmail.justbru00.epic.rename.commands.v3.Rename;
import com.gmail.justbru00.epic.rename.commands.v3.SetLoreLine;
import com.gmail.justbru00.epic.rename.enums.v3.MCVersion;
import com.gmail.justbru00.epic.rename.listeners.v3.OnJoin;
import com.gmail.justbru00.epic.rename.main.v3.Metrics.Graph;
import com.gmail.justbru00.epic.rename.main.v3.bstats.BStats;
import com.gmail.justbru00.epic.rename.utils.v3.Debug;
import com.gmail.justbru00.epic.rename.utils.v3.Messager;
import com.gmail.justbru00.epic.rename.utils.v3.PluginFile;
import net.milkbowl.vault.economy.Economy;
public class Main extends JavaPlugin {
public static boolean debug = false;
public static String PLUGIN_VERISON = null;
/**
* Default to the method for getting items in hand for MC version 1.9.x+
*/
public static boolean USE_NEW_GET_HAND = true;
/**
* Version is set in checkServerVerison()
*/
public static MCVersion MC_VERSION;
public static Main plugin;
public static PluginFile messages = null;
/**
* Vault economy.
*/
public static Economy econ = null;
public static boolean USE_ECO = false;
public static final int CONFIG_VERSION = 6;
public static final int MESSAGES_VERSION = 9;
public static ConsoleCommandSender clogger = Bukkit.getServer().getConsoleSender();
public static Logger log = Bukkit.getLogger();
public static String prefix = Messager.color("&8[&bEpic&fRename&8] &f");
@Override
public void onDisable() {
Messager.msgConsole("&cPlugin Disabled.");
plugin = null; // Fix memory leak.
}
@Override
public void onEnable() {
plugin = this;
this.saveDefaultConfig();
messages = new PluginFile(this, "messages.yml", "messages.yml");
PLUGIN_VERISON = Main.getInstance().getDescription().getVersion();
checkServerVerison();
Messager.msgConsole("&bVersion: &c" + PLUGIN_VERISON + " &bMC Version: &c" + MC_VERSION.toString());
Messager.msgConsole("&cThis plugin is Copyright (c) " + Calendar.getInstance().get(Calendar.YEAR)
+ " Justin \"JustBru00\" Brubaker. This plugin is licensed under the MPL v2.0. "
+ "You can view a copy of it at: http://bit.ly/2eMknxx");
Messager.msgConsole("&aStarting to enable plugin...");
checkConfigVersions();
if (Main.getInstance().getConfig().getBoolean("economy.use")) {
USE_ECO = true;
Messager.msgConsole("&aEconomy is enabled in the config.");
}
if (!setupEconomy()) {
// Message now handled in setupEconomy()
Messager.msgConsole("&cDisabling support for economy features.");
USE_ECO = false;
}
// Register Listeners
Bukkit.getServer().getPluginManager().registerEvents(new OnJoin(), this);
// Command Executors
getCommand("rename").setExecutor(new Rename());
getCommand("epicrename").setExecutor(new EpicRename());
getCommand("lore").setExecutor(new Lore());
getCommand("setloreline").setExecutor(new SetLoreLine());
getCommand("removeloreline").setExecutor(new RemoveLoreLine());
getCommand("glow").setExecutor(new Glow());
getCommand("removeglow").setExecutor(new RemoveGlow());
getCommand("import").setExecutor(new Import());;
getCommand("export").setExecutor(new Export());
// Start Metrics
try {
Metrics metrics = new Metrics(plugin);
Graph ecoEnabledGraph = metrics.createGraph("Economy Features");
ecoEnabledGraph.addPlotter(new Metrics.Plotter("Enabled") {
@Override
public int getValue() {
if (Main.USE_ECO) {
return 1; // True
} else {
return 0; // False
}
}
});
ecoEnabledGraph.addPlotter(new Metrics.Plotter("Disabled") {
@Override
public int getValue() {
if (Main.USE_ECO) {
return 0; // True
} else {
return 1; // False
}
}
});
metrics.start();
} catch (IOException e) {
Messager.msgConsole("&cMCSTATS FAILED TO SUBMIT STATS.");
}
// Start bstats
BStats bstats = new BStats(this);
bstats.addCustomChart(new BStats.SimplePie("economy_features") {
@Override
public String getValue() {
return Boolean.toString(Main.USE_ECO);
}
});
// Prefix
if (Main.getInstance().getConfig().getString("prefix") != null) {
prefix = Messager.color(Main.getInstance().getConfig().getString("prefix"));
} else {
Messager.msgConsole("&cThe prefix in the config is null. Keeping default instead.");
}
Messager.msgConsole("&aPrefix set to: '" + prefix + "&a'");
Messager.msgConsole("&aPlugin Enabled!");
}
/**
*
* @param path
* Path to the message in messages.yml
* @return The colored string from messages.yml
*/
public static String getMsgFromConfig(String path) {
if (messages.getString(path) == null) {
Debug.send("[Main#getMsgFromConfig()] A message from messages.yml was NULL. The path to the message is: " + path);
return "[ERROR] Message from config is null. Ask a server admin to enable /epicrename debug to find the broken value. [ERROR]";
}
return messages.getString(path); // Removed duplicate Messager.color(); Messager#msgXXXX colors the message.
}
public static boolean getBooleanFromConfig(String path) {
return Main.getInstance().getConfig().getBoolean(path);
}
public static Main getInstance() {
return plugin;
}
public static void reloadConfigs() {
getInstance().reloadConfig();
messages.reload();
if (Main.getInstance().getConfig().getBoolean("economy.use")) {
USE_ECO = true;
Messager.msgConsole("&aEconomy is enabled in the config.");
}
}
public static void checkServerVerison() {
// Check Server Version
if ((Bukkit.getVersion().contains("1.7")) || (Bukkit.getVersion().contains("1.8"))) {
USE_NEW_GET_HAND = false;
MC_VERSION = MCVersion.OLDER_THAN_ONE_DOT_NINE;
Debug.send("[Main#checkServerVersion()] Using methods for version 1.7 or 1.8");
} else if ((Bukkit.getVersion().contains("1.9")) || (Bukkit.getVersion().contains("1.10"))
|| (Bukkit.getVersion().contains("1.11")) || Bukkit.getVersion().contains("1.12") || Bukkit.getVersion().contains("1.13")) {
USE_NEW_GET_HAND = true;
MC_VERSION = MCVersion.NEWER_THAN_ONE_DOT_EIGHT;
Debug.send("[Main#checkServerVersion()] Using methods for version 1.9+");
} else {
USE_NEW_GET_HAND = true;
MC_VERSION = MCVersion.NEWER_THAN_ONE_DOT_EIGHT;
Messager.msgConsole("[Main#checkServerVersion()] Server running unknown version. Assuming newer than 1.13");
} // End of Server Version Check
}
public static void checkConfigVersions() {
if (getInstance().getConfig().getInt("config_version") != CONFIG_VERSION) {
Messager.msgConsole(
"&cWARNING -> config.yml is outdated. Please delete it and restart the server. The plugin may not work as intended.");
}
if (messages.getInt("messages_yml_version") != MESSAGES_VERSION) {
Messager.msgConsole(
"&cWARNING -> messages.yml is outdated. Please delete it and restart the server. The plugin may not work as intended.");
}
}
/**
* Sets up vault economy.
*
* @return
*/
private boolean setupEconomy() {
if (getServer().getPluginManager().getPlugin("Vault") == null) {
Messager.msgConsole("&cVault not found! If you would like to use economy features download Vault at: "
+ "http://dev.bukkit.org/bukkit-plugins/vault/");
return false;
}
RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null) {
Messager.msgConsole("&cFailed to get the economy details from Vault. Is there a Vault compatible economy plugin installed?");
return false;
}
econ = rsp.getProvider();
return econ != null;
}
}
|
/export
|
src/com/gmail/justbru00/epic/rename/main/v3/Main.java
|
/export
|
|
Java
|
mpl-2.0
|
34195982cb52661e5498ff880dd7b5b5b3230790
| 0
|
AlexTrotsenko/rhino,qhanam/rhino,tuchida/rhino,sam/htmlunit-rhino-fork,Angelfirenze/rhino,sainaen/rhino,jsdoc3/rhino,sam/htmlunit-rhino-fork,Pilarbrist/rhino,Angelfirenze/rhino,Angelfirenze/rhino,Pilarbrist/rhino,swannodette/rhino,qhanam/rhino,jsdoc3/rhino,lv7777/egit_test,tejassaoji/RhinoCoarseTainting,Distrotech/rhino,tntim96/rhino-apigee,Angelfirenze/rhino,lv7777/egit_test,swannodette/rhino,sainaen/rhino,tejassaoji/RhinoCoarseTainting,rasmuserik/rhino,Pilarbrist/rhino,tntim96/rhino-apigee,swannodette/rhino,sam/htmlunit-rhino-fork,tntim96/htmlunit-rhino-fork,Pilarbrist/rhino,Distrotech/rhino,AlexTrotsenko/rhino,Angelfirenze/rhino,sainaen/rhino,tejassaoji/RhinoCoarseTainting,tntim96/rhino-jscover,AlexTrotsenko/rhino,sam/htmlunit-rhino-fork,swannodette/rhino,tntim96/rhino-jscover-repackaged,tntim96/rhino-apigee,swannodette/rhino,AlexTrotsenko/rhino,sam/htmlunit-rhino-fork,ashwinrayaprolu1984/rhino,sainaen/rhino,AlexTrotsenko/rhino,sainaen/rhino,sainaen/rhino,ashwinrayaprolu1984/rhino,tuchida/rhino,lv7777/egit_test,Angelfirenze/rhino,swannodette/rhino,AlexTrotsenko/rhino,tntim96/htmlunit-rhino-fork,ashwinrayaprolu1984/rhino,tntim96/rhino-jscover,tejassaoji/RhinoCoarseTainting,Pilarbrist/rhino,lv7777/egit_test,lv7777/egit_test,Pilarbrist/rhino,ashwinrayaprolu1984/rhino,sam/htmlunit-rhino-fork,tuchida/rhino,tejassaoji/RhinoCoarseTainting,ashwinrayaprolu1984/rhino,tuchida/rhino,tntim96/rhino-jscover-repackaged,lv7777/egit_test,rasmuserik/rhino,tuchida/rhino,AlexTrotsenko/rhino,Pilarbrist/rhino,ashwinrayaprolu1984/rhino,tuchida/rhino,swannodette/rhino,qhanam/rhino,jsdoc3/rhino,Angelfirenze/rhino,tejassaoji/RhinoCoarseTainting,ashwinrayaprolu1984/rhino,tuchida/rhino,InstantWebP2P/rhino-android,sainaen/rhino,sam/htmlunit-rhino-fork,tejassaoji/RhinoCoarseTainting,qhanam/rhino,lv7777/egit_test,InstantWebP2P/rhino-android
|
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Igor Bukanov
* Daniel Gredler
* Bob Jervis
* Roger Lawrence
* Cameron McCormack
* Steve Weiss
* Hannes Wallnoefer
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
// API class
package org.mozilla.javascript;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.mozilla.javascript.debug.DebuggableObject;
import org.mozilla.javascript.annotations.JSConstructor;
import org.mozilla.javascript.annotations.JSFunction;
import org.mozilla.javascript.annotations.JSGetter;
import org.mozilla.javascript.annotations.JSSetter;
import org.mozilla.javascript.annotations.JSStaticFunction;
/**
* This is the default implementation of the Scriptable interface. This
* class provides convenient default behavior that makes it easier to
* define host objects.
* <p>
* Various properties and methods of JavaScript objects can be conveniently
* defined using methods of ScriptableObject.
* <p>
* Classes extending ScriptableObject must define the getClassName method.
*
* @see org.mozilla.javascript.Scriptable
* @author Norris Boyd
*/
public abstract class ScriptableObject implements Scriptable, Serializable,
DebuggableObject,
ConstProperties
{
/**
* The empty property attribute.
*
* Used by getAttributes() and setAttributes().
*
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int EMPTY = 0x00;
/**
* Property attribute indicating assignment to this property is ignored.
*
* @see org.mozilla.javascript.ScriptableObject
* #put(String, Scriptable, Object)
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int READONLY = 0x01;
/**
* Property attribute indicating property is not enumerated.
*
* Only enumerated properties will be returned by getIds().
*
* @see org.mozilla.javascript.ScriptableObject#getIds()
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int DONTENUM = 0x02;
/**
* Property attribute indicating property cannot be deleted.
*
* @see org.mozilla.javascript.ScriptableObject#delete(String)
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int PERMANENT = 0x04;
/**
* Property attribute indicating that this is a const property that has not
* been assigned yet. The first 'const' assignment to the property will
* clear this bit.
*/
public static final int UNINITIALIZED_CONST = 0x08;
public static final int CONST = PERMANENT|READONLY|UNINITIALIZED_CONST;
/**
* The prototype of this object.
*/
private Scriptable prototypeObject;
/**
* The parent scope of this object.
*/
private Scriptable parentScopeObject;
private transient Slot[] slots;
// If count >= 0, it gives number of keys or if count < 0,
// it indicates sealed object where ~count gives number of keys
private int count;
// gateways into the definition-order linked list of slots
private transient Slot firstAdded;
private transient Slot lastAdded;
private volatile Map<Object,Object> associatedValues;
private static final int SLOT_QUERY = 1;
private static final int SLOT_MODIFY = 2;
private static final int SLOT_MODIFY_CONST = 3;
private static final int SLOT_MODIFY_GETTER_SETTER = 4;
private static final int SLOT_CONVERT_ACCESSOR_TO_DATA = 5;
// initial slot array size, must be a power of 2
private static final int INITIAL_SLOT_SIZE = 4;
private boolean isExtensible = true;
private static class Slot implements Serializable
{
private static final long serialVersionUID = -6090581677123995491L;
String name; // This can change due to caching
int indexOrHash;
private volatile short attributes;
transient volatile boolean wasDeleted;
volatile Object value;
transient Slot next; // next in hash table bucket
transient volatile Slot orderedNext; // next in linked list
Slot(String name, int indexOrHash, int attributes)
{
this.name = name;
this.indexOrHash = indexOrHash;
this.attributes = (short)attributes;
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
if (name != null) {
indexOrHash = name.hashCode();
}
}
boolean setValue(Object value, Scriptable owner, Scriptable start) {
if ((attributes & READONLY) != 0) {
return true;
}
if (owner == start) {
this.value = value;
return true;
} else {
return false;
}
}
Object getValue(Scriptable start) {
return value;
}
int getAttributes()
{
return attributes;
}
synchronized void setAttributes(int value)
{
checkValidAttributes(value);
attributes = (short)value;
}
void markDeleted() {
wasDeleted = true;
value = null;
name = null;
}
ScriptableObject getPropertyDescriptor(Context cx, Scriptable scope) {
return buildDataDescriptor(
scope,
(value == null ? Undefined.instance : value),
attributes);
}
}
protected static ScriptableObject buildDataDescriptor(Scriptable scope,
Object value,
int attributes) {
ScriptableObject desc = new NativeObject();
ScriptRuntime.setBuiltinProtoAndParent(desc, scope, TopLevel.Builtins.Object);
desc.defineProperty("value", value, EMPTY);
desc.defineProperty("writable", (attributes & READONLY) == 0, EMPTY);
desc.defineProperty("enumerable", (attributes & DONTENUM) == 0, EMPTY);
desc.defineProperty("configurable", (attributes & PERMANENT) == 0, EMPTY);
return desc;
}
private static final class GetterSlot extends Slot
{
static final long serialVersionUID = -4900574849788797588L;
Object getter;
Object setter;
GetterSlot(String name, int indexOrHash, int attributes)
{
super(name, indexOrHash, attributes);
}
@Override
ScriptableObject getPropertyDescriptor(Context cx, Scriptable scope) {
int attr = getAttributes();
ScriptableObject desc = new NativeObject();
ScriptRuntime.setBuiltinProtoAndParent(desc, scope, TopLevel.Builtins.Object);
desc.defineProperty("enumerable", (attr & DONTENUM) == 0, EMPTY);
desc.defineProperty("configurable", (attr & PERMANENT) == 0, EMPTY);
if (getter != null) desc.defineProperty("get", getter, EMPTY);
if (setter != null) desc.defineProperty("set", setter, EMPTY);
return desc;
}
@Override
boolean setValue(Object value, Scriptable owner, Scriptable start) {
if (setter == null) {
if (getter != null) {
if (Context.getContext().hasFeature(Context.FEATURE_STRICT_MODE)) {
// Based on TC39 ES3.1 Draft of 9-Feb-2009, 8.12.4, step 2,
// we should throw a TypeError in this case.
throw ScriptRuntime.typeError1("msg.set.prop.no.setter", name);
}
// Assignment to a property with only a getter defined. The
// assignment is ignored. See bug 478047.
return true;
}
} else {
Context cx = Context.getContext();
if (setter instanceof MemberBox) {
MemberBox nativeSetter = (MemberBox)setter;
Class<?> pTypes[] = nativeSetter.argTypes;
// XXX: cache tag since it is already calculated in
// defineProperty ?
Class<?> valueType = pTypes[pTypes.length - 1];
int tag = FunctionObject.getTypeTag(valueType);
Object actualArg = FunctionObject.convertArg(cx, start,
value, tag);
Object setterThis;
Object[] args;
if (nativeSetter.delegateTo == null) {
setterThis = start;
args = new Object[] { actualArg };
} else {
setterThis = nativeSetter.delegateTo;
args = new Object[] { start, actualArg };
}
nativeSetter.invoke(setterThis, args);
} else if (setter instanceof Function) {
Function f = (Function)setter;
f.call(cx, f.getParentScope(), start,
new Object[] { value });
}
return true;
}
return super.setValue(value, owner, start);
}
@Override
Object getValue(Scriptable start) {
if (getter != null) {
if (getter instanceof MemberBox) {
MemberBox nativeGetter = (MemberBox)getter;
Object getterThis;
Object[] args;
if (nativeGetter.delegateTo == null) {
getterThis = start;
args = ScriptRuntime.emptyArgs;
} else {
getterThis = nativeGetter.delegateTo;
args = new Object[] { start };
}
return nativeGetter.invoke(getterThis, args);
} else if (getter instanceof Function) {
Function f = (Function)getter;
Context cx = Context.getContext();
return f.call(cx, f.getParentScope(), start,
ScriptRuntime.emptyArgs);
}
}
Object val = this.value;
if (val instanceof LazilyLoadedCtor) {
LazilyLoadedCtor initializer = (LazilyLoadedCtor)val;
try {
initializer.init();
} finally {
this.value = val = initializer.getValue();
}
}
return val;
}
@Override
void markDeleted() {
super.markDeleted();
getter = null;
setter = null;
}
}
/**
* A wrapper around a slot that allows the slot to be used in a new slot
* table while keeping it functioning in its old slot table/linked list
* context. This is used when linked slots are copied to a new slot table.
* In a multi-threaded environment, these slots may still be accessed
* through their old slot table. See bug 688458.
*/
private static class RelinkedSlot extends Slot {
final Slot slot;
RelinkedSlot(Slot slot) {
super(slot.name, slot.indexOrHash, slot.attributes);
// Make sure we always wrap the actual slot, not another relinked one
this.slot = unwrapSlot(slot);
}
@Override
boolean setValue(Object value, Scriptable owner, Scriptable start) {
return slot.setValue(value, owner, start);
}
@Override
Object getValue(Scriptable start) {
return slot.getValue(start);
}
@Override
ScriptableObject getPropertyDescriptor(Context cx, Scriptable scope) {
return slot.getPropertyDescriptor(cx, scope);
}
@Override
int getAttributes() {
return slot.getAttributes();
}
@Override
void setAttributes(int value) {
slot.setAttributes(value);
}
@Override
void markDeleted() {
super.markDeleted();
slot.markDeleted();
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(slot); // just serialize the wrapped slot
}
}
static void checkValidAttributes(int attributes)
{
final int mask = READONLY | DONTENUM | PERMANENT | UNINITIALIZED_CONST;
if ((attributes & ~mask) != 0) {
throw new IllegalArgumentException(String.valueOf(attributes));
}
}
public ScriptableObject()
{
}
public ScriptableObject(Scriptable scope, Scriptable prototype)
{
if (scope == null)
throw new IllegalArgumentException();
parentScopeObject = scope;
prototypeObject = prototype;
}
/**
* Gets the value that will be returned by calling the typeof operator on this object.
* @return default is "object" unless {@link #avoidObjectDetection()} is <code>true</code> in which
* case it returns "undefined"
*/
public String getTypeOf() {
return avoidObjectDetection() ? "undefined" : "object";
}
/**
* Return the name of the class.
*
* This is typically the same name as the constructor.
* Classes extending ScriptableObject must implement this abstract
* method.
*/
public abstract String getClassName();
/**
* Returns true if the named property is defined.
*
* @param name the name of the property
* @param start the object in which the lookup began
* @return true if and only if the property was found in the object
*/
public boolean has(String name, Scriptable start)
{
return null != getSlot(name, 0, SLOT_QUERY);
}
/**
* Returns true if the property index is defined.
*
* @param index the numeric index for the property
* @param start the object in which the lookup began
* @return true if and only if the property was found in the object
*/
public boolean has(int index, Scriptable start)
{
return null != getSlot(null, index, SLOT_QUERY);
}
/**
* Returns the value of the named property or NOT_FOUND.
*
* If the property was created using defineProperty, the
* appropriate getter method is called.
*
* @param name the name of the property
* @param start the object in which the lookup began
* @return the value of the property (may be null), or NOT_FOUND
*/
public Object get(String name, Scriptable start)
{
Slot slot = getSlot(name, 0, SLOT_QUERY);
if (slot == null) {
return Scriptable.NOT_FOUND;
}
return slot.getValue(start);
}
/**
* Returns the value of the indexed property or NOT_FOUND.
*
* @param index the numeric index for the property
* @param start the object in which the lookup began
* @return the value of the property (may be null), or NOT_FOUND
*/
public Object get(int index, Scriptable start)
{
Slot slot = getSlot(null, index, SLOT_QUERY);
if (slot == null) {
return Scriptable.NOT_FOUND;
}
return slot.getValue(start);
}
/**
* Sets the value of the named property, creating it if need be.
*
* If the property was created using defineProperty, the
* appropriate setter method is called. <p>
*
* If the property's attributes include READONLY, no action is
* taken.
* This method will actually set the property in the start
* object.
*
* @param name the name of the property
* @param start the object whose property is being set
* @param value value to set the property to
*/
public void put(String name, Scriptable start, Object value)
{
if (putImpl(name, 0, start, value))
return;
if (start == this) throw Kit.codeBug();
start.put(name, start, value);
}
/**
* Sets the value of the indexed property, creating it if need be.
*
* @param index the numeric index for the property
* @param start the object whose property is being set
* @param value value to set the property to
*/
public void put(int index, Scriptable start, Object value)
{
if (putImpl(null, index, start, value))
return;
if (start == this) throw Kit.codeBug();
start.put(index, start, value);
}
/**
* Removes a named property from the object.
*
* If the property is not found, or it has the PERMANENT attribute,
* no action is taken.
*
* @param name the name of the property
*/
public void delete(String name)
{
checkNotSealed(name, 0);
removeSlot(name, 0);
}
/**
* Removes the indexed property from the object.
*
* If the property is not found, or it has the PERMANENT attribute,
* no action is taken.
*
* @param index the numeric index for the property
*/
public void delete(int index)
{
checkNotSealed(null, index);
removeSlot(null, index);
}
/**
* Sets the value of the named const property, creating it if need be.
*
* If the property was created using defineProperty, the
* appropriate setter method is called. <p>
*
* If the property's attributes include READONLY, no action is
* taken.
* This method will actually set the property in the start
* object.
*
* @param name the name of the property
* @param start the object whose property is being set
* @param value value to set the property to
*/
public void putConst(String name, Scriptable start, Object value)
{
if (putConstImpl(name, 0, start, value, READONLY))
return;
if (start == this) throw Kit.codeBug();
if (start instanceof ConstProperties)
((ConstProperties)start).putConst(name, start, value);
else
start.put(name, start, value);
}
public void defineConst(String name, Scriptable start)
{
if (putConstImpl(name, 0, start, Undefined.instance, UNINITIALIZED_CONST))
return;
if (start == this) throw Kit.codeBug();
if (start instanceof ConstProperties)
((ConstProperties)start).defineConst(name, start);
}
/**
* Returns true if the named property is defined as a const on this object.
* @param name
* @return true if the named property is defined as a const, false
* otherwise.
*/
public boolean isConst(String name)
{
Slot slot = getSlot(name, 0, SLOT_QUERY);
if (slot == null) {
return false;
}
return (slot.getAttributes() & (PERMANENT|READONLY)) ==
(PERMANENT|READONLY);
}
/**
* @deprecated Use {@link #getAttributes(String name)}. The engine always
* ignored the start argument.
*/
public final int getAttributes(String name, Scriptable start)
{
return getAttributes(name);
}
/**
* @deprecated Use {@link #getAttributes(int index)}. The engine always
* ignored the start argument.
*/
public final int getAttributes(int index, Scriptable start)
{
return getAttributes(index);
}
/**
* @deprecated Use {@link #setAttributes(String name, int attributes)}.
* The engine always ignored the start argument.
*/
public final void setAttributes(String name, Scriptable start,
int attributes)
{
setAttributes(name, attributes);
}
/**
* @deprecated Use {@link #setAttributes(int index, int attributes)}.
* The engine always ignored the start argument.
*/
public void setAttributes(int index, Scriptable start,
int attributes)
{
setAttributes(index, attributes);
}
/**
* Get the attributes of a named property.
*
* The property is specified by <code>name</code>
* as defined for <code>has</code>.<p>
*
* @param name the identifier for the property
* @return the bitset of attributes
* @exception EvaluatorException if the named property is not found
* @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public int getAttributes(String name)
{
return findAttributeSlot(name, 0, SLOT_QUERY).getAttributes();
}
/**
* Get the attributes of an indexed property.
*
* @param index the numeric index for the property
* @exception EvaluatorException if the named property is not found
* is not found
* @return the bitset of attributes
* @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public int getAttributes(int index)
{
return findAttributeSlot(null, index, SLOT_QUERY).getAttributes();
}
/**
* Set the attributes of a named property.
*
* The property is specified by <code>name</code>
* as defined for <code>has</code>.<p>
*
* The possible attributes are READONLY, DONTENUM,
* and PERMANENT. Combinations of attributes
* are expressed by the bitwise OR of attributes.
* EMPTY is the state of no attributes set. Any unused
* bits are reserved for future use.
*
* @param name the name of the property
* @param attributes the bitset of attributes
* @exception EvaluatorException if the named property is not found
* @see org.mozilla.javascript.Scriptable#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public void setAttributes(String name, int attributes)
{
checkNotSealed(name, 0);
findAttributeSlot(name, 0, SLOT_MODIFY).setAttributes(attributes);
}
/**
* Set the attributes of an indexed property.
*
* @param index the numeric index for the property
* @param attributes the bitset of attributes
* @exception EvaluatorException if the named property is not found
* @see org.mozilla.javascript.Scriptable#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public void setAttributes(int index, int attributes)
{
checkNotSealed(null, index);
findAttributeSlot(null, index, SLOT_MODIFY).setAttributes(attributes);
}
/**
* XXX: write docs.
*/
public void setGetterOrSetter(String name, int index,
Callable getterOrSetter, boolean isSetter)
{
setGetterOrSetter(name, index, getterOrSetter, isSetter, false);
}
private void setGetterOrSetter(String name, int index, Callable getterOrSetter,
boolean isSetter, boolean force)
{
if (name != null && index != 0)
throw new IllegalArgumentException(name);
if (!force) {
checkNotSealed(name, index);
}
final GetterSlot gslot;
if (isExtensible()) {
gslot = (GetterSlot)getSlot(name, index, SLOT_MODIFY_GETTER_SETTER);
} else {
Slot slot = unwrapSlot(getSlot(name, index, SLOT_QUERY));
if (!(slot instanceof GetterSlot))
return;
gslot = (GetterSlot) slot;
}
if (!force) {
int attributes = gslot.getAttributes();
if ((attributes & READONLY) != 0) {
throw Context.reportRuntimeError1("msg.modify.readonly", name);
}
}
if (isSetter) {
gslot.setter = getterOrSetter;
} else {
gslot.getter = getterOrSetter;
}
gslot.value = Undefined.instance;
}
/**
* Get the getter or setter for a given property. Used by __lookupGetter__
* and __lookupSetter__.
*
* @param name Name of the object. If nonnull, index must be 0.
* @param index Index of the object. If nonzero, name must be null.
* @param isSetter If true, return the setter, otherwise return the getter.
* @exception IllegalArgumentException if both name and index are nonnull
* and nonzero respectively.
* @return Null if the property does not exist. Otherwise returns either
* the getter or the setter for the property, depending on
* the value of isSetter (may be undefined if unset).
*/
public Object getGetterOrSetter(String name, int index, boolean isSetter)
{
if (name != null && index != 0)
throw new IllegalArgumentException(name);
Slot slot = unwrapSlot(getSlot(name, index, SLOT_QUERY));
if (slot == null)
return null;
if (slot instanceof GetterSlot) {
GetterSlot gslot = (GetterSlot)slot;
Object result = isSetter ? gslot.setter : gslot.getter;
return result != null ? result : Undefined.instance;
} else
return Undefined.instance;
}
/**
* Returns whether a property is a getter or a setter
* @param name property name
* @param index property index
* @param setter true to check for a setter, false for a getter
* @return whether the property is a getter or a setter
*/
protected boolean isGetterOrSetter(String name, int index, boolean setter) {
Slot slot = unwrapSlot(getSlot(name, index, SLOT_QUERY));
if (slot instanceof GetterSlot) {
if (setter && ((GetterSlot)slot).setter != null) return true;
if (!setter && ((GetterSlot)slot).getter != null) return true;
}
return false;
}
void addLazilyInitializedValue(String name, int index,
LazilyLoadedCtor init, int attributes)
{
if (name != null && index != 0)
throw new IllegalArgumentException(name);
checkNotSealed(name, index);
GetterSlot gslot = (GetterSlot)getSlot(name, index,
SLOT_MODIFY_GETTER_SETTER);
gslot.setAttributes(attributes);
gslot.getter = null;
gslot.setter = null;
gslot.value = init;
}
/**
* Returns the prototype of the object.
*/
public Scriptable getPrototype()
{
return prototypeObject;
}
/**
* Sets the prototype of the object.
*/
public void setPrototype(Scriptable m)
{
prototypeObject = m;
}
/**
* Returns the parent (enclosing) scope of the object.
*/
public Scriptable getParentScope()
{
return parentScopeObject;
}
/**
* Sets the parent (enclosing) scope of the object.
*/
public void setParentScope(Scriptable m)
{
parentScopeObject = m;
}
/**
* Returns an array of ids for the properties of the object.
*
* <p>Any properties with the attribute DONTENUM are not listed. <p>
*
* @return an array of java.lang.Objects with an entry for every
* listed property. Properties accessed via an integer index will
* have a corresponding
* Integer entry in the returned array. Properties accessed by
* a String will have a String entry in the returned array.
*/
public Object[] getIds() {
return getIds(false);
}
/**
* Returns an array of ids for the properties of the object.
*
* <p>All properties, even those with attribute DONTENUM, are listed. <p>
*
* @return an array of java.lang.Objects with an entry for every
* listed property. Properties accessed via an integer index will
* have a corresponding
* Integer entry in the returned array. Properties accessed by
* a String will have a String entry in the returned array.
*/
public Object[] getAllIds() {
return getIds(true);
}
/**
* Implements the [[DefaultValue]] internal method.
*
* <p>Note that the toPrimitive conversion is a no-op for
* every type other than Object, for which [[DefaultValue]]
* is called. See ECMA 9.1.<p>
*
* A <code>hint</code> of null means "no hint".
*
* @param typeHint the type hint
* @return the default value for the object
*
* See ECMA 8.6.2.6.
*/
public Object getDefaultValue(Class<?> typeHint)
{
return getDefaultValue(this, typeHint);
}
public static Object getDefaultValue(Scriptable object, Class<?> typeHint)
{
Context cx = null;
for (int i=0; i < 2; i++) {
boolean tryToString;
if (typeHint == ScriptRuntime.StringClass) {
tryToString = (i == 0);
} else {
tryToString = (i == 1);
}
String methodName;
Object[] args;
if (tryToString) {
methodName = "toString";
args = ScriptRuntime.emptyArgs;
} else {
methodName = "valueOf";
args = new Object[1];
String hint;
if (typeHint == null) {
hint = "undefined";
} else if (typeHint == ScriptRuntime.StringClass) {
hint = "string";
} else if (typeHint == ScriptRuntime.ScriptableClass) {
hint = "object";
} else if (typeHint == ScriptRuntime.FunctionClass) {
hint = "function";
} else if (typeHint == ScriptRuntime.BooleanClass
|| typeHint == Boolean.TYPE)
{
hint = "boolean";
} else if (typeHint == ScriptRuntime.NumberClass ||
typeHint == ScriptRuntime.ByteClass ||
typeHint == Byte.TYPE ||
typeHint == ScriptRuntime.ShortClass ||
typeHint == Short.TYPE ||
typeHint == ScriptRuntime.IntegerClass ||
typeHint == Integer.TYPE ||
typeHint == ScriptRuntime.FloatClass ||
typeHint == Float.TYPE ||
typeHint == ScriptRuntime.DoubleClass ||
typeHint == Double.TYPE)
{
hint = "number";
} else {
throw Context.reportRuntimeError1(
"msg.invalid.type", typeHint.toString());
}
args[0] = hint;
}
Object v = getProperty(object, methodName);
if (!(v instanceof Function))
continue;
Function fun = (Function) v;
if (cx == null)
cx = Context.getContext();
v = fun.call(cx, fun.getParentScope(), object, args);
if (v != null) {
if (!(v instanceof Scriptable)) {
return v;
}
if (typeHint == ScriptRuntime.ScriptableClass
|| typeHint == ScriptRuntime.FunctionClass)
{
return v;
}
if (tryToString && v instanceof Wrapper) {
// Let a wrapped java.lang.String pass for a primitive
// string.
Object u = ((Wrapper)v).unwrap();
if (u instanceof String)
return u;
}
}
}
// fall through to error
String arg = (typeHint == null) ? "undefined" : typeHint.getName();
throw ScriptRuntime.typeError1("msg.default.value", arg);
}
/**
* Implements the instanceof operator.
*
* <p>This operator has been proposed to ECMA.
*
* @param instance The value that appeared on the LHS of the instanceof
* operator
* @return true if "this" appears in value's prototype chain
*
*/
public boolean hasInstance(Scriptable instance) {
// Default for JS objects (other than Function) is to do prototype
// chasing. This will be overridden in NativeFunction and non-JS
// objects.
return ScriptRuntime.jsDelegatesTo(instance, this);
}
/**
* Emulate the SpiderMonkey (and Firefox) feature of allowing
* custom objects to avoid detection by normal "object detection"
* code patterns. This is used to implement document.all.
* See https://bugzilla.mozilla.org/show_bug.cgi?id=412247.
* This is an analog to JOF_DETECTING from SpiderMonkey; see
* https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
* Other than this special case, embeddings should return false.
* @return true if this object should avoid object detection
* @since 1.7R1
*/
public boolean avoidObjectDetection() {
return false;
}
/**
* Custom <tt>==</tt> operator.
* Must return {@link Scriptable#NOT_FOUND} if this object does not
* have custom equality operator for the given value,
* <tt>Boolean.TRUE</tt> if this object is equivalent to <tt>value</tt>,
* <tt>Boolean.FALSE</tt> if this object is not equivalent to
* <tt>value</tt>.
* <p>
* The default implementation returns Boolean.TRUE
* if <tt>this == value</tt> or {@link Scriptable#NOT_FOUND} otherwise.
* It indicates that by default custom equality is available only if
* <tt>value</tt> is <tt>this</tt> in which case true is returned.
*/
protected Object equivalentValues(Object value)
{
return (this == value) ? Boolean.TRUE : Scriptable.NOT_FOUND;
}
/**
* Defines JavaScript objects from a Java class that implements Scriptable.
*
* If the given class has a method
* <pre>
* static void init(Context cx, Scriptable scope, boolean sealed);</pre>
*
* or its compatibility form
* <pre>
* static void init(Scriptable scope);</pre>
*
* then it is invoked and no further initialization is done.<p>
*
* However, if no such a method is found, then the class's constructors and
* methods are used to initialize a class in the following manner.<p>
*
* First, the zero-parameter constructor of the class is called to
* create the prototype. If no such constructor exists,
* a {@link EvaluatorException} is thrown. <p>
*
* Next, all methods are scanned for special prefixes that indicate that they
* have special meaning for defining JavaScript objects.
* These special prefixes are
* <ul>
* <li><code>jsFunction_</code> for a JavaScript function
* <li><code>jsStaticFunction_</code> for a JavaScript function that
* is a property of the constructor
* <li><code>jsGet_</code> for a getter of a JavaScript property
* <li><code>jsSet_</code> for a setter of a JavaScript property
* <li><code>jsConstructor</code> for a JavaScript function that
* is the constructor
* </ul><p>
*
* If the method's name begins with "jsFunction_", a JavaScript function
* is created with a name formed from the rest of the Java method name
* following "jsFunction_". So a Java method named "jsFunction_foo" will
* define a JavaScript method "foo". Calling this JavaScript function
* will cause the Java method to be called. The parameters of the method
* must be of number and types as defined by the FunctionObject class.
* The JavaScript function is then added as a property
* of the prototype. <p>
*
* If the method's name begins with "jsStaticFunction_", it is handled
* similarly except that the resulting JavaScript function is added as a
* property of the constructor object. The Java method must be static.
*
* If the method's name begins with "jsGet_" or "jsSet_", the method is
* considered to define a property. Accesses to the defined property
* will result in calls to these getter and setter methods. If no
* setter is defined, the property is defined as READONLY.<p>
*
* If the method's name is "jsConstructor", the method is
* considered to define the body of the constructor. Only one
* method of this name may be defined. You may use the varargs forms
* for constructors documented in {@link FunctionObject#FunctionObject(String, Member, Scriptable)}
*
* If no method is found that can serve as constructor, a Java
* constructor will be selected to serve as the JavaScript
* constructor in the following manner. If the class has only one
* Java constructor, that constructor is used to define
* the JavaScript constructor. If the the class has two constructors,
* one must be the zero-argument constructor (otherwise an
* {@link EvaluatorException} would have already been thrown
* when the prototype was to be created). In this case
* the Java constructor with one or more parameters will be used
* to define the JavaScript constructor. If the class has three
* or more constructors, an {@link EvaluatorException}
* will be thrown.<p>
*
* Finally, if there is a method
* <pre>
* static void finishInit(Scriptable scope, FunctionObject constructor,
* Scriptable prototype)</pre>
*
* it will be called to finish any initialization. The <code>scope</code>
* argument will be passed, along with the newly created constructor and
* the newly created prototype.<p>
*
* @param scope The scope in which to define the constructor.
* @param clazz The Java class to use to define the JavaScript objects
* and properties.
* @exception IllegalAccessException if access is not available
* to a reflected class member
* @exception InstantiationException if unable to instantiate
* the named class
* @exception InvocationTargetException if an exception is thrown
* during execution of methods of the named class
* @see org.mozilla.javascript.Function
* @see org.mozilla.javascript.FunctionObject
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject
* #defineProperty(String, Class, int)
*/
public static <T extends Scriptable> void defineClass(
Scriptable scope, Class<T> clazz)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
defineClass(scope, clazz, false, false);
}
/**
* Defines JavaScript objects from a Java class, optionally
* allowing sealing.
*
* Similar to <code>defineClass(Scriptable scope, Class clazz)</code>
* except that sealing is allowed. An object that is sealed cannot have
* properties added or removed. Note that sealing is not allowed in
* the current ECMA/ISO language specification, but is likely for
* the next version.
*
* @param scope The scope in which to define the constructor.
* @param clazz The Java class to use to define the JavaScript objects
* and properties. The class must implement Scriptable.
* @param sealed Whether or not to create sealed standard objects that
* cannot be modified.
* @exception IllegalAccessException if access is not available
* to a reflected class member
* @exception InstantiationException if unable to instantiate
* the named class
* @exception InvocationTargetException if an exception is thrown
* during execution of methods of the named class
* @since 1.4R3
*/
public static <T extends Scriptable> void defineClass(
Scriptable scope, Class<T> clazz, boolean sealed)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
defineClass(scope, clazz, sealed, false);
}
/**
* Defines JavaScript objects from a Java class, optionally
* allowing sealing and mapping of Java inheritance to JavaScript
* prototype-based inheritance.
*
* Similar to <code>defineClass(Scriptable scope, Class clazz)</code>
* except that sealing and inheritance mapping are allowed. An object
* that is sealed cannot have properties added or removed. Note that
* sealing is not allowed in the current ECMA/ISO language specification,
* but is likely for the next version.
*
* @param scope The scope in which to define the constructor.
* @param clazz The Java class to use to define the JavaScript objects
* and properties. The class must implement Scriptable.
* @param sealed Whether or not to create sealed standard objects that
* cannot be modified.
* @param mapInheritance Whether or not to map Java inheritance to
* JavaScript prototype-based inheritance.
* @return the class name for the prototype of the specified class
* @exception IllegalAccessException if access is not available
* to a reflected class member
* @exception InstantiationException if unable to instantiate
* the named class
* @exception InvocationTargetException if an exception is thrown
* during execution of methods of the named class
* @since 1.6R2
*/
public static <T extends Scriptable> String defineClass(
Scriptable scope, Class<T> clazz, boolean sealed,
boolean mapInheritance)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
BaseFunction ctor = buildClassCtor(scope, clazz, sealed,
mapInheritance);
if (ctor == null)
return null;
String name = ctor.getClassPrototype().getClassName();
defineProperty(scope, name, ctor, ScriptableObject.DONTENUM);
return name;
}
static <T extends Scriptable> BaseFunction buildClassCtor(
Scriptable scope, Class<T> clazz,
boolean sealed,
boolean mapInheritance)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
Method[] methods = FunctionObject.getMethodList(clazz);
for (int i=0; i < methods.length; i++) {
Method method = methods[i];
if (!method.getName().equals("init"))
continue;
Class<?>[] parmTypes = method.getParameterTypes();
if (parmTypes.length == 3 &&
parmTypes[0] == ScriptRuntime.ContextClass &&
parmTypes[1] == ScriptRuntime.ScriptableClass &&
parmTypes[2] == Boolean.TYPE &&
Modifier.isStatic(method.getModifiers()))
{
Object args[] = { Context.getContext(), scope,
sealed ? Boolean.TRUE : Boolean.FALSE };
method.invoke(null, args);
return null;
}
if (parmTypes.length == 1 &&
parmTypes[0] == ScriptRuntime.ScriptableClass &&
Modifier.isStatic(method.getModifiers()))
{
Object args[] = { scope };
method.invoke(null, args);
return null;
}
}
// If we got here, there isn't an "init" method with the right
// parameter types.
Constructor<?>[] ctors = clazz.getConstructors();
Constructor<?> protoCtor = null;
for (int i=0; i < ctors.length; i++) {
if (ctors[i].getParameterTypes().length == 0) {
protoCtor = ctors[i];
break;
}
}
if (protoCtor == null) {
throw Context.reportRuntimeError1(
"msg.zero.arg.ctor", clazz.getName());
}
Scriptable proto = (Scriptable) protoCtor.newInstance(ScriptRuntime.emptyArgs);
String className = proto.getClassName();
// Set the prototype's prototype, trying to map Java inheritance to JS
// prototype-based inheritance if requested to do so.
Scriptable superProto = null;
if (mapInheritance) {
Class<? super T> superClass = clazz.getSuperclass();
if (ScriptRuntime.ScriptableClass.isAssignableFrom(superClass) &&
!Modifier.isAbstract(superClass.getModifiers()))
{
Class<? extends Scriptable> superScriptable =
extendsScriptable(superClass);
String name = ScriptableObject.defineClass(scope,
superScriptable, sealed, mapInheritance);
if (name != null) {
superProto = ScriptableObject.getClassPrototype(scope, name);
}
}
}
if (superProto == null) {
superProto = ScriptableObject.getObjectPrototype(scope);
}
proto.setPrototype(superProto);
// Find out whether there are any methods that begin with
// "js". If so, then only methods that begin with special
// prefixes will be defined as JavaScript entities.
final String functionPrefix = "jsFunction_";
final String staticFunctionPrefix = "jsStaticFunction_";
final String getterPrefix = "jsGet_";
final String setterPrefix = "jsSet_";
final String ctorName = "jsConstructor";
Member ctorMember = findAnnotatedMember(methods, JSConstructor.class);
if (ctorMember == null) {
ctorMember = findAnnotatedMember(ctors, JSConstructor.class);
}
if (ctorMember == null) {
ctorMember = FunctionObject.findSingleMethod(methods, ctorName);
}
if (ctorMember == null) {
if (ctors.length == 1) {
ctorMember = ctors[0];
} else if (ctors.length == 2) {
if (ctors[0].getParameterTypes().length == 0)
ctorMember = ctors[1];
else if (ctors[1].getParameterTypes().length == 0)
ctorMember = ctors[0];
}
if (ctorMember == null) {
throw Context.reportRuntimeError1(
"msg.ctor.multiple.parms", clazz.getName());
}
}
FunctionObject ctor = new FunctionObject(className, ctorMember, scope);
if (ctor.isVarArgsMethod()) {
throw Context.reportRuntimeError1
("msg.varargs.ctor", ctorMember.getName());
}
ctor.initAsConstructor(scope, proto);
Method finishInit = null;
HashSet<String> staticNames = new HashSet<String>(),
instanceNames = new HashSet<String>();
for (Method method : methods) {
if (method == ctorMember) {
continue;
}
String name = method.getName();
if (name.equals("finishInit")) {
Class<?>[] parmTypes = method.getParameterTypes();
if (parmTypes.length == 3 &&
parmTypes[0] == ScriptRuntime.ScriptableClass &&
parmTypes[1] == FunctionObject.class &&
parmTypes[2] == ScriptRuntime.ScriptableClass &&
Modifier.isStatic(method.getModifiers()))
{
finishInit = method;
continue;
}
}
// ignore any compiler generated methods.
if (name.indexOf('$') != -1)
continue;
if (name.equals(ctorName))
continue;
Annotation annotation = null;
String prefix = null;
if (method.isAnnotationPresent(JSFunction.class)) {
annotation = method.getAnnotation(JSFunction.class);
} else if (method.isAnnotationPresent(JSStaticFunction.class)) {
annotation = method.getAnnotation(JSStaticFunction.class);
} else if (method.isAnnotationPresent(JSGetter.class)) {
annotation = method.getAnnotation(JSGetter.class);
} else if (method.isAnnotationPresent(JSSetter.class)) {
continue;
}
if (annotation == null) {
if (name.startsWith(functionPrefix)) {
prefix = functionPrefix;
} else if (name.startsWith(staticFunctionPrefix)) {
prefix = staticFunctionPrefix;
} else if (name.startsWith(getterPrefix)) {
prefix = getterPrefix;
} else if (annotation == null) {
// note that setterPrefix is among the unhandled names here -
// we deal with that when we see the getter
continue;
}
}
boolean isStatic = annotation instanceof JSStaticFunction
|| prefix == staticFunctionPrefix;
HashSet<String> names = isStatic ? staticNames : instanceNames;
String propName = getPropertyName(name, prefix, annotation);
if (names.contains(propName)) {
throw Context.reportRuntimeError2("duplicate.defineClass.name",
name, propName);
}
names.add(propName);
name = propName;
if (annotation instanceof JSGetter || prefix == getterPrefix) {
if (!(proto instanceof ScriptableObject)) {
throw Context.reportRuntimeError2(
"msg.extend.scriptable",
proto.getClass().toString(), name);
}
Method setter = findSetterMethod(methods, name, setterPrefix);
int attr = ScriptableObject.PERMANENT |
ScriptableObject.DONTENUM |
(setter != null ? 0
: ScriptableObject.READONLY);
((ScriptableObject) proto).defineProperty(name, null,
method, setter,
attr);
continue;
}
if (isStatic && !Modifier.isStatic(method.getModifiers())) {
throw Context.reportRuntimeError(
"jsStaticFunction must be used with static method.");
}
FunctionObject f = new FunctionObject(name, method, proto);
if (f.isVarArgsConstructor()) {
throw Context.reportRuntimeError1
("msg.varargs.fun", ctorMember.getName());
}
defineProperty(isStatic ? ctor : proto, name, f, DONTENUM);
if (sealed) {
f.sealObject();
}
}
// Call user code to complete initialization if necessary.
if (finishInit != null) {
Object[] finishArgs = { scope, ctor, proto };
finishInit.invoke(null, finishArgs);
}
// Seal the object if necessary.
if (sealed) {
ctor.sealObject();
if (proto instanceof ScriptableObject) {
((ScriptableObject) proto).sealObject();
}
}
return ctor;
}
private static Member findAnnotatedMember(AccessibleObject[] members,
Class<? extends Annotation> annotation) {
for (AccessibleObject member : members) {
if (member.isAnnotationPresent(annotation)) {
return (Member) member;
}
}
return null;
}
private static Method findSetterMethod(Method[] methods,
String name,
String prefix) {
String newStyleName = "set"
+ Character.toUpperCase(name.charAt(0))
+ name.substring(1);
for (Method method : methods) {
JSSetter annotation = method.getAnnotation(JSSetter.class);
if (annotation != null) {
if (name.equals(annotation.value()) ||
("".equals(annotation.value()) && newStyleName.equals(method.getName()))) {
return method;
}
}
}
String oldStyleName = prefix + name;
for (Method method : methods) {
if (oldStyleName.equals(method.getName())) {
return method;
}
}
return null;
}
private static String getPropertyName(String methodName,
String prefix,
Annotation annotation) {
if (prefix != null) {
return methodName.substring(prefix.length());
}
String propName = null;
if (annotation instanceof JSGetter) {
propName = ((JSGetter) annotation).value();
if (propName == null || propName.length() == 0) {
if (methodName.length() > 3 && methodName.startsWith("get")) {
propName = methodName.substring(3);
if (Character.isUpperCase(propName.charAt(0))) {
if (propName.length() == 1) {
propName = propName.toLowerCase();
} else if (!Character.isUpperCase(propName.charAt(1))){
propName = Character.toLowerCase(propName.charAt(0))
+ propName.substring(1);
}
}
}
}
} else if (annotation instanceof JSFunction) {
propName = ((JSFunction) annotation).value();
} else if (annotation instanceof JSStaticFunction) {
propName = ((JSStaticFunction) annotation).value();
}
if (propName == null || propName.length() == 0) {
propName = methodName;
}
return propName;
}
@SuppressWarnings({"unchecked"})
private static <T extends Scriptable> Class<T> extendsScriptable(Class<?> c)
{
if (ScriptRuntime.ScriptableClass.isAssignableFrom(c))
return (Class<T>) c;
return null;
}
/**
* Define a JavaScript property.
*
* Creates the property with an initial value and sets its attributes.
*
* @param propertyName the name of the property to define.
* @param value the initial value of the property
* @param attributes the attributes of the JavaScript property
* @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object)
*/
public void defineProperty(String propertyName, Object value,
int attributes)
{
checkNotSealed(propertyName, 0);
put(propertyName, this, value);
setAttributes(propertyName, attributes);
}
/**
* Utility method to add properties to arbitrary Scriptable object.
* If destination is instance of ScriptableObject, calls
* defineProperty there, otherwise calls put in destination
* ignoring attributes
*/
public static void defineProperty(Scriptable destination,
String propertyName, Object value,
int attributes)
{
if (!(destination instanceof ScriptableObject)) {
destination.put(propertyName, destination, value);
return;
}
ScriptableObject so = (ScriptableObject)destination;
so.defineProperty(propertyName, value, attributes);
}
/**
* Utility method to add properties to arbitrary Scriptable object.
* If destination is instance of ScriptableObject, calls
* defineProperty there, otherwise calls put in destination
* ignoring attributes
*/
public static void defineConstProperty(Scriptable destination,
String propertyName)
{
if (destination instanceof ConstProperties) {
ConstProperties cp = (ConstProperties)destination;
cp.defineConst(propertyName, destination);
} else
defineProperty(destination, propertyName, Undefined.instance, CONST);
}
/**
* Define a JavaScript property with getter and setter side effects.
*
* If the setter is not found, the attribute READONLY is added to
* the given attributes. <p>
*
* The getter must be a method with zero parameters, and the setter, if
* found, must be a method with one parameter.<p>
*
* @param propertyName the name of the property to define. This name
* also affects the name of the setter and getter
* to search for. If the propertyId is "foo", then
* <code>clazz</code> will be searched for "getFoo"
* and "setFoo" methods.
* @param clazz the Java class to search for the getter and setter
* @param attributes the attributes of the JavaScript property
* @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object)
*/
public void defineProperty(String propertyName, Class<?> clazz,
int attributes)
{
int length = propertyName.length();
if (length == 0) throw new IllegalArgumentException();
char[] buf = new char[3 + length];
propertyName.getChars(0, length, buf, 3);
buf[3] = Character.toUpperCase(buf[3]);
buf[0] = 'g';
buf[1] = 'e';
buf[2] = 't';
String getterName = new String(buf);
buf[0] = 's';
String setterName = new String(buf);
Method[] methods = FunctionObject.getMethodList(clazz);
Method getter = FunctionObject.findSingleMethod(methods, getterName);
Method setter = FunctionObject.findSingleMethod(methods, setterName);
if (setter == null)
attributes |= ScriptableObject.READONLY;
defineProperty(propertyName, null, getter,
setter == null ? null : setter, attributes);
}
/**
* Define a JavaScript property.
*
* Use this method only if you wish to define getters and setters for
* a given property in a ScriptableObject. To create a property without
* special getter or setter side effects, use
* <code>defineProperty(String,int)</code>.
*
* If <code>setter</code> is null, the attribute READONLY is added to
* the given attributes.<p>
*
* Several forms of getters or setters are allowed. In all cases the
* type of the value parameter can be any one of the following types:
* Object, String, boolean, Scriptable, byte, short, int, long, float,
* or double. The runtime will perform appropriate conversions based
* upon the type of the parameter (see description in FunctionObject).
* The first forms are nonstatic methods of the class referred to
* by 'this':
* <pre>
* Object getFoo();
* void setFoo(SomeType value);</pre>
* Next are static methods that may be of any class; the object whose
* property is being accessed is passed in as an extra argument:
* <pre>
* static Object getFoo(Scriptable obj);
* static void setFoo(Scriptable obj, SomeType value);</pre>
* Finally, it is possible to delegate to another object entirely using
* the <code>delegateTo</code> parameter. In this case the methods are
* nonstatic methods of the class delegated to, and the object whose
* property is being accessed is passed in as an extra argument:
* <pre>
* Object getFoo(Scriptable obj);
* void setFoo(Scriptable obj, SomeType value);</pre>
*
* @param propertyName the name of the property to define.
* @param delegateTo an object to call the getter and setter methods on,
* or null, depending on the form used above.
* @param getter the method to invoke to get the value of the property
* @param setter the method to invoke to set the value of the property
* @param attributes the attributes of the JavaScript property
*/
public void defineProperty(String propertyName, Object delegateTo,
Method getter, Method setter, int attributes)
{
MemberBox getterBox = null;
if (getter != null) {
getterBox = new MemberBox(getter);
boolean delegatedForm;
if (!Modifier.isStatic(getter.getModifiers())) {
delegatedForm = (delegateTo != null);
getterBox.delegateTo = delegateTo;
} else {
delegatedForm = true;
// Ignore delegateTo for static getter but store
// non-null delegateTo indicator.
getterBox.delegateTo = Void.TYPE;
}
String errorId = null;
Class<?>[] parmTypes = getter.getParameterTypes();
if (parmTypes.length == 0) {
if (delegatedForm) {
errorId = "msg.obj.getter.parms";
}
} else if (parmTypes.length == 1) {
Object argType = parmTypes[0];
// Allow ScriptableObject for compatibility
if (!(argType == ScriptRuntime.ScriptableClass ||
argType == ScriptRuntime.ScriptableObjectClass))
{
errorId = "msg.bad.getter.parms";
} else if (!delegatedForm) {
errorId = "msg.bad.getter.parms";
}
} else {
errorId = "msg.bad.getter.parms";
}
if (errorId != null) {
throw Context.reportRuntimeError1(errorId, getter.toString());
}
}
MemberBox setterBox = null;
if (setter != null) {
if (setter.getReturnType() != Void.TYPE)
throw Context.reportRuntimeError1("msg.setter.return",
setter.toString());
setterBox = new MemberBox(setter);
boolean delegatedForm;
if (!Modifier.isStatic(setter.getModifiers())) {
delegatedForm = (delegateTo != null);
setterBox.delegateTo = delegateTo;
} else {
delegatedForm = true;
// Ignore delegateTo for static setter but store
// non-null delegateTo indicator.
setterBox.delegateTo = Void.TYPE;
}
String errorId = null;
Class<?>[] parmTypes = setter.getParameterTypes();
if (parmTypes.length == 1) {
if (delegatedForm) {
errorId = "msg.setter2.expected";
}
} else if (parmTypes.length == 2) {
Object argType = parmTypes[0];
// Allow ScriptableObject for compatibility
if (!(argType == ScriptRuntime.ScriptableClass ||
argType == ScriptRuntime.ScriptableObjectClass))
{
errorId = "msg.setter2.parms";
} else if (!delegatedForm) {
errorId = "msg.setter1.parms";
}
} else {
errorId = "msg.setter.parms";
}
if (errorId != null) {
throw Context.reportRuntimeError1(errorId, setter.toString());
}
}
GetterSlot gslot = (GetterSlot)getSlot(propertyName, 0,
SLOT_MODIFY_GETTER_SETTER);
gslot.setAttributes(attributes);
gslot.getter = getterBox;
gslot.setter = setterBox;
}
public void defineOwnProperties(Context cx, ScriptableObject props) {
Object[] ids = props.getIds();
for (Object id : ids) {
String name = ScriptRuntime.toString(id);
Object descObj = props.get(id);
ScriptableObject desc = ensureScriptableObject(descObj);
checkValidPropertyDefinition(getSlot(name, 0, SLOT_QUERY), desc);
}
for (Object id : ids) {
String name = ScriptRuntime.toString(id);
ScriptableObject desc = (ScriptableObject) props.get(id);
defineOwnProperty(cx, name, desc, false);
}
}
/**
* Defines a property on an object
*
* Based on [[DefineOwnProperty]] from 8.12.10 of the spec
*
* @param cx the current Context
* @param id the name/index of the property
* @param desc the new property descriptor, as described in 8.6.1
*/
public void defineOwnProperty(Context cx, Object id, ScriptableObject desc) {
defineOwnProperty(cx, id, desc, true);
}
private void defineOwnProperty(Context cx, Object id, ScriptableObject desc,
boolean checkValid) {
Slot slot = getSlot(cx, id, SLOT_QUERY);
if (checkValid)
checkValidPropertyDefinition(slot, desc);
boolean isAccessor = isAccessorDescriptor(desc);
final int attributes;
if (slot == null) { // new slot
slot = getSlot(cx, id, isAccessor ? SLOT_MODIFY_GETTER_SETTER : SLOT_MODIFY);
attributes = applyDescriptorToAttributeBitset(DONTENUM|READONLY|PERMANENT, desc);
} else {
attributes = applyDescriptorToAttributeBitset(slot.getAttributes(), desc);
}
slot = unwrapSlot(slot);
if (isAccessor) {
if ( !(slot instanceof GetterSlot) ) {
slot = getSlot(cx, id, SLOT_MODIFY_GETTER_SETTER);
}
GetterSlot gslot = (GetterSlot) slot;
Object getter = getProperty(desc, "get");
if (getter != NOT_FOUND) {
gslot.getter = getter;
}
Object setter = getProperty(desc, "set");
if (setter != NOT_FOUND) {
gslot.setter = setter;
}
gslot.value = Undefined.instance;
gslot.setAttributes(attributes);
} else {
if (slot instanceof GetterSlot && isDataDescriptor(desc)) {
slot = getSlot(cx, id, SLOT_CONVERT_ACCESSOR_TO_DATA);
}
Object value = getProperty(desc, "value");
if (value != NOT_FOUND) {
slot.value = value;
}
slot.setAttributes(attributes);
}
}
private void checkValidPropertyDefinition(Slot slot, ScriptableObject desc) {
Object getter = getProperty(desc, "get");
if (getter != NOT_FOUND && getter != Undefined.instance && !(getter instanceof Callable)) {
throw ScriptRuntime.notFunctionError(getter);
}
Object setter = getProperty(desc, "set");
if (setter != NOT_FOUND && setter != Undefined.instance && !(setter instanceof Callable)) {
throw ScriptRuntime.notFunctionError(setter);
}
if (isDataDescriptor(desc) && isAccessorDescriptor(desc)) {
throw ScriptRuntime.typeError0("msg.both.data.and.accessor.desc");
}
if (slot == null) { // new property
if (!isExtensible()) throw ScriptRuntime.typeError0("msg.not.extensible");
} else {
ScriptableObject current = slot.getPropertyDescriptor(Context.getContext(), this);
if (isFalse(current.get("configurable", current))) {
String id = slot.name != null ?
slot.name : Integer.toString(slot.indexOrHash);
if (isTrue(getProperty(desc, "configurable")))
throw ScriptRuntime.typeError1(
"msg.change.configurable.false.to.true", id);
if (isTrue(current.get("enumerable", current)) != isTrue(getProperty(desc, "enumerable")))
throw ScriptRuntime.typeError1(
"msg.change.enumerable.with.configurable.false", id);
if (isGenericDescriptor(desc)) {
// no further validation required
} else if (isDataDescriptor(desc) && isDataDescriptor(current)) {
if (isFalse(current.get("writable", current))) {
if (isTrue(getProperty(desc, "writable")))
throw ScriptRuntime.typeError1(
"msg.change.writable.false.to.true.with.configurable.false", id);
if (changes(current.get("value", current), getProperty(desc, "value")))
throw ScriptRuntime.typeError1(
"msg.change.value.with.writable.false", id);
}
} else if (isAccessorDescriptor(desc) && isAccessorDescriptor(current)) {
if (changes(current.get("set", current), setter))
throw ScriptRuntime.typeError1(
"msg.change.setter.with.configurable.false", id);
if (changes(current.get("get", current), getter))
throw ScriptRuntime.typeError1(
"msg.change.getter.with.configurable.false", id);
} else {
if (isDataDescriptor(current))
throw ScriptRuntime.typeError1(
"msg.change.property.data.to.accessor.with.configurable.false", id);
else
throw ScriptRuntime.typeError1(
"msg.change.property.accessor.to.data.with.configurable.false", id);
}
}
}
}
protected static boolean isTrue(Object value) {
return (value == NOT_FOUND) ? false : ScriptRuntime.toBoolean(value);
}
protected static boolean isFalse(Object value) {
return !isTrue(value);
}
private boolean changes(Object currentValue, Object newValue) {
if (newValue == NOT_FOUND) return false;
if (currentValue == NOT_FOUND) {
currentValue = Undefined.instance;
}
return !ScriptRuntime.shallowEq(currentValue, newValue);
}
protected int applyDescriptorToAttributeBitset(int attributes,
ScriptableObject desc)
{
Object enumerable = getProperty(desc, "enumerable");
if (enumerable != NOT_FOUND) {
attributes = ScriptRuntime.toBoolean(enumerable)
? attributes & ~DONTENUM : attributes | DONTENUM;
}
Object writable = getProperty(desc, "writable");
if (writable != NOT_FOUND) {
attributes = ScriptRuntime.toBoolean(writable)
? attributes & ~READONLY : attributes | READONLY;
}
Object configurable = getProperty(desc, "configurable");
if (configurable != NOT_FOUND) {
attributes = ScriptRuntime.toBoolean(configurable)
? attributes & ~PERMANENT : attributes | PERMANENT;
}
return attributes;
}
protected boolean isDataDescriptor(ScriptableObject desc) {
return hasProperty(desc, "value") || hasProperty(desc, "writable");
}
protected boolean isAccessorDescriptor(ScriptableObject desc) {
return hasProperty(desc, "get") || hasProperty(desc, "set");
}
protected boolean isGenericDescriptor(ScriptableObject desc) {
return !isDataDescriptor(desc) && !isAccessorDescriptor(desc);
}
protected Scriptable ensureScriptable(Object arg) {
if ( !(arg instanceof Scriptable) )
throw ScriptRuntime.typeError1("msg.arg.not.object", ScriptRuntime.typeof(arg));
return (Scriptable) arg;
}
protected ScriptableObject ensureScriptableObject(Object arg) {
if ( !(arg instanceof ScriptableObject) )
throw ScriptRuntime.typeError1("msg.arg.not.object", ScriptRuntime.typeof(arg));
return (ScriptableObject) arg;
}
/**
* Search for names in a class, adding the resulting methods
* as properties.
*
* <p> Uses reflection to find the methods of the given names. Then
* FunctionObjects are constructed from the methods found, and
* are added to this object as properties with the given names.
*
* @param names the names of the Methods to add as function properties
* @param clazz the class to search for the Methods
* @param attributes the attributes of the new properties
* @see org.mozilla.javascript.FunctionObject
*/
public void defineFunctionProperties(String[] names, Class<?> clazz,
int attributes)
{
Method[] methods = FunctionObject.getMethodList(clazz);
for (int i=0; i < names.length; i++) {
String name = names[i];
Method m = FunctionObject.findSingleMethod(methods, name);
if (m == null) {
throw Context.reportRuntimeError2(
"msg.method.not.found", name, clazz.getName());
}
FunctionObject f = new FunctionObject(name, m, this);
defineProperty(name, f, attributes);
}
}
/**
* Get the Object.prototype property.
* See ECMA 15.2.4.
*/
public static Scriptable getObjectPrototype(Scriptable scope) {
return TopLevel.getBuiltinPrototype(getTopLevelScope(scope),
TopLevel.Builtins.Object);
}
/**
* Get the Function.prototype property.
* See ECMA 15.3.4.
*/
public static Scriptable getFunctionPrototype(Scriptable scope) {
return TopLevel.getBuiltinPrototype(getTopLevelScope(scope),
TopLevel.Builtins.Function);
}
public static Scriptable getArrayPrototype(Scriptable scope) {
return TopLevel.getBuiltinPrototype(getTopLevelScope(scope),
TopLevel.Builtins.Array);
}
/**
* Get the prototype for the named class.
*
* For example, <code>getClassPrototype(s, "Date")</code> will first
* walk up the parent chain to find the outermost scope, then will
* search that scope for the Date constructor, and then will
* return Date.prototype. If any of the lookups fail, or
* the prototype is not a JavaScript object, then null will
* be returned.
*
* @param scope an object in the scope chain
* @param className the name of the constructor
* @return the prototype for the named class, or null if it
* cannot be found.
*/
public static Scriptable getClassPrototype(Scriptable scope,
String className)
{
scope = getTopLevelScope(scope);
Object ctor = getProperty(scope, className);
Object proto;
if (ctor instanceof BaseFunction) {
proto = ((BaseFunction)ctor).getPrototypeProperty();
} else if (ctor instanceof Scriptable) {
Scriptable ctorObj = (Scriptable)ctor;
proto = ctorObj.get("prototype", ctorObj);
} else {
return null;
}
if (proto instanceof Scriptable) {
return (Scriptable)proto;
}
return null;
}
/**
* Get the global scope.
*
* <p>Walks the parent scope chain to find an object with a null
* parent scope (the global object).
*
* @param obj a JavaScript object
* @return the corresponding global scope
*/
public static Scriptable getTopLevelScope(Scriptable obj)
{
for (;;) {
Scriptable parent = obj.getParentScope();
if (parent == null) {
return obj;
}
obj = parent;
}
}
public boolean isExtensible() {
return isExtensible;
}
public void preventExtensions() {
isExtensible = false;
}
/**
* Seal this object.
*
* It is an error to add properties to or delete properties from
* a sealed object. It is possible to change the value of an
* existing property. Once an object is sealed it may not be unsealed.
*
* @since 1.4R3
*/
public synchronized void sealObject() {
if (count >= 0) {
// Make sure all LazilyLoadedCtors are initialized before sealing.
Slot slot = firstAdded;
while (slot != null) {
Object value = slot.value;
if (value instanceof LazilyLoadedCtor) {
LazilyLoadedCtor initializer = (LazilyLoadedCtor) value;
try {
initializer.init();
} finally {
slot.value = initializer.getValue();
}
}
slot = slot.orderedNext;
}
count = ~count;
}
}
/**
* Return true if this object is sealed.
*
* @return true if sealed, false otherwise.
* @since 1.4R3
* @see #sealObject()
*/
public final boolean isSealed() {
return count < 0;
}
private void checkNotSealed(String name, int index)
{
if (!isSealed())
return;
String str = (name != null) ? name : Integer.toString(index);
throw Context.reportRuntimeError1("msg.modify.sealed", str);
}
/**
* Gets a named property from an object or any object in its prototype chain.
* <p>
* Searches the prototype chain for a property named <code>name</code>.
* <p>
* @param obj a JavaScript object
* @param name a property name
* @return the value of a property with name <code>name</code> found in
* <code>obj</code> or any object in its prototype chain, or
* <code>Scriptable.NOT_FOUND</code> if not found
* @since 1.5R2
*/
public static Object getProperty(Scriptable obj, String name)
{
Scriptable start = obj;
Object result;
do {
result = obj.get(name, start);
if (result != Scriptable.NOT_FOUND)
break;
obj = obj.getPrototype();
} while (obj != null);
return result;
}
/**
* Gets an indexed property from an object or any object in its prototype
* chain and coerces it to the requested Java type.
* <p>
* Searches the prototype chain for a property with integral index
* <code>index</code>. Note that if you wish to look for properties with numerical
* but non-integral indicies, you should use getProperty(Scriptable,String) with
* the string value of the index.
* <p>
* @param s a JavaScript object
* @param index an integral index
* @param type the required Java type of the result
* @return the value of a property with name <code>name</code> found in
* <code>obj</code> or any object in its prototype chain, or
* null if not found. Note that it does not return
* {@link Scriptable#NOT_FOUND} as it can ordinarily not be
* converted to most of the types.
* @since 1.7R3
*/
public static <T> T getTypedProperty(Scriptable s, int index, Class<T> type) {
Object val = getProperty(s, index);
if(val == Scriptable.NOT_FOUND) {
val = null;
}
return type.cast(Context.jsToJava(val, type));
}
/**
* Gets an indexed property from an object or any object in its prototype chain.
* <p>
* Searches the prototype chain for a property with integral index
* <code>index</code>. Note that if you wish to look for properties with numerical
* but non-integral indicies, you should use getProperty(Scriptable,String) with
* the string value of the index.
* <p>
* @param obj a JavaScript object
* @param index an integral index
* @return the value of a property with index <code>index</code> found in
* <code>obj</code> or any object in its prototype chain, or
* <code>Scriptable.NOT_FOUND</code> if not found
* @since 1.5R2
*/
public static Object getProperty(Scriptable obj, int index)
{
Scriptable start = obj;
Object result;
do {
result = obj.get(index, start);
if (result != Scriptable.NOT_FOUND)
break;
obj = obj.getPrototype();
} while (obj != null);
return result;
}
/**
* Gets a named property from an object or any object in its prototype chain
* and coerces it to the requested Java type.
* <p>
* Searches the prototype chain for a property named <code>name</code>.
* <p>
* @param s a JavaScript object
* @param name a property name
* @param type the required Java type of the result
* @return the value of a property with name <code>name</code> found in
* <code>obj</code> or any object in its prototype chain, or
* null if not found. Note that it does not return
* {@link Scriptable#NOT_FOUND} as it can ordinarily not be
* converted to most of the types.
* @since 1.7R3
*/
public static <T> T getTypedProperty(Scriptable s, String name, Class<T> type) {
Object val = getProperty(s, name);
if(val == Scriptable.NOT_FOUND) {
val = null;
}
return type.cast(Context.jsToJava(val, type));
}
/**
* Returns whether a named property is defined in an object or any object
* in its prototype chain.
* <p>
* Searches the prototype chain for a property named <code>name</code>.
* <p>
* @param obj a JavaScript object
* @param name a property name
* @return the true if property was found
* @since 1.5R2
*/
public static boolean hasProperty(Scriptable obj, String name)
{
return null != getBase(obj, name);
}
/**
* If hasProperty(obj, name) would return true, then if the property that
* was found is compatible with the new property, this method just returns.
* If the property is not compatible, then an exception is thrown.
*
* A property redefinition is incompatible if the first definition was a
* const declaration or if this one is. They are compatible only if neither
* was const.
*/
public static void redefineProperty(Scriptable obj, String name,
boolean isConst)
{
Scriptable base = getBase(obj, name);
if (base == null)
return;
if (base instanceof ConstProperties) {
ConstProperties cp = (ConstProperties)base;
if (cp.isConst(name))
throw Context.reportRuntimeError1("msg.const.redecl", name);
}
if (isConst)
throw Context.reportRuntimeError1("msg.var.redecl", name);
}
/**
* Returns whether an indexed property is defined in an object or any object
* in its prototype chain.
* <p>
* Searches the prototype chain for a property with index <code>index</code>.
* <p>
* @param obj a JavaScript object
* @param index a property index
* @return the true if property was found
* @since 1.5R2
*/
public static boolean hasProperty(Scriptable obj, int index)
{
return null != getBase(obj, index);
}
/**
* Puts a named property in an object or in an object in its prototype chain.
* <p>
* Searches for the named property in the prototype chain. If it is found,
* the value of the property in <code>obj</code> is changed through a call
* to {@link Scriptable#put(String, Scriptable, Object)} on the
* prototype passing <code>obj</code> as the <code>start</code> argument.
* This allows the prototype to veto the property setting in case the
* prototype defines the property with [[ReadOnly]] attribute. If the
* property is not found, it is added in <code>obj</code>.
* @param obj a JavaScript object
* @param name a property name
* @param value any JavaScript value accepted by Scriptable.put
* @since 1.5R2
*/
public static void putProperty(Scriptable obj, String name, Object value)
{
Scriptable base = getBase(obj, name);
if (base == null)
base = obj;
base.put(name, obj, value);
}
/**
* Puts a named property in an object or in an object in its prototype chain.
* <p>
* Searches for the named property in the prototype chain. If it is found,
* the value of the property in <code>obj</code> is changed through a call
* to {@link Scriptable#put(String, Scriptable, Object)} on the
* prototype passing <code>obj</code> as the <code>start</code> argument.
* This allows the prototype to veto the property setting in case the
* prototype defines the property with [[ReadOnly]] attribute. If the
* property is not found, it is added in <code>obj</code>.
* @param obj a JavaScript object
* @param name a property name
* @param value any JavaScript value accepted by Scriptable.put
* @since 1.5R2
*/
public static void putConstProperty(Scriptable obj, String name, Object value)
{
Scriptable base = getBase(obj, name);
if (base == null)
base = obj;
if (base instanceof ConstProperties)
((ConstProperties)base).putConst(name, obj, value);
}
/**
* Puts an indexed property in an object or in an object in its prototype chain.
* <p>
* Searches for the indexed property in the prototype chain. If it is found,
* the value of the property in <code>obj</code> is changed through a call
* to {@link Scriptable#put(int, Scriptable, Object)} on the prototype
* passing <code>obj</code> as the <code>start</code> argument. This allows
* the prototype to veto the property setting in case the prototype defines
* the property with [[ReadOnly]] attribute. If the property is not found,
* it is added in <code>obj</code>.
* @param obj a JavaScript object
* @param index a property index
* @param value any JavaScript value accepted by Scriptable.put
* @since 1.5R2
*/
public static void putProperty(Scriptable obj, int index, Object value)
{
Scriptable base = getBase(obj, index);
if (base == null)
base = obj;
base.put(index, obj, value);
}
/**
* Removes the property from an object or its prototype chain.
* <p>
* Searches for a property with <code>name</code> in obj or
* its prototype chain. If it is found, the object's delete
* method is called.
* @param obj a JavaScript object
* @param name a property name
* @return true if the property doesn't exist or was successfully removed
* @since 1.5R2
*/
public static boolean deleteProperty(Scriptable obj, String name)
{
Scriptable base = getBase(obj, name);
if (base == null)
return true;
base.delete(name);
return !base.has(name, obj);
}
/**
* Removes the property from an object or its prototype chain.
* <p>
* Searches for a property with <code>index</code> in obj or
* its prototype chain. If it is found, the object's delete
* method is called.
* @param obj a JavaScript object
* @param index a property index
* @return true if the property doesn't exist or was successfully removed
* @since 1.5R2
*/
public static boolean deleteProperty(Scriptable obj, int index)
{
Scriptable base = getBase(obj, index);
if (base == null)
return true;
base.delete(index);
return !base.has(index, obj);
}
/**
* Returns an array of all ids from an object and its prototypes.
* <p>
* @param obj a JavaScript object
* @return an array of all ids from all object in the prototype chain.
* If a given id occurs multiple times in the prototype chain,
* it will occur only once in this list.
* @since 1.5R2
*/
public static Object[] getPropertyIds(Scriptable obj)
{
if (obj == null) {
return ScriptRuntime.emptyArgs;
}
Object[] result = obj.getIds();
ObjToIntMap map = null;
for (;;) {
obj = obj.getPrototype();
if (obj == null) {
break;
}
Object[] ids = obj.getIds();
if (ids.length == 0) {
continue;
}
if (map == null) {
if (result.length == 0) {
result = ids;
continue;
}
map = new ObjToIntMap(result.length + ids.length);
for (int i = 0; i != result.length; ++i) {
map.intern(result[i]);
}
result = null; // Allow to GC the result
}
for (int i = 0; i != ids.length; ++i) {
map.intern(ids[i]);
}
}
if (map != null) {
result = map.getKeys();
}
return result;
}
/**
* Call a method of an object.
* @param obj the JavaScript object
* @param methodName the name of the function property
* @param args the arguments for the call
*
* @see Context#getCurrentContext()
*/
public static Object callMethod(Scriptable obj, String methodName,
Object[] args)
{
return callMethod(null, obj, methodName, args);
}
/**
* Call a method of an object.
* @param cx the Context object associated with the current thread.
* @param obj the JavaScript object
* @param methodName the name of the function property
* @param args the arguments for the call
*/
public static Object callMethod(Context cx, Scriptable obj,
String methodName,
Object[] args)
{
Object funObj = getProperty(obj, methodName);
if (!(funObj instanceof Function)) {
throw ScriptRuntime.notFunctionError(obj, methodName);
}
Function fun = (Function)funObj;
// XXX: What should be the scope when calling funObj?
// The following favor scope stored in the object on the assumption
// that is more useful especially under dynamic scope setup.
// An alternative is to check for dynamic scope flag
// and use ScriptableObject.getTopLevelScope(fun) if the flag is not
// set. But that require access to Context and messy code
// so for now it is not checked.
Scriptable scope = ScriptableObject.getTopLevelScope(obj);
if (cx != null) {
return fun.call(cx, scope, obj, args);
} else {
return Context.call(null, fun, scope, obj, args);
}
}
private static Scriptable getBase(Scriptable obj, String name)
{
do {
if (obj.has(name, obj))
break;
obj = obj.getPrototype();
} while(obj != null);
return obj;
}
private static Scriptable getBase(Scriptable obj, int index)
{
do {
if (obj.has(index, obj))
break;
obj = obj.getPrototype();
} while(obj != null);
return obj;
}
/**
* Get arbitrary application-specific value associated with this object.
* @param key key object to select particular value.
* @see #associateValue(Object key, Object value)
*/
public final Object getAssociatedValue(Object key)
{
Map<Object,Object> h = associatedValues;
if (h == null)
return null;
return h.get(key);
}
/**
* Get arbitrary application-specific value associated with the top scope
* of the given scope.
* The method first calls {@link #getTopLevelScope(Scriptable scope)}
* and then searches the prototype chain of the top scope for the first
* object containing the associated value with the given key.
*
* @param scope the starting scope.
* @param key key object to select particular value.
* @see #getAssociatedValue(Object key)
*/
public static Object getTopScopeValue(Scriptable scope, Object key)
{
scope = ScriptableObject.getTopLevelScope(scope);
for (;;) {
if (scope instanceof ScriptableObject) {
ScriptableObject so = (ScriptableObject)scope;
Object value = so.getAssociatedValue(key);
if (value != null) {
return value;
}
}
scope = scope.getPrototype();
if (scope == null) {
return null;
}
}
}
/**
* Associate arbitrary application-specific value with this object.
* Value can only be associated with the given object and key only once.
* The method ignores any subsequent attempts to change the already
* associated value.
* <p> The associated values are not serialized.
* @param key key object to select particular value.
* @param value the value to associate
* @return the passed value if the method is called first time for the
* given key or old value for any subsequent calls.
* @see #getAssociatedValue(Object key)
*/
public synchronized final Object associateValue(Object key, Object value)
{
if (value == null) throw new IllegalArgumentException();
Map<Object,Object> h = associatedValues;
if (h == null) {
h = new HashMap<Object,Object>();
associatedValues = h;
}
return Kit.initHash(h, key, value);
}
/**
*
* @param name
* @param index
* @param start
* @param value
* @return false if this != start and no slot was found. true if this == start
* or this != start and a READONLY slot was found.
*/
private boolean putImpl(String name, int index, Scriptable start,
Object value)
{
// This method is very hot (basically called on each assignment)
// so we inline the extensible/sealed checks below.
Slot slot;
if (this != start) {
slot = getSlot(name, index, SLOT_QUERY);
if (slot == null) {
return false;
}
} else if (!isExtensible) {
slot = getSlot(name, index, SLOT_QUERY);
if (slot == null) {
return true;
}
} else {
if (count < 0) checkNotSealed(name, index);
slot = getSlot(name, index, SLOT_MODIFY);
}
return slot.setValue(value, this, start);
}
/**
*
* @param name
* @param index
* @param start
* @param value
* @param constFlag EMPTY means normal put. UNINITIALIZED_CONST means
* defineConstProperty. READONLY means const initialization expression.
* @return false if this != start and no slot was found. true if this == start
* or this != start and a READONLY slot was found.
*/
private boolean putConstImpl(String name, int index, Scriptable start,
Object value, int constFlag)
{
assert (constFlag != EMPTY);
Slot slot;
if (this != start) {
slot = getSlot(name, index, SLOT_QUERY);
if (slot == null) {
return false;
}
} else if (!isExtensible()) {
slot = getSlot(name, index, SLOT_QUERY);
if (slot == null) {
return true;
}
} else {
checkNotSealed(name, index);
// either const hoisted declaration or initialization
slot = unwrapSlot(getSlot(name, index, SLOT_MODIFY_CONST));
int attr = slot.getAttributes();
if ((attr & READONLY) == 0)
throw Context.reportRuntimeError1("msg.var.redecl", name);
if ((attr & UNINITIALIZED_CONST) != 0) {
slot.value = value;
// clear the bit on const initialization
if (constFlag != UNINITIALIZED_CONST)
slot.setAttributes(attr & ~UNINITIALIZED_CONST);
}
return true;
}
return slot.setValue(value, this, start);
}
private Slot findAttributeSlot(String name, int index, int accessType)
{
Slot slot = getSlot(name, index, accessType);
if (slot == null) {
String str = (name != null ? name : Integer.toString(index));
throw Context.reportRuntimeError1("msg.prop.not.found", str);
}
return slot;
}
private static Slot unwrapSlot(Slot slot) {
return (slot instanceof RelinkedSlot) ? ((RelinkedSlot)slot).slot : slot;
}
/**
* Locate the slot with given name or index. Depending on the accessType
* parameter and the current slot status, a new slot may be allocated.
*
* @param name property name or null if slot holds spare array index.
* @param index index or 0 if slot holds property name.
*/
private Slot getSlot(String name, int index, int accessType)
{
// Check the hashtable without using synchronization
Slot[] slotsLocalRef = slots; // Get stable local reference
if (slotsLocalRef == null && accessType == SLOT_QUERY) {
return null;
}
int indexOrHash = (name != null ? name.hashCode() : index);
if (slotsLocalRef != null) {
Slot slot;
int slotIndex = getSlotIndex(slotsLocalRef.length, indexOrHash);
for (slot = slotsLocalRef[slotIndex];
slot != null;
slot = slot.next) {
Object sname = slot.name;
if (indexOrHash == slot.indexOrHash &&
(sname == name ||
(name != null && name.equals(sname)))) {
break;
}
}
switch (accessType) {
case SLOT_QUERY:
return slot;
case SLOT_MODIFY:
case SLOT_MODIFY_CONST:
if (slot != null)
return slot;
break;
case SLOT_MODIFY_GETTER_SETTER:
slot = unwrapSlot(slot);
if (slot instanceof GetterSlot)
return slot;
break;
case SLOT_CONVERT_ACCESSOR_TO_DATA:
slot = unwrapSlot(slot);
if ( !(slot instanceof GetterSlot) )
return slot;
break;
}
}
// A new slot has to be inserted or the old has to be replaced
// by GetterSlot. Time to synchronize.
return createSlot(name, indexOrHash, accessType);
}
private synchronized Slot createSlot(String name, int indexOrHash, int accessType) {
Slot[] slotsLocalRef = slots;
int insertPos;
if (count == 0) {
// Always throw away old slots if any on empty insert.
slotsLocalRef = new Slot[INITIAL_SLOT_SIZE];
slots = slotsLocalRef;
insertPos = getSlotIndex(slotsLocalRef.length, indexOrHash);
} else {
int tableSize = slotsLocalRef.length;
insertPos = getSlotIndex(tableSize, indexOrHash);
Slot prev = slotsLocalRef[insertPos];
Slot slot = prev;
while (slot != null) {
if (slot.indexOrHash == indexOrHash &&
(slot.name == name ||
(name != null && name.equals(slot.name))))
{
break;
}
prev = slot;
slot = slot.next;
}
if (slot != null) {
// Another thread just added a slot with same
// name/index before this one entered synchronized
// block. This is a race in application code and
// probably indicates bug there. But for the hashtable
// implementation it is harmless with the only
// complication is the need to replace the added slot
// if we need GetterSlot and the old one is not.
slot = unwrapSlot(slot);
Slot newSlot;
if (accessType == SLOT_MODIFY_GETTER_SETTER
&& !(slot instanceof GetterSlot)) {
newSlot = new GetterSlot(name, indexOrHash, slot.getAttributes());
} else if (accessType == SLOT_CONVERT_ACCESSOR_TO_DATA
&& (slot instanceof GetterSlot)) {
newSlot = new Slot(name, indexOrHash, slot.getAttributes());
} else if (accessType == SLOT_MODIFY_CONST) {
return null;
} else {
return slot;
}
newSlot.value = slot.value;
newSlot.next = slot.next;
// add new slot to linked list
if (lastAdded != null)
lastAdded.orderedNext = newSlot;
if (firstAdded == null)
firstAdded = newSlot;
lastAdded = newSlot;
// add new slot to hash table
if (prev == slot) {
slotsLocalRef[insertPos] = newSlot;
} else {
prev.next = newSlot;
}
// other housekeeping
slot.markDeleted();
return newSlot;
} else {
// Check if the table is not too full before inserting.
if (4 * (count + 1) > 3 * slotsLocalRef.length) {
// table size must be a power of 2, always grow by x2
slotsLocalRef = new Slot[slotsLocalRef.length * 2];
copyTable(slots, slotsLocalRef, count);
slots = slotsLocalRef;
insertPos = getSlotIndex(slotsLocalRef.length,
indexOrHash);
}
}
}
Slot newSlot = (accessType == SLOT_MODIFY_GETTER_SETTER
? new GetterSlot(name, indexOrHash, 0)
: new Slot(name, indexOrHash, 0));
if (accessType == SLOT_MODIFY_CONST)
newSlot.setAttributes(CONST);
++count;
// add new slot to linked list
if (lastAdded != null)
lastAdded.orderedNext = newSlot;
if (firstAdded == null)
firstAdded = newSlot;
lastAdded = newSlot;
// add new slot to hash table, return it
addKnownAbsentSlot(slotsLocalRef, newSlot, insertPos);
return newSlot;
}
private synchronized void removeSlot(String name, int index) {
int indexOrHash = (name != null ? name.hashCode() : index);
Slot[] slotsLocalRef = slots;
if (count != 0) {
int tableSize = slotsLocalRef.length;
int slotIndex = getSlotIndex(tableSize, indexOrHash);
Slot prev = slotsLocalRef[slotIndex];
Slot slot = prev;
while (slot != null) {
if (slot.indexOrHash == indexOrHash &&
(slot.name == name ||
(name != null && name.equals(slot.name))))
{
break;
}
prev = slot;
slot = slot.next;
}
if (slot != null && (slot.getAttributes() & PERMANENT) == 0) {
count--;
// remove slot from hash table
if (prev == slot) {
slotsLocalRef[slotIndex] = slot.next;
} else {
prev.next = slot.next;
}
// remove from ordered list. Previously this was done lazily in
// getIds() but delete is an infrequent operation so O(n)
// should be ok
// ordered list always uses the actual slot
Slot deleted = unwrapSlot(slot);
if (deleted == firstAdded) {
prev = null;
firstAdded = deleted.orderedNext;
} else {
prev = firstAdded;
while (prev.orderedNext != deleted) {
prev = prev.orderedNext;
}
prev.orderedNext = deleted.orderedNext;
}
if (deleted == lastAdded) {
lastAdded = prev;
}
// Mark the slot as removed.
slot.markDeleted();
}
}
}
private static int getSlotIndex(int tableSize, int indexOrHash)
{
// tableSize is a power of 2
return indexOrHash & (tableSize - 1);
}
// Must be inside synchronized (this)
private static void copyTable(Slot[] oldSlots, Slot[] newSlots, int count)
{
if (count == 0) throw Kit.codeBug();
int tableSize = newSlots.length;
int i = oldSlots.length;
for (;;) {
--i;
Slot slot = oldSlots[i];
while (slot != null) {
int insertPos = getSlotIndex(tableSize, slot.indexOrHash);
// If slot has next chain in old table use a new
// RelinkedSlot wrapper to keep old table valid
Slot insSlot = slot.next == null ? slot : new RelinkedSlot(slot);
addKnownAbsentSlot(newSlots, insSlot, insertPos);
slot = slot.next;
if (--count == 0)
return;
}
}
}
/**
* Add slot with keys that are known to absent from the table.
* This is an optimization to use when inserting into empty table,
* after table growth or during deserialization.
*/
private static void addKnownAbsentSlot(Slot[] slots, Slot slot,
int insertPos)
{
if (slots[insertPos] == null) {
slots[insertPos] = slot;
} else {
Slot prev = slots[insertPos];
Slot next = prev.next;
while (next != null) {
prev = next;
next = prev.next;
}
prev.next = slot;
}
}
Object[] getIds(boolean getAll) {
Slot[] s = slots;
Object[] a = ScriptRuntime.emptyArgs;
if (s == null)
return a;
int c = 0;
Slot slot = firstAdded;
while (slot != null && slot.wasDeleted) {
// we used to removed deleted slots from the linked list here
// but this is now done in removeSlot(). There may still be deleted
// slots (e.g. from slot conversion) but we don't want to mess
// with the list in unsynchronized code.
slot = slot.orderedNext;
}
while (slot != null) {
if (getAll || (slot.getAttributes() & DONTENUM) == 0) {
if (c == 0)
a = new Object[s.length];
a[c++] = slot.name != null
? slot.name
: Integer.valueOf(slot.indexOrHash);
}
slot = slot.orderedNext;
while (slot != null && slot.wasDeleted) {
// skip deleted slots, see comment above
slot = slot.orderedNext;
}
}
if (c == a.length)
return a;
Object[] result = new Object[c];
System.arraycopy(a, 0, result, 0, c);
return result;
}
private synchronized void writeObject(ObjectOutputStream out)
throws IOException
{
out.defaultWriteObject();
int objectsCount = count;
if (objectsCount < 0) {
// "this" was sealed
objectsCount = ~objectsCount;
}
if (objectsCount == 0) {
out.writeInt(0);
} else {
out.writeInt(slots.length);
Slot slot = firstAdded;
while (slot != null && slot.wasDeleted) {
// as long as we're traversing the order-added linked list,
// remove deleted slots
slot = slot.orderedNext;
}
firstAdded = slot;
while (slot != null) {
out.writeObject(slot);
Slot next = slot.orderedNext;
while (next != null && next.wasDeleted) {
// remove deleted slots
next = next.orderedNext;
}
slot.orderedNext = next;
slot = next;
}
}
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
int tableSize = in.readInt();
if (tableSize != 0) {
// If tableSize is not a power of 2 find the closest
// power of 2 >= the original size.
if ((tableSize & (tableSize - 1)) != 0) {
if (tableSize > 1 << 30)
throw new RuntimeException("Property table overflow");
int newSize = INITIAL_SLOT_SIZE;
while (newSize < tableSize)
newSize <<= 1;
tableSize = newSize;
}
slots = new Slot[tableSize];
int objectsCount = count;
if (objectsCount < 0) {
// "this" was sealed
objectsCount = ~objectsCount;
}
Slot prev = null;
for (int i=0; i != objectsCount; ++i) {
lastAdded = (Slot)in.readObject();
if (i==0) {
firstAdded = lastAdded;
} else {
prev.orderedNext = lastAdded;
}
int slotIndex = getSlotIndex(tableSize, lastAdded.indexOrHash);
addKnownAbsentSlot(slots, lastAdded, slotIndex);
prev = lastAdded;
}
}
}
protected ScriptableObject getOwnPropertyDescriptor(Context cx, Object id) {
Slot slot = getSlot(cx, id, SLOT_QUERY);
if (slot == null) return null;
Scriptable scope = getParentScope();
return slot.getPropertyDescriptor(cx, (scope == null ? this : scope));
}
protected Slot getSlot(Context cx, Object id, int accessType) {
String name = ScriptRuntime.toStringIdOrIndex(cx, id);
if (name == null) {
return getSlot(null, ScriptRuntime.lastIndexResult(cx), accessType);
} else {
return getSlot(name, 0, accessType);
}
}
// Partial implementation of java.util.Map. See NativeObject for
// a subclass that implements java.util.Map.
public int size() {
return count < 0 ? ~count : count;
}
public boolean isEmpty() {
return count == 0 || count == -1;
}
public Object get(Object key) {
Object value = null;
if (key instanceof String) {
value = get((String) key, this);
} else if (key instanceof Number) {
value = get(((Number) key).intValue(), this);
}
if (value == Scriptable.NOT_FOUND || value == Undefined.instance) {
return null;
} else if (value instanceof Wrapper) {
return ((Wrapper) value).unwrap();
} else {
return value;
}
}
}
|
src/org/mozilla/javascript/ScriptableObject.java
|
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Igor Bukanov
* Daniel Gredler
* Bob Jervis
* Roger Lawrence
* Cameron McCormack
* Steve Weiss
* Hannes Wallnoefer
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
// API class
package org.mozilla.javascript;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.mozilla.javascript.debug.DebuggableObject;
import org.mozilla.javascript.annotations.JSConstructor;
import org.mozilla.javascript.annotations.JSFunction;
import org.mozilla.javascript.annotations.JSGetter;
import org.mozilla.javascript.annotations.JSSetter;
import org.mozilla.javascript.annotations.JSStaticFunction;
/**
* This is the default implementation of the Scriptable interface. This
* class provides convenient default behavior that makes it easier to
* define host objects.
* <p>
* Various properties and methods of JavaScript objects can be conveniently
* defined using methods of ScriptableObject.
* <p>
* Classes extending ScriptableObject must define the getClassName method.
*
* @see org.mozilla.javascript.Scriptable
* @author Norris Boyd
*/
public abstract class ScriptableObject implements Scriptable, Serializable,
DebuggableObject,
ConstProperties
{
/**
* The empty property attribute.
*
* Used by getAttributes() and setAttributes().
*
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int EMPTY = 0x00;
/**
* Property attribute indicating assignment to this property is ignored.
*
* @see org.mozilla.javascript.ScriptableObject
* #put(String, Scriptable, Object)
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int READONLY = 0x01;
/**
* Property attribute indicating property is not enumerated.
*
* Only enumerated properties will be returned by getIds().
*
* @see org.mozilla.javascript.ScriptableObject#getIds()
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int DONTENUM = 0x02;
/**
* Property attribute indicating property cannot be deleted.
*
* @see org.mozilla.javascript.ScriptableObject#delete(String)
* @see org.mozilla.javascript.ScriptableObject#getAttributes(String)
* @see org.mozilla.javascript.ScriptableObject#setAttributes(String, int)
*/
public static final int PERMANENT = 0x04;
/**
* Property attribute indicating that this is a const property that has not
* been assigned yet. The first 'const' assignment to the property will
* clear this bit.
*/
public static final int UNINITIALIZED_CONST = 0x08;
public static final int CONST = PERMANENT|READONLY|UNINITIALIZED_CONST;
/**
* The prototype of this object.
*/
private Scriptable prototypeObject;
/**
* The parent scope of this object.
*/
private Scriptable parentScopeObject;
private transient Slot[] slots;
// If count >= 0, it gives number of keys or if count < 0,
// it indicates sealed object where ~count gives number of keys
private int count;
// gateways into the definition-order linked list of slots
private transient Slot firstAdded;
private transient Slot lastAdded;
private volatile Map<Object,Object> associatedValues;
private static final int SLOT_QUERY = 1;
private static final int SLOT_MODIFY = 2;
private static final int SLOT_MODIFY_CONST = 3;
private static final int SLOT_MODIFY_GETTER_SETTER = 4;
private static final int SLOT_CONVERT_ACCESSOR_TO_DATA = 5;
// initial slot array size, must be a power of 2
private static final int INITIAL_SLOT_SIZE = 4;
private boolean isExtensible = true;
private static class Slot implements Serializable
{
private static final long serialVersionUID = -6090581677123995491L;
String name; // This can change due to caching
int indexOrHash;
private volatile short attributes;
transient volatile boolean wasDeleted;
volatile Object value;
transient Slot next; // next in hash table bucket
transient volatile Slot orderedNext; // next in linked list
Slot(String name, int indexOrHash, int attributes)
{
this.name = name;
this.indexOrHash = indexOrHash;
this.attributes = (short)attributes;
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
if (name != null) {
indexOrHash = name.hashCode();
}
}
boolean setValue(Object value, Scriptable owner, Scriptable start) {
if ((attributes & READONLY) != 0) {
return true;
}
if (owner == start) {
this.value = value;
return true;
} else {
return false;
}
}
Object getValue(Scriptable start) {
return value;
}
int getAttributes()
{
return attributes;
}
synchronized void setAttributes(int value)
{
checkValidAttributes(value);
attributes = (short)value;
}
void markDeleted() {
wasDeleted = true;
value = null;
name = null;
}
ScriptableObject getPropertyDescriptor(Context cx, Scriptable scope) {
return buildDataDescriptor(
scope,
(value == null ? Undefined.instance : value),
attributes);
}
}
protected static ScriptableObject buildDataDescriptor(Scriptable scope,
Object value,
int attributes) {
ScriptableObject desc = new NativeObject();
ScriptRuntime.setBuiltinProtoAndParent(desc, scope, TopLevel.Builtins.Object);
desc.defineProperty("value", value, EMPTY);
desc.defineProperty("writable", (attributes & READONLY) == 0, EMPTY);
desc.defineProperty("enumerable", (attributes & DONTENUM) == 0, EMPTY);
desc.defineProperty("configurable", (attributes & PERMANENT) == 0, EMPTY);
return desc;
}
private static final class GetterSlot extends Slot
{
static final long serialVersionUID = -4900574849788797588L;
Object getter;
Object setter;
GetterSlot(String name, int indexOrHash, int attributes)
{
super(name, indexOrHash, attributes);
}
@Override
ScriptableObject getPropertyDescriptor(Context cx, Scriptable scope) {
int attr = getAttributes();
ScriptableObject desc = new NativeObject();
ScriptRuntime.setBuiltinProtoAndParent(desc, scope, TopLevel.Builtins.Object);
desc.defineProperty("enumerable", (attr & DONTENUM) == 0, EMPTY);
desc.defineProperty("configurable", (attr & PERMANENT) == 0, EMPTY);
if (getter != null) desc.defineProperty("get", getter, EMPTY);
if (setter != null) desc.defineProperty("set", setter, EMPTY);
return desc;
}
@Override
boolean setValue(Object value, Scriptable owner, Scriptable start) {
if (setter == null) {
if (getter != null) {
if (Context.getContext().hasFeature(Context.FEATURE_STRICT_MODE)) {
// Based on TC39 ES3.1 Draft of 9-Feb-2009, 8.12.4, step 2,
// we should throw a TypeError in this case.
throw ScriptRuntime.typeError1("msg.set.prop.no.setter", name);
}
// Assignment to a property with only a getter defined. The
// assignment is ignored. See bug 478047.
return true;
}
} else {
Context cx = Context.getContext();
if (setter instanceof MemberBox) {
MemberBox nativeSetter = (MemberBox)setter;
Class<?> pTypes[] = nativeSetter.argTypes;
// XXX: cache tag since it is already calculated in
// defineProperty ?
Class<?> valueType = pTypes[pTypes.length - 1];
int tag = FunctionObject.getTypeTag(valueType);
Object actualArg = FunctionObject.convertArg(cx, start,
value, tag);
Object setterThis;
Object[] args;
if (nativeSetter.delegateTo == null) {
setterThis = start;
args = new Object[] { actualArg };
} else {
setterThis = nativeSetter.delegateTo;
args = new Object[] { start, actualArg };
}
nativeSetter.invoke(setterThis, args);
} else if (setter instanceof Function) {
Function f = (Function)setter;
f.call(cx, f.getParentScope(), start,
new Object[] { value });
}
return true;
}
return super.setValue(value, owner, start);
}
@Override
Object getValue(Scriptable start) {
if (getter != null) {
if (getter instanceof MemberBox) {
MemberBox nativeGetter = (MemberBox)getter;
Object getterThis;
Object[] args;
if (nativeGetter.delegateTo == null) {
getterThis = start;
args = ScriptRuntime.emptyArgs;
} else {
getterThis = nativeGetter.delegateTo;
args = new Object[] { start };
}
return nativeGetter.invoke(getterThis, args);
} else if (getter instanceof Function) {
Function f = (Function)getter;
Context cx = Context.getContext();
return f.call(cx, f.getParentScope(), start,
ScriptRuntime.emptyArgs);
}
}
Object val = this.value;
if (val instanceof LazilyLoadedCtor) {
LazilyLoadedCtor initializer = (LazilyLoadedCtor)val;
try {
initializer.init();
} finally {
this.value = val = initializer.getValue();
}
}
return val;
}
@Override
void markDeleted() {
super.markDeleted();
getter = null;
setter = null;
}
}
/**
* A wrapper around a slot that allows the slot to be used in a new slot
* table while keeping it functioning in its old slot table/linked list
* context. This is used when linked slots are copied to a new slot table.
* In a multi-threaded environment, these slots may still be accessed
* through their old slot table. See bug 688458.
*/
private static class RelinkedSlot extends Slot {
final Slot slot;
RelinkedSlot(Slot slot) {
super(slot.name, slot.indexOrHash, slot.attributes);
// Make sure we always wrap the actual slot, not another relinked one
this.slot = unwrapSlot(slot);
}
@Override
boolean setValue(Object value, Scriptable owner, Scriptable start) {
return slot.setValue(value, owner, start);
}
@Override
Object getValue(Scriptable start) {
return slot.getValue(start);
}
@Override
ScriptableObject getPropertyDescriptor(Context cx, Scriptable scope) {
return slot.getPropertyDescriptor(cx, scope);
}
@Override
int getAttributes() {
return slot.getAttributes();
}
@Override
void setAttributes(int value) {
slot.setAttributes(value);
}
@Override
void markDeleted() {
super.markDeleted();
slot.markDeleted();
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(slot); // just serialize the wrapped slot
}
}
static void checkValidAttributes(int attributes)
{
final int mask = READONLY | DONTENUM | PERMANENT | UNINITIALIZED_CONST;
if ((attributes & ~mask) != 0) {
throw new IllegalArgumentException(String.valueOf(attributes));
}
}
public ScriptableObject()
{
}
public ScriptableObject(Scriptable scope, Scriptable prototype)
{
if (scope == null)
throw new IllegalArgumentException();
parentScopeObject = scope;
prototypeObject = prototype;
}
/**
* Gets the value that will be returned by calling the typeof operator on this object.
* @return default is "object" unless {@link #avoidObjectDetection()} is <code>true</code> in which
* case it returns "undefined"
*/
public String getTypeOf() {
return avoidObjectDetection() ? "undefined" : "object";
}
/**
* Return the name of the class.
*
* This is typically the same name as the constructor.
* Classes extending ScriptableObject must implement this abstract
* method.
*/
public abstract String getClassName();
/**
* Returns true if the named property is defined.
*
* @param name the name of the property
* @param start the object in which the lookup began
* @return true if and only if the property was found in the object
*/
public boolean has(String name, Scriptable start)
{
return null != getSlot(name, 0, SLOT_QUERY);
}
/**
* Returns true if the property index is defined.
*
* @param index the numeric index for the property
* @param start the object in which the lookup began
* @return true if and only if the property was found in the object
*/
public boolean has(int index, Scriptable start)
{
return null != getSlot(null, index, SLOT_QUERY);
}
/**
* Returns the value of the named property or NOT_FOUND.
*
* If the property was created using defineProperty, the
* appropriate getter method is called.
*
* @param name the name of the property
* @param start the object in which the lookup began
* @return the value of the property (may be null), or NOT_FOUND
*/
public Object get(String name, Scriptable start)
{
Slot slot = getSlot(name, 0, SLOT_QUERY);
if (slot == null) {
return Scriptable.NOT_FOUND;
}
return slot.getValue(start);
}
/**
* Returns the value of the indexed property or NOT_FOUND.
*
* @param index the numeric index for the property
* @param start the object in which the lookup began
* @return the value of the property (may be null), or NOT_FOUND
*/
public Object get(int index, Scriptable start)
{
Slot slot = getSlot(null, index, SLOT_QUERY);
if (slot == null) {
return Scriptable.NOT_FOUND;
}
return slot.getValue(start);
}
/**
* Sets the value of the named property, creating it if need be.
*
* If the property was created using defineProperty, the
* appropriate setter method is called. <p>
*
* If the property's attributes include READONLY, no action is
* taken.
* This method will actually set the property in the start
* object.
*
* @param name the name of the property
* @param start the object whose property is being set
* @param value value to set the property to
*/
public void put(String name, Scriptable start, Object value)
{
if (putImpl(name, 0, start, value))
return;
if (start == this) throw Kit.codeBug();
start.put(name, start, value);
}
/**
* Sets the value of the indexed property, creating it if need be.
*
* @param index the numeric index for the property
* @param start the object whose property is being set
* @param value value to set the property to
*/
public void put(int index, Scriptable start, Object value)
{
if (putImpl(null, index, start, value))
return;
if (start == this) throw Kit.codeBug();
start.put(index, start, value);
}
/**
* Removes a named property from the object.
*
* If the property is not found, or it has the PERMANENT attribute,
* no action is taken.
*
* @param name the name of the property
*/
public void delete(String name)
{
checkNotSealed(name, 0);
removeSlot(name, 0);
}
/**
* Removes the indexed property from the object.
*
* If the property is not found, or it has the PERMANENT attribute,
* no action is taken.
*
* @param index the numeric index for the property
*/
public void delete(int index)
{
checkNotSealed(null, index);
removeSlot(null, index);
}
/**
* Sets the value of the named const property, creating it if need be.
*
* If the property was created using defineProperty, the
* appropriate setter method is called. <p>
*
* If the property's attributes include READONLY, no action is
* taken.
* This method will actually set the property in the start
* object.
*
* @param name the name of the property
* @param start the object whose property is being set
* @param value value to set the property to
*/
public void putConst(String name, Scriptable start, Object value)
{
if (putConstImpl(name, 0, start, value, READONLY))
return;
if (start == this) throw Kit.codeBug();
if (start instanceof ConstProperties)
((ConstProperties)start).putConst(name, start, value);
else
start.put(name, start, value);
}
public void defineConst(String name, Scriptable start)
{
if (putConstImpl(name, 0, start, Undefined.instance, UNINITIALIZED_CONST))
return;
if (start == this) throw Kit.codeBug();
if (start instanceof ConstProperties)
((ConstProperties)start).defineConst(name, start);
}
/**
* Returns true if the named property is defined as a const on this object.
* @param name
* @return true if the named property is defined as a const, false
* otherwise.
*/
public boolean isConst(String name)
{
Slot slot = getSlot(name, 0, SLOT_QUERY);
if (slot == null) {
return false;
}
return (slot.getAttributes() & (PERMANENT|READONLY)) ==
(PERMANENT|READONLY);
}
/**
* @deprecated Use {@link #getAttributes(String name)}. The engine always
* ignored the start argument.
*/
public final int getAttributes(String name, Scriptable start)
{
return getAttributes(name);
}
/**
* @deprecated Use {@link #getAttributes(int index)}. The engine always
* ignored the start argument.
*/
public final int getAttributes(int index, Scriptable start)
{
return getAttributes(index);
}
/**
* @deprecated Use {@link #setAttributes(String name, int attributes)}.
* The engine always ignored the start argument.
*/
public final void setAttributes(String name, Scriptable start,
int attributes)
{
setAttributes(name, attributes);
}
/**
* @deprecated Use {@link #setAttributes(int index, int attributes)}.
* The engine always ignored the start argument.
*/
public void setAttributes(int index, Scriptable start,
int attributes)
{
setAttributes(index, attributes);
}
/**
* Get the attributes of a named property.
*
* The property is specified by <code>name</code>
* as defined for <code>has</code>.<p>
*
* @param name the identifier for the property
* @return the bitset of attributes
* @exception EvaluatorException if the named property is not found
* @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public int getAttributes(String name)
{
return findAttributeSlot(name, 0, SLOT_QUERY).getAttributes();
}
/**
* Get the attributes of an indexed property.
*
* @param index the numeric index for the property
* @exception EvaluatorException if the named property is not found
* is not found
* @return the bitset of attributes
* @see org.mozilla.javascript.ScriptableObject#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public int getAttributes(int index)
{
return findAttributeSlot(null, index, SLOT_QUERY).getAttributes();
}
/**
* Set the attributes of a named property.
*
* The property is specified by <code>name</code>
* as defined for <code>has</code>.<p>
*
* The possible attributes are READONLY, DONTENUM,
* and PERMANENT. Combinations of attributes
* are expressed by the bitwise OR of attributes.
* EMPTY is the state of no attributes set. Any unused
* bits are reserved for future use.
*
* @param name the name of the property
* @param attributes the bitset of attributes
* @exception EvaluatorException if the named property is not found
* @see org.mozilla.javascript.Scriptable#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public void setAttributes(String name, int attributes)
{
checkNotSealed(name, 0);
findAttributeSlot(name, 0, SLOT_MODIFY).setAttributes(attributes);
}
/**
* Set the attributes of an indexed property.
*
* @param index the numeric index for the property
* @param attributes the bitset of attributes
* @exception EvaluatorException if the named property is not found
* @see org.mozilla.javascript.Scriptable#has(String, Scriptable)
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject#DONTENUM
* @see org.mozilla.javascript.ScriptableObject#PERMANENT
* @see org.mozilla.javascript.ScriptableObject#EMPTY
*/
public void setAttributes(int index, int attributes)
{
checkNotSealed(null, index);
findAttributeSlot(null, index, SLOT_MODIFY).setAttributes(attributes);
}
/**
* XXX: write docs.
*/
public void setGetterOrSetter(String name, int index,
Callable getterOrSetter, boolean isSetter)
{
setGetterOrSetter(name, index, getterOrSetter, isSetter, false);
}
private void setGetterOrSetter(String name, int index, Callable getterOrSetter,
boolean isSetter, boolean force)
{
if (name != null && index != 0)
throw new IllegalArgumentException(name);
if (!force) {
checkNotSealed(name, index);
}
final GetterSlot gslot;
if (isExtensible()) {
gslot = (GetterSlot)getSlot(name, index, SLOT_MODIFY_GETTER_SETTER);
} else {
Slot slot = unwrapSlot(getSlot(name, index, SLOT_QUERY));
if (!(slot instanceof GetterSlot))
return;
gslot = (GetterSlot) slot;
}
if (!force) {
int attributes = gslot.getAttributes();
if ((attributes & READONLY) != 0) {
throw Context.reportRuntimeError1("msg.modify.readonly", name);
}
}
if (isSetter) {
gslot.setter = getterOrSetter;
} else {
gslot.getter = getterOrSetter;
}
gslot.value = Undefined.instance;
}
/**
* Get the getter or setter for a given property. Used by __lookupGetter__
* and __lookupSetter__.
*
* @param name Name of the object. If nonnull, index must be 0.
* @param index Index of the object. If nonzero, name must be null.
* @param isSetter If true, return the setter, otherwise return the getter.
* @exception IllegalArgumentException if both name and index are nonnull
* and nonzero respectively.
* @return Null if the property does not exist. Otherwise returns either
* the getter or the setter for the property, depending on
* the value of isSetter (may be undefined if unset).
*/
public Object getGetterOrSetter(String name, int index, boolean isSetter)
{
if (name != null && index != 0)
throw new IllegalArgumentException(name);
Slot slot = unwrapSlot(getSlot(name, index, SLOT_QUERY));
if (slot == null)
return null;
if (slot instanceof GetterSlot) {
GetterSlot gslot = (GetterSlot)slot;
Object result = isSetter ? gslot.setter : gslot.getter;
return result != null ? result : Undefined.instance;
} else
return Undefined.instance;
}
/**
* Returns whether a property is a getter or a setter
* @param name property name
* @param index property index
* @param setter true to check for a setter, false for a getter
* @return whether the property is a getter or a setter
*/
protected boolean isGetterOrSetter(String name, int index, boolean setter) {
Slot slot = unwrapSlot(getSlot(name, index, SLOT_QUERY));
if (slot instanceof GetterSlot) {
if (setter && ((GetterSlot)slot).setter != null) return true;
if (!setter && ((GetterSlot)slot).getter != null) return true;
}
return false;
}
void addLazilyInitializedValue(String name, int index,
LazilyLoadedCtor init, int attributes)
{
if (name != null && index != 0)
throw new IllegalArgumentException(name);
checkNotSealed(name, index);
GetterSlot gslot = (GetterSlot)getSlot(name, index,
SLOT_MODIFY_GETTER_SETTER);
gslot.setAttributes(attributes);
gslot.getter = null;
gslot.setter = null;
gslot.value = init;
}
/**
* Returns the prototype of the object.
*/
public Scriptable getPrototype()
{
return prototypeObject;
}
/**
* Sets the prototype of the object.
*/
public void setPrototype(Scriptable m)
{
prototypeObject = m;
}
/**
* Returns the parent (enclosing) scope of the object.
*/
public Scriptable getParentScope()
{
return parentScopeObject;
}
/**
* Sets the parent (enclosing) scope of the object.
*/
public void setParentScope(Scriptable m)
{
parentScopeObject = m;
}
/**
* Returns an array of ids for the properties of the object.
*
* <p>Any properties with the attribute DONTENUM are not listed. <p>
*
* @return an array of java.lang.Objects with an entry for every
* listed property. Properties accessed via an integer index will
* have a corresponding
* Integer entry in the returned array. Properties accessed by
* a String will have a String entry in the returned array.
*/
public Object[] getIds() {
return getIds(false);
}
/**
* Returns an array of ids for the properties of the object.
*
* <p>All properties, even those with attribute DONTENUM, are listed. <p>
*
* @return an array of java.lang.Objects with an entry for every
* listed property. Properties accessed via an integer index will
* have a corresponding
* Integer entry in the returned array. Properties accessed by
* a String will have a String entry in the returned array.
*/
public Object[] getAllIds() {
return getIds(true);
}
/**
* Implements the [[DefaultValue]] internal method.
*
* <p>Note that the toPrimitive conversion is a no-op for
* every type other than Object, for which [[DefaultValue]]
* is called. See ECMA 9.1.<p>
*
* A <code>hint</code> of null means "no hint".
*
* @param typeHint the type hint
* @return the default value for the object
*
* See ECMA 8.6.2.6.
*/
public Object getDefaultValue(Class<?> typeHint)
{
return getDefaultValue(this, typeHint);
}
public static Object getDefaultValue(Scriptable object, Class<?> typeHint)
{
Context cx = null;
for (int i=0; i < 2; i++) {
boolean tryToString;
if (typeHint == ScriptRuntime.StringClass) {
tryToString = (i == 0);
} else {
tryToString = (i == 1);
}
String methodName;
Object[] args;
if (tryToString) {
methodName = "toString";
args = ScriptRuntime.emptyArgs;
} else {
methodName = "valueOf";
args = new Object[1];
String hint;
if (typeHint == null) {
hint = "undefined";
} else if (typeHint == ScriptRuntime.StringClass) {
hint = "string";
} else if (typeHint == ScriptRuntime.ScriptableClass) {
hint = "object";
} else if (typeHint == ScriptRuntime.FunctionClass) {
hint = "function";
} else if (typeHint == ScriptRuntime.BooleanClass
|| typeHint == Boolean.TYPE)
{
hint = "boolean";
} else if (typeHint == ScriptRuntime.NumberClass ||
typeHint == ScriptRuntime.ByteClass ||
typeHint == Byte.TYPE ||
typeHint == ScriptRuntime.ShortClass ||
typeHint == Short.TYPE ||
typeHint == ScriptRuntime.IntegerClass ||
typeHint == Integer.TYPE ||
typeHint == ScriptRuntime.FloatClass ||
typeHint == Float.TYPE ||
typeHint == ScriptRuntime.DoubleClass ||
typeHint == Double.TYPE)
{
hint = "number";
} else {
throw Context.reportRuntimeError1(
"msg.invalid.type", typeHint.toString());
}
args[0] = hint;
}
Object v = getProperty(object, methodName);
if (!(v instanceof Function))
continue;
Function fun = (Function) v;
if (cx == null)
cx = Context.getContext();
v = fun.call(cx, fun.getParentScope(), object, args);
if (v != null) {
if (!(v instanceof Scriptable)) {
return v;
}
if (typeHint == ScriptRuntime.ScriptableClass
|| typeHint == ScriptRuntime.FunctionClass)
{
return v;
}
if (tryToString && v instanceof Wrapper) {
// Let a wrapped java.lang.String pass for a primitive
// string.
Object u = ((Wrapper)v).unwrap();
if (u instanceof String)
return u;
}
}
}
// fall through to error
String arg = (typeHint == null) ? "undefined" : typeHint.getName();
throw ScriptRuntime.typeError1("msg.default.value", arg);
}
/**
* Implements the instanceof operator.
*
* <p>This operator has been proposed to ECMA.
*
* @param instance The value that appeared on the LHS of the instanceof
* operator
* @return true if "this" appears in value's prototype chain
*
*/
public boolean hasInstance(Scriptable instance) {
// Default for JS objects (other than Function) is to do prototype
// chasing. This will be overridden in NativeFunction and non-JS
// objects.
return ScriptRuntime.jsDelegatesTo(instance, this);
}
/**
* Emulate the SpiderMonkey (and Firefox) feature of allowing
* custom objects to avoid detection by normal "object detection"
* code patterns. This is used to implement document.all.
* See https://bugzilla.mozilla.org/show_bug.cgi?id=412247.
* This is an analog to JOF_DETECTING from SpiderMonkey; see
* https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
* Other than this special case, embeddings should return false.
* @return true if this object should avoid object detection
* @since 1.7R1
*/
public boolean avoidObjectDetection() {
return false;
}
/**
* Custom <tt>==</tt> operator.
* Must return {@link Scriptable#NOT_FOUND} if this object does not
* have custom equality operator for the given value,
* <tt>Boolean.TRUE</tt> if this object is equivalent to <tt>value</tt>,
* <tt>Boolean.FALSE</tt> if this object is not equivalent to
* <tt>value</tt>.
* <p>
* The default implementation returns Boolean.TRUE
* if <tt>this == value</tt> or {@link Scriptable#NOT_FOUND} otherwise.
* It indicates that by default custom equality is available only if
* <tt>value</tt> is <tt>this</tt> in which case true is returned.
*/
protected Object equivalentValues(Object value)
{
return (this == value) ? Boolean.TRUE : Scriptable.NOT_FOUND;
}
/**
* Defines JavaScript objects from a Java class that implements Scriptable.
*
* If the given class has a method
* <pre>
* static void init(Context cx, Scriptable scope, boolean sealed);</pre>
*
* or its compatibility form
* <pre>
* static void init(Scriptable scope);</pre>
*
* then it is invoked and no further initialization is done.<p>
*
* However, if no such a method is found, then the class's constructors and
* methods are used to initialize a class in the following manner.<p>
*
* First, the zero-parameter constructor of the class is called to
* create the prototype. If no such constructor exists,
* a {@link EvaluatorException} is thrown. <p>
*
* Next, all methods are scanned for special prefixes that indicate that they
* have special meaning for defining JavaScript objects.
* These special prefixes are
* <ul>
* <li><code>jsFunction_</code> for a JavaScript function
* <li><code>jsStaticFunction_</code> for a JavaScript function that
* is a property of the constructor
* <li><code>jsGet_</code> for a getter of a JavaScript property
* <li><code>jsSet_</code> for a setter of a JavaScript property
* <li><code>jsConstructor</code> for a JavaScript function that
* is the constructor
* </ul><p>
*
* If the method's name begins with "jsFunction_", a JavaScript function
* is created with a name formed from the rest of the Java method name
* following "jsFunction_". So a Java method named "jsFunction_foo" will
* define a JavaScript method "foo". Calling this JavaScript function
* will cause the Java method to be called. The parameters of the method
* must be of number and types as defined by the FunctionObject class.
* The JavaScript function is then added as a property
* of the prototype. <p>
*
* If the method's name begins with "jsStaticFunction_", it is handled
* similarly except that the resulting JavaScript function is added as a
* property of the constructor object. The Java method must be static.
*
* If the method's name begins with "jsGet_" or "jsSet_", the method is
* considered to define a property. Accesses to the defined property
* will result in calls to these getter and setter methods. If no
* setter is defined, the property is defined as READONLY.<p>
*
* If the method's name is "jsConstructor", the method is
* considered to define the body of the constructor. Only one
* method of this name may be defined. You may use the varargs forms
* for constructors documented in {@link FunctionObject#FunctionObject(String, Member, Scriptable)}
*
* If no method is found that can serve as constructor, a Java
* constructor will be selected to serve as the JavaScript
* constructor in the following manner. If the class has only one
* Java constructor, that constructor is used to define
* the JavaScript constructor. If the the class has two constructors,
* one must be the zero-argument constructor (otherwise an
* {@link EvaluatorException} would have already been thrown
* when the prototype was to be created). In this case
* the Java constructor with one or more parameters will be used
* to define the JavaScript constructor. If the class has three
* or more constructors, an {@link EvaluatorException}
* will be thrown.<p>
*
* Finally, if there is a method
* <pre>
* static void finishInit(Scriptable scope, FunctionObject constructor,
* Scriptable prototype)</pre>
*
* it will be called to finish any initialization. The <code>scope</code>
* argument will be passed, along with the newly created constructor and
* the newly created prototype.<p>
*
* @param scope The scope in which to define the constructor.
* @param clazz The Java class to use to define the JavaScript objects
* and properties.
* @exception IllegalAccessException if access is not available
* to a reflected class member
* @exception InstantiationException if unable to instantiate
* the named class
* @exception InvocationTargetException if an exception is thrown
* during execution of methods of the named class
* @see org.mozilla.javascript.Function
* @see org.mozilla.javascript.FunctionObject
* @see org.mozilla.javascript.ScriptableObject#READONLY
* @see org.mozilla.javascript.ScriptableObject
* #defineProperty(String, Class, int)
*/
public static <T extends Scriptable> void defineClass(
Scriptable scope, Class<T> clazz)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
defineClass(scope, clazz, false, false);
}
/**
* Defines JavaScript objects from a Java class, optionally
* allowing sealing.
*
* Similar to <code>defineClass(Scriptable scope, Class clazz)</code>
* except that sealing is allowed. An object that is sealed cannot have
* properties added or removed. Note that sealing is not allowed in
* the current ECMA/ISO language specification, but is likely for
* the next version.
*
* @param scope The scope in which to define the constructor.
* @param clazz The Java class to use to define the JavaScript objects
* and properties. The class must implement Scriptable.
* @param sealed Whether or not to create sealed standard objects that
* cannot be modified.
* @exception IllegalAccessException if access is not available
* to a reflected class member
* @exception InstantiationException if unable to instantiate
* the named class
* @exception InvocationTargetException if an exception is thrown
* during execution of methods of the named class
* @since 1.4R3
*/
public static <T extends Scriptable> void defineClass(
Scriptable scope, Class<T> clazz, boolean sealed)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
defineClass(scope, clazz, sealed, false);
}
/**
* Defines JavaScript objects from a Java class, optionally
* allowing sealing and mapping of Java inheritance to JavaScript
* prototype-based inheritance.
*
* Similar to <code>defineClass(Scriptable scope, Class clazz)</code>
* except that sealing and inheritance mapping are allowed. An object
* that is sealed cannot have properties added or removed. Note that
* sealing is not allowed in the current ECMA/ISO language specification,
* but is likely for the next version.
*
* @param scope The scope in which to define the constructor.
* @param clazz The Java class to use to define the JavaScript objects
* and properties. The class must implement Scriptable.
* @param sealed Whether or not to create sealed standard objects that
* cannot be modified.
* @param mapInheritance Whether or not to map Java inheritance to
* JavaScript prototype-based inheritance.
* @return the class name for the prototype of the specified class
* @exception IllegalAccessException if access is not available
* to a reflected class member
* @exception InstantiationException if unable to instantiate
* the named class
* @exception InvocationTargetException if an exception is thrown
* during execution of methods of the named class
* @since 1.6R2
*/
public static <T extends Scriptable> String defineClass(
Scriptable scope, Class<T> clazz, boolean sealed,
boolean mapInheritance)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
BaseFunction ctor = buildClassCtor(scope, clazz, sealed,
mapInheritance);
if (ctor == null)
return null;
String name = ctor.getClassPrototype().getClassName();
defineProperty(scope, name, ctor, ScriptableObject.DONTENUM);
return name;
}
static <T extends Scriptable> BaseFunction buildClassCtor(
Scriptable scope, Class<T> clazz,
boolean sealed,
boolean mapInheritance)
throws IllegalAccessException, InstantiationException,
InvocationTargetException
{
Method[] methods = FunctionObject.getMethodList(clazz);
for (int i=0; i < methods.length; i++) {
Method method = methods[i];
if (!method.getName().equals("init"))
continue;
Class<?>[] parmTypes = method.getParameterTypes();
if (parmTypes.length == 3 &&
parmTypes[0] == ScriptRuntime.ContextClass &&
parmTypes[1] == ScriptRuntime.ScriptableClass &&
parmTypes[2] == Boolean.TYPE &&
Modifier.isStatic(method.getModifiers()))
{
Object args[] = { Context.getContext(), scope,
sealed ? Boolean.TRUE : Boolean.FALSE };
method.invoke(null, args);
return null;
}
if (parmTypes.length == 1 &&
parmTypes[0] == ScriptRuntime.ScriptableClass &&
Modifier.isStatic(method.getModifiers()))
{
Object args[] = { scope };
method.invoke(null, args);
return null;
}
}
// If we got here, there isn't an "init" method with the right
// parameter types.
Constructor<?>[] ctors = clazz.getConstructors();
Constructor<?> protoCtor = null;
for (int i=0; i < ctors.length; i++) {
if (ctors[i].getParameterTypes().length == 0) {
protoCtor = ctors[i];
break;
}
}
if (protoCtor == null) {
throw Context.reportRuntimeError1(
"msg.zero.arg.ctor", clazz.getName());
}
Scriptable proto = (Scriptable) protoCtor.newInstance(ScriptRuntime.emptyArgs);
String className = proto.getClassName();
// Set the prototype's prototype, trying to map Java inheritance to JS
// prototype-based inheritance if requested to do so.
Scriptable superProto = null;
if (mapInheritance) {
Class<? super T> superClass = clazz.getSuperclass();
if (ScriptRuntime.ScriptableClass.isAssignableFrom(superClass) &&
!Modifier.isAbstract(superClass.getModifiers()))
{
Class<? extends Scriptable> superScriptable =
extendsScriptable(superClass);
String name = ScriptableObject.defineClass(scope,
superScriptable, sealed, mapInheritance);
if (name != null) {
superProto = ScriptableObject.getClassPrototype(scope, name);
}
}
}
if (superProto == null) {
superProto = ScriptableObject.getObjectPrototype(scope);
}
proto.setPrototype(superProto);
// Find out whether there are any methods that begin with
// "js". If so, then only methods that begin with special
// prefixes will be defined as JavaScript entities.
final String functionPrefix = "jsFunction_";
final String staticFunctionPrefix = "jsStaticFunction_";
final String getterPrefix = "jsGet_";
final String setterPrefix = "jsSet_";
final String ctorName = "jsConstructor";
Member ctorMember = findAnnotatedMember(methods, JSConstructor.class);
if (ctorMember == null) {
ctorMember = findAnnotatedMember(ctors, JSConstructor.class);
}
if (ctorMember == null) {
ctorMember = FunctionObject.findSingleMethod(methods, ctorName);
}
if (ctorMember == null) {
if (ctors.length == 1) {
ctorMember = ctors[0];
} else if (ctors.length == 2) {
if (ctors[0].getParameterTypes().length == 0)
ctorMember = ctors[1];
else if (ctors[1].getParameterTypes().length == 0)
ctorMember = ctors[0];
}
if (ctorMember == null) {
throw Context.reportRuntimeError1(
"msg.ctor.multiple.parms", clazz.getName());
}
}
FunctionObject ctor = new FunctionObject(className, ctorMember, scope);
if (ctor.isVarArgsMethod()) {
throw Context.reportRuntimeError1
("msg.varargs.ctor", ctorMember.getName());
}
ctor.initAsConstructor(scope, proto);
Method finishInit = null;
HashSet<String> staticNames = new HashSet<String>(),
instanceNames = new HashSet<String>();
for (Method method : methods) {
if (method == ctorMember) {
continue;
}
String name = method.getName();
if (name.equals("finishInit")) {
Class<?>[] parmTypes = method.getParameterTypes();
if (parmTypes.length == 3 &&
parmTypes[0] == ScriptRuntime.ScriptableClass &&
parmTypes[1] == FunctionObject.class &&
parmTypes[2] == ScriptRuntime.ScriptableClass &&
Modifier.isStatic(method.getModifiers()))
{
finishInit = method;
continue;
}
}
// ignore any compiler generated methods.
if (name.indexOf('$') != -1)
continue;
if (name.equals(ctorName))
continue;
Annotation annotation = null;
String prefix = null;
if (method.isAnnotationPresent(JSFunction.class)) {
annotation = method.getAnnotation(JSFunction.class);
} else if (method.isAnnotationPresent(JSStaticFunction.class)) {
annotation = method.getAnnotation(JSStaticFunction.class);
} else if (method.isAnnotationPresent(JSGetter.class)) {
annotation = method.getAnnotation(JSGetter.class);
} else if (method.isAnnotationPresent(JSSetter.class)) {
continue;
}
if (annotation == null) {
if (name.startsWith(functionPrefix)) {
prefix = functionPrefix;
} else if (name.startsWith(staticFunctionPrefix)) {
prefix = staticFunctionPrefix;
} else if (name.startsWith(getterPrefix)) {
prefix = getterPrefix;
} else if (annotation == null) {
// note that setterPrefix is among the unhandled names here -
// we deal with that when we see the getter
continue;
}
}
boolean isStatic = annotation instanceof JSStaticFunction
|| prefix == staticFunctionPrefix;
HashSet<String> names = isStatic ? staticNames : instanceNames;
String propName = getPropertyName(name, prefix, annotation);
if (names.contains(propName)) {
throw Context.reportRuntimeError2("duplicate.defineClass.name",
name, propName);
}
names.add(propName);
name = propName;
if (annotation instanceof JSGetter || prefix == getterPrefix) {
if (!(proto instanceof ScriptableObject)) {
throw Context.reportRuntimeError2(
"msg.extend.scriptable",
proto.getClass().toString(), name);
}
Method setter = findSetterMethod(methods, name, setterPrefix);
int attr = ScriptableObject.PERMANENT |
ScriptableObject.DONTENUM |
(setter != null ? 0
: ScriptableObject.READONLY);
((ScriptableObject) proto).defineProperty(name, null,
method, setter,
attr);
continue;
}
if (isStatic && !Modifier.isStatic(method.getModifiers())) {
throw Context.reportRuntimeError(
"jsStaticFunction must be used with static method.");
}
FunctionObject f = new FunctionObject(name, method, proto);
if (f.isVarArgsConstructor()) {
throw Context.reportRuntimeError1
("msg.varargs.fun", ctorMember.getName());
}
defineProperty(isStatic ? ctor : proto, name, f, DONTENUM);
if (sealed) {
f.sealObject();
}
}
// Call user code to complete initialization if necessary.
if (finishInit != null) {
Object[] finishArgs = { scope, ctor, proto };
finishInit.invoke(null, finishArgs);
}
// Seal the object if necessary.
if (sealed) {
ctor.sealObject();
if (proto instanceof ScriptableObject) {
((ScriptableObject) proto).sealObject();
}
}
return ctor;
}
private static Member findAnnotatedMember(AccessibleObject[] members,
Class<? extends Annotation> annotation) {
for (AccessibleObject member : members) {
if (member.isAnnotationPresent(annotation)) {
return (Member) member;
}
}
return null;
}
private static Method findSetterMethod(Method[] methods,
String name,
String prefix) {
String newStyleName = "set"
+ Character.toUpperCase(name.charAt(0))
+ name.substring(1);
for (Method method : methods) {
JSSetter annotation = method.getAnnotation(JSSetter.class);
if (annotation != null) {
if (name.equals(annotation.value()) ||
("".equals(annotation.value()) && newStyleName.equals(method.getName()))) {
return method;
}
}
}
String oldStyleName = prefix + name;
for (Method method : methods) {
if (oldStyleName.equals(method.getName())) {
return method;
}
}
return null;
}
private static String getPropertyName(String methodName,
String prefix,
Annotation annotation) {
if (prefix != null) {
return methodName.substring(prefix.length());
}
String propName = null;
if (annotation instanceof JSGetter) {
propName = ((JSGetter) annotation).value();
if (propName == null || propName.length() == 0) {
if (methodName.length() > 3 && methodName.startsWith("get")) {
propName = methodName.substring(3);
if (Character.isUpperCase(propName.charAt(0))) {
if (propName.length() == 1) {
propName = propName.toLowerCase();
} else if (!Character.isUpperCase(propName.charAt(1))){
propName = Character.toLowerCase(propName.charAt(0))
+ propName.substring(1);
}
}
}
}
} else if (annotation instanceof JSFunction) {
propName = ((JSFunction) annotation).value();
} else if (annotation instanceof JSStaticFunction) {
propName = ((JSStaticFunction) annotation).value();
}
if (propName == null || propName.length() == 0) {
propName = methodName;
}
return propName;
}
@SuppressWarnings({"unchecked"})
private static <T extends Scriptable> Class<T> extendsScriptable(Class<?> c)
{
if (ScriptRuntime.ScriptableClass.isAssignableFrom(c))
return (Class<T>) c;
return null;
}
/**
* Define a JavaScript property.
*
* Creates the property with an initial value and sets its attributes.
*
* @param propertyName the name of the property to define.
* @param value the initial value of the property
* @param attributes the attributes of the JavaScript property
* @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object)
*/
public void defineProperty(String propertyName, Object value,
int attributes)
{
checkNotSealed(propertyName, 0);
put(propertyName, this, value);
setAttributes(propertyName, attributes);
}
/**
* Utility method to add properties to arbitrary Scriptable object.
* If destination is instance of ScriptableObject, calls
* defineProperty there, otherwise calls put in destination
* ignoring attributes
*/
public static void defineProperty(Scriptable destination,
String propertyName, Object value,
int attributes)
{
if (!(destination instanceof ScriptableObject)) {
destination.put(propertyName, destination, value);
return;
}
ScriptableObject so = (ScriptableObject)destination;
so.defineProperty(propertyName, value, attributes);
}
/**
* Utility method to add properties to arbitrary Scriptable object.
* If destination is instance of ScriptableObject, calls
* defineProperty there, otherwise calls put in destination
* ignoring attributes
*/
public static void defineConstProperty(Scriptable destination,
String propertyName)
{
if (destination instanceof ConstProperties) {
ConstProperties cp = (ConstProperties)destination;
cp.defineConst(propertyName, destination);
} else
defineProperty(destination, propertyName, Undefined.instance, CONST);
}
/**
* Define a JavaScript property with getter and setter side effects.
*
* If the setter is not found, the attribute READONLY is added to
* the given attributes. <p>
*
* The getter must be a method with zero parameters, and the setter, if
* found, must be a method with one parameter.<p>
*
* @param propertyName the name of the property to define. This name
* also affects the name of the setter and getter
* to search for. If the propertyId is "foo", then
* <code>clazz</code> will be searched for "getFoo"
* and "setFoo" methods.
* @param clazz the Java class to search for the getter and setter
* @param attributes the attributes of the JavaScript property
* @see org.mozilla.javascript.Scriptable#put(String, Scriptable, Object)
*/
public void defineProperty(String propertyName, Class<?> clazz,
int attributes)
{
int length = propertyName.length();
if (length == 0) throw new IllegalArgumentException();
char[] buf = new char[3 + length];
propertyName.getChars(0, length, buf, 3);
buf[3] = Character.toUpperCase(buf[3]);
buf[0] = 'g';
buf[1] = 'e';
buf[2] = 't';
String getterName = new String(buf);
buf[0] = 's';
String setterName = new String(buf);
Method[] methods = FunctionObject.getMethodList(clazz);
Method getter = FunctionObject.findSingleMethod(methods, getterName);
Method setter = FunctionObject.findSingleMethod(methods, setterName);
if (setter == null)
attributes |= ScriptableObject.READONLY;
defineProperty(propertyName, null, getter,
setter == null ? null : setter, attributes);
}
/**
* Define a JavaScript property.
*
* Use this method only if you wish to define getters and setters for
* a given property in a ScriptableObject. To create a property without
* special getter or setter side effects, use
* <code>defineProperty(String,int)</code>.
*
* If <code>setter</code> is null, the attribute READONLY is added to
* the given attributes.<p>
*
* Several forms of getters or setters are allowed. In all cases the
* type of the value parameter can be any one of the following types:
* Object, String, boolean, Scriptable, byte, short, int, long, float,
* or double. The runtime will perform appropriate conversions based
* upon the type of the parameter (see description in FunctionObject).
* The first forms are nonstatic methods of the class referred to
* by 'this':
* <pre>
* Object getFoo();
* void setFoo(SomeType value);</pre>
* Next are static methods that may be of any class; the object whose
* property is being accessed is passed in as an extra argument:
* <pre>
* static Object getFoo(Scriptable obj);
* static void setFoo(Scriptable obj, SomeType value);</pre>
* Finally, it is possible to delegate to another object entirely using
* the <code>delegateTo</code> parameter. In this case the methods are
* nonstatic methods of the class delegated to, and the object whose
* property is being accessed is passed in as an extra argument:
* <pre>
* Object getFoo(Scriptable obj);
* void setFoo(Scriptable obj, SomeType value);</pre>
*
* @param propertyName the name of the property to define.
* @param delegateTo an object to call the getter and setter methods on,
* or null, depending on the form used above.
* @param getter the method to invoke to get the value of the property
* @param setter the method to invoke to set the value of the property
* @param attributes the attributes of the JavaScript property
*/
public void defineProperty(String propertyName, Object delegateTo,
Method getter, Method setter, int attributes)
{
MemberBox getterBox = null;
if (getter != null) {
getterBox = new MemberBox(getter);
boolean delegatedForm;
if (!Modifier.isStatic(getter.getModifiers())) {
delegatedForm = (delegateTo != null);
getterBox.delegateTo = delegateTo;
} else {
delegatedForm = true;
// Ignore delegateTo for static getter but store
// non-null delegateTo indicator.
getterBox.delegateTo = Void.TYPE;
}
String errorId = null;
Class<?>[] parmTypes = getter.getParameterTypes();
if (parmTypes.length == 0) {
if (delegatedForm) {
errorId = "msg.obj.getter.parms";
}
} else if (parmTypes.length == 1) {
Object argType = parmTypes[0];
// Allow ScriptableObject for compatibility
if (!(argType == ScriptRuntime.ScriptableClass ||
argType == ScriptRuntime.ScriptableObjectClass))
{
errorId = "msg.bad.getter.parms";
} else if (!delegatedForm) {
errorId = "msg.bad.getter.parms";
}
} else {
errorId = "msg.bad.getter.parms";
}
if (errorId != null) {
throw Context.reportRuntimeError1(errorId, getter.toString());
}
}
MemberBox setterBox = null;
if (setter != null) {
if (setter.getReturnType() != Void.TYPE)
throw Context.reportRuntimeError1("msg.setter.return",
setter.toString());
setterBox = new MemberBox(setter);
boolean delegatedForm;
if (!Modifier.isStatic(setter.getModifiers())) {
delegatedForm = (delegateTo != null);
setterBox.delegateTo = delegateTo;
} else {
delegatedForm = true;
// Ignore delegateTo for static setter but store
// non-null delegateTo indicator.
setterBox.delegateTo = Void.TYPE;
}
String errorId = null;
Class<?>[] parmTypes = setter.getParameterTypes();
if (parmTypes.length == 1) {
if (delegatedForm) {
errorId = "msg.setter2.expected";
}
} else if (parmTypes.length == 2) {
Object argType = parmTypes[0];
// Allow ScriptableObject for compatibility
if (!(argType == ScriptRuntime.ScriptableClass ||
argType == ScriptRuntime.ScriptableObjectClass))
{
errorId = "msg.setter2.parms";
} else if (!delegatedForm) {
errorId = "msg.setter1.parms";
}
} else {
errorId = "msg.setter.parms";
}
if (errorId != null) {
throw Context.reportRuntimeError1(errorId, setter.toString());
}
}
GetterSlot gslot = (GetterSlot)getSlot(propertyName, 0,
SLOT_MODIFY_GETTER_SETTER);
gslot.setAttributes(attributes);
gslot.getter = getterBox;
gslot.setter = setterBox;
}
public void defineOwnProperties(Context cx, ScriptableObject props) {
Object[] ids = props.getIds();
for (Object id : ids) {
String name = ScriptRuntime.toString(id);
Object descObj = props.get(id);
ScriptableObject desc = ensureScriptableObject(descObj);
checkValidPropertyDefinition(getSlot(name, 0, SLOT_QUERY), desc);
}
for (Object id : ids) {
String name = ScriptRuntime.toString(id);
ScriptableObject desc = (ScriptableObject) props.get(id);
defineOwnProperty(cx, name, desc, false);
}
}
/**
* Defines a property on an object
*
* Based on [[DefineOwnProperty]] from 8.12.10 of the spec
*
* @param cx the current Context
* @param id the name/index of the property
* @param desc the new property descriptor, as described in 8.6.1
*/
public void defineOwnProperty(Context cx, Object id, ScriptableObject desc) {
defineOwnProperty(cx, id, desc, true);
}
private void defineOwnProperty(Context cx, Object id, ScriptableObject desc,
boolean checkValid) {
Slot slot = getSlot(cx, id, SLOT_QUERY);
if (checkValid)
checkValidPropertyDefinition(slot, desc);
boolean isAccessor = isAccessorDescriptor(desc);
final int attributes;
if (slot == null) { // new slot
slot = getSlot(cx, id, isAccessor ? SLOT_MODIFY_GETTER_SETTER : SLOT_MODIFY);
attributes = applyDescriptorToAttributeBitset(DONTENUM|READONLY|PERMANENT, desc);
} else {
attributes = applyDescriptorToAttributeBitset(slot.getAttributes(), desc);
}
slot = unwrapSlot(slot);
if (isAccessor) {
if ( !(slot instanceof GetterSlot) ) {
slot = getSlot(cx, id, SLOT_MODIFY_GETTER_SETTER);
}
GetterSlot gslot = (GetterSlot) slot;
Object getter = getProperty(desc, "get");
if (getter != NOT_FOUND) {
gslot.getter = getter;
}
Object setter = getProperty(desc, "set");
if (setter != NOT_FOUND) {
gslot.setter = setter;
}
gslot.value = Undefined.instance;
gslot.setAttributes(attributes);
} else {
if (slot instanceof GetterSlot && isDataDescriptor(desc)) {
slot = getSlot(cx, id, SLOT_CONVERT_ACCESSOR_TO_DATA);
}
Object value = getProperty(desc, "value");
if (value != NOT_FOUND) {
slot.value = value;
}
slot.setAttributes(attributes);
}
}
private void checkValidPropertyDefinition(Slot slot, ScriptableObject desc) {
Object getter = getProperty(desc, "get");
if (getter != NOT_FOUND && getter != Undefined.instance && !(getter instanceof Callable)) {
throw ScriptRuntime.notFunctionError(getter);
}
Object setter = getProperty(desc, "set");
if (setter != NOT_FOUND && setter != Undefined.instance && !(setter instanceof Callable)) {
throw ScriptRuntime.notFunctionError(setter);
}
if (isDataDescriptor(desc) && isAccessorDescriptor(desc)) {
throw ScriptRuntime.typeError0("msg.both.data.and.accessor.desc");
}
if (slot == null) { // new property
if (!isExtensible()) throw ScriptRuntime.typeError0("msg.not.extensible");
} else {
ScriptableObject current = slot.getPropertyDescriptor(Context.getContext(), this);
if (isFalse(current.get("configurable", current))) {
String id = slot.name != null ?
slot.name : Integer.toString(slot.indexOrHash);
if (isTrue(getProperty(desc, "configurable")))
throw ScriptRuntime.typeError1(
"msg.change.configurable.false.to.true", id);
if (isTrue(current.get("enumerable", current)) != isTrue(getProperty(desc, "enumerable")))
throw ScriptRuntime.typeError1(
"msg.change.enumerable.with.configurable.false", id);
if (isGenericDescriptor(desc)) {
// no further validation required
} else if (isDataDescriptor(desc) && isDataDescriptor(current)) {
if (isFalse(current.get("writable", current))) {
if (isTrue(getProperty(desc, "writable")))
throw ScriptRuntime.typeError1(
"msg.change.writable.false.to.true.with.configurable.false", id);
if (changes(current.get("value", current), getProperty(desc, "value")))
throw ScriptRuntime.typeError1(
"msg.change.value.with.writable.false", id);
}
} else if (isAccessorDescriptor(desc) && isAccessorDescriptor(current)) {
if (changes(current.get("set", current), setter))
throw ScriptRuntime.typeError1(
"msg.change.setter.with.configurable.false", id);
if (changes(current.get("get", current), getter))
throw ScriptRuntime.typeError1(
"msg.change.getter.with.configurable.false", id);
} else {
if (isDataDescriptor(current))
throw ScriptRuntime.typeError1(
"msg.change.property.data.to.accessor.with.configurable.false", id);
else
throw ScriptRuntime.typeError1(
"msg.change.property.accessor.to.data.with.configurable.false", id);
}
}
}
}
protected static boolean isTrue(Object value) {
return (value == NOT_FOUND) ? false : ScriptRuntime.toBoolean(value);
}
protected static boolean isFalse(Object value) {
return !isTrue(value);
}
private boolean changes(Object currentValue, Object newValue) {
if (newValue == NOT_FOUND) return false;
if (currentValue == NOT_FOUND) {
currentValue = Undefined.instance;
}
return !ScriptRuntime.shallowEq(currentValue, newValue);
}
protected int applyDescriptorToAttributeBitset(int attributes,
ScriptableObject desc)
{
Object enumerable = getProperty(desc, "enumerable");
if (enumerable != NOT_FOUND) {
attributes = ScriptRuntime.toBoolean(enumerable)
? attributes & ~DONTENUM : attributes | DONTENUM;
}
Object writable = getProperty(desc, "writable");
if (writable != NOT_FOUND) {
attributes = ScriptRuntime.toBoolean(writable)
? attributes & ~READONLY : attributes | READONLY;
}
Object configurable = getProperty(desc, "configurable");
if (configurable != NOT_FOUND) {
attributes = ScriptRuntime.toBoolean(configurable)
? attributes & ~PERMANENT : attributes | PERMANENT;
}
return attributes;
}
protected boolean isDataDescriptor(ScriptableObject desc) {
return hasProperty(desc, "value") || hasProperty(desc, "writable");
}
protected boolean isAccessorDescriptor(ScriptableObject desc) {
return hasProperty(desc, "get") || hasProperty(desc, "set");
}
protected boolean isGenericDescriptor(ScriptableObject desc) {
return !isDataDescriptor(desc) && !isAccessorDescriptor(desc);
}
protected Scriptable ensureScriptable(Object arg) {
if ( !(arg instanceof Scriptable) )
throw ScriptRuntime.typeError1("msg.arg.not.object", ScriptRuntime.typeof(arg));
return (Scriptable) arg;
}
protected ScriptableObject ensureScriptableObject(Object arg) {
if ( !(arg instanceof ScriptableObject) )
throw ScriptRuntime.typeError1("msg.arg.not.object", ScriptRuntime.typeof(arg));
return (ScriptableObject) arg;
}
/**
* Search for names in a class, adding the resulting methods
* as properties.
*
* <p> Uses reflection to find the methods of the given names. Then
* FunctionObjects are constructed from the methods found, and
* are added to this object as properties with the given names.
*
* @param names the names of the Methods to add as function properties
* @param clazz the class to search for the Methods
* @param attributes the attributes of the new properties
* @see org.mozilla.javascript.FunctionObject
*/
public void defineFunctionProperties(String[] names, Class<?> clazz,
int attributes)
{
Method[] methods = FunctionObject.getMethodList(clazz);
for (int i=0; i < names.length; i++) {
String name = names[i];
Method m = FunctionObject.findSingleMethod(methods, name);
if (m == null) {
throw Context.reportRuntimeError2(
"msg.method.not.found", name, clazz.getName());
}
FunctionObject f = new FunctionObject(name, m, this);
defineProperty(name, f, attributes);
}
}
/**
* Get the Object.prototype property.
* See ECMA 15.2.4.
*/
public static Scriptable getObjectPrototype(Scriptable scope) {
return TopLevel.getBuiltinPrototype(getTopLevelScope(scope),
TopLevel.Builtins.Object);
}
/**
* Get the Function.prototype property.
* See ECMA 15.3.4.
*/
public static Scriptable getFunctionPrototype(Scriptable scope) {
return TopLevel.getBuiltinPrototype(getTopLevelScope(scope),
TopLevel.Builtins.Function);
}
public static Scriptable getArrayPrototype(Scriptable scope) {
return TopLevel.getBuiltinPrototype(getTopLevelScope(scope),
TopLevel.Builtins.Array);
}
/**
* Get the prototype for the named class.
*
* For example, <code>getClassPrototype(s, "Date")</code> will first
* walk up the parent chain to find the outermost scope, then will
* search that scope for the Date constructor, and then will
* return Date.prototype. If any of the lookups fail, or
* the prototype is not a JavaScript object, then null will
* be returned.
*
* @param scope an object in the scope chain
* @param className the name of the constructor
* @return the prototype for the named class, or null if it
* cannot be found.
*/
public static Scriptable getClassPrototype(Scriptable scope,
String className)
{
scope = getTopLevelScope(scope);
Object ctor = getProperty(scope, className);
Object proto;
if (ctor instanceof BaseFunction) {
proto = ((BaseFunction)ctor).getPrototypeProperty();
} else if (ctor instanceof Scriptable) {
Scriptable ctorObj = (Scriptable)ctor;
proto = ctorObj.get("prototype", ctorObj);
} else {
return null;
}
if (proto instanceof Scriptable) {
return (Scriptable)proto;
}
return null;
}
/**
* Get the global scope.
*
* <p>Walks the parent scope chain to find an object with a null
* parent scope (the global object).
*
* @param obj a JavaScript object
* @return the corresponding global scope
*/
public static Scriptable getTopLevelScope(Scriptable obj)
{
for (;;) {
Scriptable parent = obj.getParentScope();
if (parent == null) {
return obj;
}
obj = parent;
}
}
public boolean isExtensible() {
return isExtensible;
}
public void preventExtensions() {
isExtensible = false;
}
/**
* Seal this object.
*
* It is an error to add properties to or delete properties from
* a sealed object. It is possible to change the value of an
* existing property. Once an object is sealed it may not be unsealed.
*
* @since 1.4R3
*/
public synchronized void sealObject() {
if (count >= 0) {
// Make sure all LazilyLoadedCtors are initialized before sealing.
Slot slot = firstAdded;
while (slot != null) {
Object value = slot.value;
if (value instanceof LazilyLoadedCtor) {
LazilyLoadedCtor initializer = (LazilyLoadedCtor) value;
try {
initializer.init();
} finally {
slot.value = initializer.getValue();
}
}
slot = slot.orderedNext;
}
count = ~count;
}
}
/**
* Return true if this object is sealed.
*
* @return true if sealed, false otherwise.
* @since 1.4R3
* @see #sealObject()
*/
public final boolean isSealed() {
return count < 0;
}
private void checkNotSealed(String name, int index)
{
if (!isSealed())
return;
String str = (name != null) ? name : Integer.toString(index);
throw Context.reportRuntimeError1("msg.modify.sealed", str);
}
/**
* Gets a named property from an object or any object in its prototype chain.
* <p>
* Searches the prototype chain for a property named <code>name</code>.
* <p>
* @param obj a JavaScript object
* @param name a property name
* @return the value of a property with name <code>name</code> found in
* <code>obj</code> or any object in its prototype chain, or
* <code>Scriptable.NOT_FOUND</code> if not found
* @since 1.5R2
*/
public static Object getProperty(Scriptable obj, String name)
{
Scriptable start = obj;
Object result;
do {
result = obj.get(name, start);
if (result != Scriptable.NOT_FOUND)
break;
obj = obj.getPrototype();
} while (obj != null);
return result;
}
/**
* Gets an indexed property from an object or any object in its prototype
* chain and coerces it to the requested Java type.
* <p>
* Searches the prototype chain for a property with integral index
* <code>index</code>. Note that if you wish to look for properties with numerical
* but non-integral indicies, you should use getProperty(Scriptable,String) with
* the string value of the index.
* <p>
* @param s a JavaScript object
* @param index an integral index
* @param type the required Java type of the result
* @return the value of a property with name <code>name</code> found in
* <code>obj</code> or any object in its prototype chain, or
* null if not found. Note that it does not return
* {@link Scriptable#NOT_FOUND} as it can ordinarily not be
* converted to most of the types.
* @since 1.7R3
*/
public static <T> T getTypedProperty(Scriptable s, int index, Class<T> type) {
Object val = getProperty(s, index);
if(val == Scriptable.NOT_FOUND) {
val = null;
}
return type.cast(Context.jsToJava(val, type));
}
/**
* Gets an indexed property from an object or any object in its prototype chain.
* <p>
* Searches the prototype chain for a property with integral index
* <code>index</code>. Note that if you wish to look for properties with numerical
* but non-integral indicies, you should use getProperty(Scriptable,String) with
* the string value of the index.
* <p>
* @param obj a JavaScript object
* @param index an integral index
* @return the value of a property with index <code>index</code> found in
* <code>obj</code> or any object in its prototype chain, or
* <code>Scriptable.NOT_FOUND</code> if not found
* @since 1.5R2
*/
public static Object getProperty(Scriptable obj, int index)
{
Scriptable start = obj;
Object result;
do {
result = obj.get(index, start);
if (result != Scriptable.NOT_FOUND)
break;
obj = obj.getPrototype();
} while (obj != null);
return result;
}
/**
* Gets a named property from an object or any object in its prototype chain
* and coerces it to the requested Java type.
* <p>
* Searches the prototype chain for a property named <code>name</code>.
* <p>
* @param s a JavaScript object
* @param name a property name
* @param type the required Java type of the result
* @return the value of a property with name <code>name</code> found in
* <code>obj</code> or any object in its prototype chain, or
* null if not found. Note that it does not return
* {@link Scriptable#NOT_FOUND} as it can ordinarily not be
* converted to most of the types.
* @since 1.7R3
*/
public static <T> T getTypedProperty(Scriptable s, String name, Class<T> type) {
Object val = getProperty(s, name);
if(val == Scriptable.NOT_FOUND) {
val = null;
}
return type.cast(Context.jsToJava(val, type));
}
/**
* Returns whether a named property is defined in an object or any object
* in its prototype chain.
* <p>
* Searches the prototype chain for a property named <code>name</code>.
* <p>
* @param obj a JavaScript object
* @param name a property name
* @return the true if property was found
* @since 1.5R2
*/
public static boolean hasProperty(Scriptable obj, String name)
{
return null != getBase(obj, name);
}
/**
* If hasProperty(obj, name) would return true, then if the property that
* was found is compatible with the new property, this method just returns.
* If the property is not compatible, then an exception is thrown.
*
* A property redefinition is incompatible if the first definition was a
* const declaration or if this one is. They are compatible only if neither
* was const.
*/
public static void redefineProperty(Scriptable obj, String name,
boolean isConst)
{
Scriptable base = getBase(obj, name);
if (base == null)
return;
if (base instanceof ConstProperties) {
ConstProperties cp = (ConstProperties)base;
if (cp.isConst(name))
throw Context.reportRuntimeError1("msg.const.redecl", name);
}
if (isConst)
throw Context.reportRuntimeError1("msg.var.redecl", name);
}
/**
* Returns whether an indexed property is defined in an object or any object
* in its prototype chain.
* <p>
* Searches the prototype chain for a property with index <code>index</code>.
* <p>
* @param obj a JavaScript object
* @param index a property index
* @return the true if property was found
* @since 1.5R2
*/
public static boolean hasProperty(Scriptable obj, int index)
{
return null != getBase(obj, index);
}
/**
* Puts a named property in an object or in an object in its prototype chain.
* <p>
* Searches for the named property in the prototype chain. If it is found,
* the value of the property in <code>obj</code> is changed through a call
* to {@link Scriptable#put(String, Scriptable, Object)} on the
* prototype passing <code>obj</code> as the <code>start</code> argument.
* This allows the prototype to veto the property setting in case the
* prototype defines the property with [[ReadOnly]] attribute. If the
* property is not found, it is added in <code>obj</code>.
* @param obj a JavaScript object
* @param name a property name
* @param value any JavaScript value accepted by Scriptable.put
* @since 1.5R2
*/
public static void putProperty(Scriptable obj, String name, Object value)
{
Scriptable base = getBase(obj, name);
if (base == null)
base = obj;
base.put(name, obj, value);
}
/**
* Puts a named property in an object or in an object in its prototype chain.
* <p>
* Searches for the named property in the prototype chain. If it is found,
* the value of the property in <code>obj</code> is changed through a call
* to {@link Scriptable#put(String, Scriptable, Object)} on the
* prototype passing <code>obj</code> as the <code>start</code> argument.
* This allows the prototype to veto the property setting in case the
* prototype defines the property with [[ReadOnly]] attribute. If the
* property is not found, it is added in <code>obj</code>.
* @param obj a JavaScript object
* @param name a property name
* @param value any JavaScript value accepted by Scriptable.put
* @since 1.5R2
*/
public static void putConstProperty(Scriptable obj, String name, Object value)
{
Scriptable base = getBase(obj, name);
if (base == null)
base = obj;
if (base instanceof ConstProperties)
((ConstProperties)base).putConst(name, obj, value);
}
/**
* Puts an indexed property in an object or in an object in its prototype chain.
* <p>
* Searches for the indexed property in the prototype chain. If it is found,
* the value of the property in <code>obj</code> is changed through a call
* to {@link Scriptable#put(int, Scriptable, Object)} on the prototype
* passing <code>obj</code> as the <code>start</code> argument. This allows
* the prototype to veto the property setting in case the prototype defines
* the property with [[ReadOnly]] attribute. If the property is not found,
* it is added in <code>obj</code>.
* @param obj a JavaScript object
* @param index a property index
* @param value any JavaScript value accepted by Scriptable.put
* @since 1.5R2
*/
public static void putProperty(Scriptable obj, int index, Object value)
{
Scriptable base = getBase(obj, index);
if (base == null)
base = obj;
base.put(index, obj, value);
}
/**
* Removes the property from an object or its prototype chain.
* <p>
* Searches for a property with <code>name</code> in obj or
* its prototype chain. If it is found, the object's delete
* method is called.
* @param obj a JavaScript object
* @param name a property name
* @return true if the property doesn't exist or was successfully removed
* @since 1.5R2
*/
public static boolean deleteProperty(Scriptable obj, String name)
{
Scriptable base = getBase(obj, name);
if (base == null)
return true;
base.delete(name);
return !base.has(name, obj);
}
/**
* Removes the property from an object or its prototype chain.
* <p>
* Searches for a property with <code>index</code> in obj or
* its prototype chain. If it is found, the object's delete
* method is called.
* @param obj a JavaScript object
* @param index a property index
* @return true if the property doesn't exist or was successfully removed
* @since 1.5R2
*/
public static boolean deleteProperty(Scriptable obj, int index)
{
Scriptable base = getBase(obj, index);
if (base == null)
return true;
base.delete(index);
return !base.has(index, obj);
}
/**
* Returns an array of all ids from an object and its prototypes.
* <p>
* @param obj a JavaScript object
* @return an array of all ids from all object in the prototype chain.
* If a given id occurs multiple times in the prototype chain,
* it will occur only once in this list.
* @since 1.5R2
*/
public static Object[] getPropertyIds(Scriptable obj)
{
if (obj == null) {
return ScriptRuntime.emptyArgs;
}
Object[] result = obj.getIds();
ObjToIntMap map = null;
for (;;) {
obj = obj.getPrototype();
if (obj == null) {
break;
}
Object[] ids = obj.getIds();
if (ids.length == 0) {
continue;
}
if (map == null) {
if (result.length == 0) {
result = ids;
continue;
}
map = new ObjToIntMap(result.length + ids.length);
for (int i = 0; i != result.length; ++i) {
map.intern(result[i]);
}
result = null; // Allow to GC the result
}
for (int i = 0; i != ids.length; ++i) {
map.intern(ids[i]);
}
}
if (map != null) {
result = map.getKeys();
}
return result;
}
/**
* Call a method of an object.
* @param obj the JavaScript object
* @param methodName the name of the function property
* @param args the arguments for the call
*
* @see Context#getCurrentContext()
*/
public static Object callMethod(Scriptable obj, String methodName,
Object[] args)
{
return callMethod(null, obj, methodName, args);
}
/**
* Call a method of an object.
* @param cx the Context object associated with the current thread.
* @param obj the JavaScript object
* @param methodName the name of the function property
* @param args the arguments for the call
*/
public static Object callMethod(Context cx, Scriptable obj,
String methodName,
Object[] args)
{
Object funObj = getProperty(obj, methodName);
if (!(funObj instanceof Function)) {
throw ScriptRuntime.notFunctionError(obj, methodName);
}
Function fun = (Function)funObj;
// XXX: What should be the scope when calling funObj?
// The following favor scope stored in the object on the assumption
// that is more useful especially under dynamic scope setup.
// An alternative is to check for dynamic scope flag
// and use ScriptableObject.getTopLevelScope(fun) if the flag is not
// set. But that require access to Context and messy code
// so for now it is not checked.
Scriptable scope = ScriptableObject.getTopLevelScope(obj);
if (cx != null) {
return fun.call(cx, scope, obj, args);
} else {
return Context.call(null, fun, scope, obj, args);
}
}
private static Scriptable getBase(Scriptable obj, String name)
{
do {
if (obj.has(name, obj))
break;
obj = obj.getPrototype();
} while(obj != null);
return obj;
}
private static Scriptable getBase(Scriptable obj, int index)
{
do {
if (obj.has(index, obj))
break;
obj = obj.getPrototype();
} while(obj != null);
return obj;
}
/**
* Get arbitrary application-specific value associated with this object.
* @param key key object to select particular value.
* @see #associateValue(Object key, Object value)
*/
public final Object getAssociatedValue(Object key)
{
Map<Object,Object> h = associatedValues;
if (h == null)
return null;
return h.get(key);
}
/**
* Get arbitrary application-specific value associated with the top scope
* of the given scope.
* The method first calls {@link #getTopLevelScope(Scriptable scope)}
* and then searches the prototype chain of the top scope for the first
* object containing the associated value with the given key.
*
* @param scope the starting scope.
* @param key key object to select particular value.
* @see #getAssociatedValue(Object key)
*/
public static Object getTopScopeValue(Scriptable scope, Object key)
{
scope = ScriptableObject.getTopLevelScope(scope);
for (;;) {
if (scope instanceof ScriptableObject) {
ScriptableObject so = (ScriptableObject)scope;
Object value = so.getAssociatedValue(key);
if (value != null) {
return value;
}
}
scope = scope.getPrototype();
if (scope == null) {
return null;
}
}
}
/**
* Associate arbitrary application-specific value with this object.
* Value can only be associated with the given object and key only once.
* The method ignores any subsequent attempts to change the already
* associated value.
* <p> The associated values are not serialized.
* @param key key object to select particular value.
* @param value the value to associate
* @return the passed value if the method is called first time for the
* given key or old value for any subsequent calls.
* @see #getAssociatedValue(Object key)
*/
public synchronized final Object associateValue(Object key, Object value)
{
if (value == null) throw new IllegalArgumentException();
Map<Object,Object> h = associatedValues;
if (h == null) {
h = new HashMap<Object,Object>();
associatedValues = h;
}
return Kit.initHash(h, key, value);
}
/**
*
* @param name
* @param index
* @param start
* @param value
* @return false if this != start and no slot was found. true if this == start
* or this != start and a READONLY slot was found.
*/
private boolean putImpl(String name, int index, Scriptable start,
Object value)
{
// This method is very hot (basically called on each assignment)
// so we inline the extensible/sealed checks below.
Slot slot;
if (this != start) {
slot = getSlot(name, index, SLOT_QUERY);
if (slot == null) {
return false;
}
} else if (!isExtensible) {
slot = getSlot(name, index, SLOT_QUERY);
if (slot == null) {
return true;
}
} else {
if (count < 0) checkNotSealed(name, index);
slot = getSlot(name, index, SLOT_MODIFY);
}
return slot.setValue(value, this, start);
}
/**
*
* @param name
* @param index
* @param start
* @param value
* @param constFlag EMPTY means normal put. UNINITIALIZED_CONST means
* defineConstProperty. READONLY means const initialization expression.
* @return false if this != start and no slot was found. true if this == start
* or this != start and a READONLY slot was found.
*/
private boolean putConstImpl(String name, int index, Scriptable start,
Object value, int constFlag)
{
assert (constFlag != EMPTY);
Slot slot;
if (this != start) {
slot = getSlot(name, index, SLOT_QUERY);
if (slot == null) {
return false;
}
} else if (!isExtensible()) {
slot = getSlot(name, index, SLOT_QUERY);
if (slot == null) {
return true;
}
} else {
checkNotSealed(name, index);
// either const hoisted declaration or initialization
slot = unwrapSlot(getSlot(name, index, SLOT_MODIFY_CONST));
int attr = slot.getAttributes();
if ((attr & READONLY) == 0)
throw Context.reportRuntimeError1("msg.var.redecl", name);
if ((attr & UNINITIALIZED_CONST) != 0) {
slot.value = value;
// clear the bit on const initialization
if (constFlag != UNINITIALIZED_CONST)
slot.setAttributes(attr & ~UNINITIALIZED_CONST);
}
return true;
}
return slot.setValue(value, this, start);
}
private Slot findAttributeSlot(String name, int index, int accessType)
{
Slot slot = getSlot(name, index, accessType);
if (slot == null) {
String str = (name != null ? name : Integer.toString(index));
throw Context.reportRuntimeError1("msg.prop.not.found", str);
}
return slot;
}
private static Slot unwrapSlot(Slot slot) {
return (slot instanceof RelinkedSlot) ? ((RelinkedSlot)slot).slot : slot;
}
/**
* Locate the slot with given name or index. Depending on the accessType
* parameter and the current slot status, a new slot may be allocated.
*
* @param name property name or null if slot holds spare array index.
* @param index index or 0 if slot holds property name.
*/
private Slot getSlot(String name, int index, int accessType)
{
// Check the hashtable without using synchronization
Slot[] slotsLocalRef = slots; // Get stable local reference
if (slotsLocalRef == null && accessType == SLOT_QUERY) {
return null;
}
int indexOrHash = (name != null ? name.hashCode() : index);
if (slotsLocalRef != null) {
Slot slot;
int slotIndex = getSlotIndex(slotsLocalRef.length, indexOrHash);
for (slot = slotsLocalRef[slotIndex];
slot != null;
slot = slot.next) {
Object sname = slot.name;
if (indexOrHash == slot.indexOrHash &&
(sname == name ||
(name != null && name.equals(sname)))) {
break;
}
}
switch (accessType) {
case SLOT_QUERY:
return slot;
case SLOT_MODIFY:
case SLOT_MODIFY_CONST:
if (slot != null)
return slot;
break;
case SLOT_MODIFY_GETTER_SETTER:
slot = unwrapSlot(slot);
if (slot instanceof GetterSlot)
return slot;
break;
case SLOT_CONVERT_ACCESSOR_TO_DATA:
slot = unwrapSlot(slot);
if ( !(slot instanceof GetterSlot) )
return slot;
break;
}
}
// A new slot has to be inserted or the old has to be replaced
// by GetterSlot. Time to synchronize.
return createSlot(name, indexOrHash, accessType);
}
private synchronized Slot createSlot(String name, int indexOrHash, int accessType) {
Slot[] slotsLocalRef = slots;
int insertPos;
if (count == 0) {
// Always throw away old slots if any on empty insert.
slotsLocalRef = new Slot[INITIAL_SLOT_SIZE];
slots = slotsLocalRef;
insertPos = getSlotIndex(slotsLocalRef.length, indexOrHash);
} else {
int tableSize = slotsLocalRef.length;
insertPos = getSlotIndex(tableSize, indexOrHash);
Slot prev = slotsLocalRef[insertPos];
Slot slot = prev;
while (slot != null) {
if (slot.indexOrHash == indexOrHash &&
(slot.name == name ||
(name != null && name.equals(slot.name))))
{
break;
}
prev = slot;
slot = slot.next;
}
if (slot != null) {
// Another thread just added a slot with same
// name/index before this one entered synchronized
// block. This is a race in application code and
// probably indicates bug there. But for the hashtable
// implementation it is harmless with the only
// complication is the need to replace the added slot
// if we need GetterSlot and the old one is not.
slot = unwrapSlot(slot);
Slot newSlot;
if (accessType == SLOT_MODIFY_GETTER_SETTER
&& !(slot instanceof GetterSlot)) {
newSlot = new GetterSlot(name, indexOrHash, slot.getAttributes());
} else if (accessType == SLOT_CONVERT_ACCESSOR_TO_DATA
&& (slot instanceof GetterSlot)) {
newSlot = new Slot(name, indexOrHash, slot.getAttributes());
} else if (accessType == SLOT_MODIFY_CONST) {
return null;
} else {
return slot;
}
newSlot.value = slot.value;
newSlot.next = slot.next;
// add new slot to linked list
if (lastAdded != null)
lastAdded.orderedNext = newSlot;
if (firstAdded == null)
firstAdded = newSlot;
lastAdded = newSlot;
// add new slot to hash table
if (prev == slot) {
slotsLocalRef[insertPos] = newSlot;
} else {
prev.next = newSlot;
}
// other housekeeping
slot.markDeleted();
return newSlot;
} else {
// Check if the table is not too full before inserting.
if (4 * (count + 1) > 3 * slotsLocalRef.length) {
// table size must be a power of 2, always grow by x2
slotsLocalRef = new Slot[slotsLocalRef.length * 2];
copyTable(slots, slotsLocalRef, count);
slots = slotsLocalRef;
insertPos = getSlotIndex(slotsLocalRef.length,
indexOrHash);
}
}
}
Slot newSlot = (accessType == SLOT_MODIFY_GETTER_SETTER
? new GetterSlot(name, indexOrHash, 0)
: new Slot(name, indexOrHash, 0));
if (accessType == SLOT_MODIFY_CONST)
newSlot.setAttributes(CONST);
++count;
// add new slot to linked list
if (lastAdded != null)
lastAdded.orderedNext = newSlot;
if (firstAdded == null)
firstAdded = newSlot;
lastAdded = newSlot;
// add new slot to hash table, return it
addKnownAbsentSlot(slotsLocalRef, newSlot, insertPos);
return newSlot;
}
private synchronized void removeSlot(String name, int index) {
int indexOrHash = (name != null ? name.hashCode() : index);
Slot[] slotsLocalRef = slots;
if (count != 0) {
int tableSize = slotsLocalRef.length;
int slotIndex = getSlotIndex(tableSize, indexOrHash);
Slot prev = slotsLocalRef[slotIndex];
Slot slot = prev;
while (slot != null) {
if (slot.indexOrHash == indexOrHash &&
(slot.name == name ||
(name != null && name.equals(slot.name))))
{
break;
}
prev = slot;
slot = slot.next;
}
if (slot != null && (slot.getAttributes() & PERMANENT) == 0) {
count--;
// remove slot from hash table
if (prev == slot) {
slotsLocalRef[slotIndex] = slot.next;
} else {
prev.next = slot.next;
}
// remove from ordered list. Previously this was done lazily in
// getIds() but delete is an infrequent operation so O(n)
// should be ok
// ordered list always uses the actual slot
Slot deleted = unwrapSlot(slot);
if (deleted == firstAdded) {
prev = null;
firstAdded = deleted.orderedNext;
} else {
prev = firstAdded;
while (prev.orderedNext != deleted) {
prev = prev.orderedNext;
}
prev.orderedNext = deleted.orderedNext;
}
if (deleted == lastAdded) {
lastAdded = prev;
}
// Mark the slot as removed.
slot.markDeleted();
}
}
}
private static int getSlotIndex(int tableSize, int indexOrHash)
{
// tableSize is a power of 2
return indexOrHash & (tableSize - 1);
}
// Must be inside synchronized (this)
private static void copyTable(Slot[] oldSlots, Slot[] newSlots, int count)
{
if (count == 0) throw Kit.codeBug();
int tableSize = newSlots.length;
int i = oldSlots.length;
for (;;) {
--i;
Slot slot = oldSlots[i];
while (slot != null) {
int insertPos = getSlotIndex(tableSize, slot.indexOrHash);
// If slot has next chain in old table use a new
// RelinkedSlot wrapper to keep old table valid
Slot insSlot = slot.next == null ? slot : new RelinkedSlot(slot);
addKnownAbsentSlot(newSlots, insSlot, insertPos);
slot = slot.next;
if (--count == 0)
return;
}
}
}
/**
* Add slot with keys that are known to absent from the table.
* This is an optimization to use when inserting into empty table,
* after table growth or during deserialization.
*/
private static void addKnownAbsentSlot(Slot[] slots, Slot slot,
int insertPos)
{
if (slots[insertPos] == null) {
slots[insertPos] = slot;
} else {
Slot prev = slots[insertPos];
Slot next = prev.next;
while (next != null) {
prev = next;
next = prev.next;
}
prev.next = slot;
}
}
Object[] getIds(boolean getAll) {
Slot[] s = slots;
Object[] a = ScriptRuntime.emptyArgs;
if (s == null)
return a;
int c = 0;
Slot slot = firstAdded;
while (slot != null && slot.wasDeleted) {
// we used to removed deleted slots from the linked list here
// but this is now done in removeSlot(). There may still be deleted
// slots (e.g. from slot conversion) but we don't want to mess
// with the list in unsynchronized code.
slot = slot.orderedNext;
}
while (slot != null) {
if (getAll || (slot.getAttributes() & DONTENUM) == 0) {
if (c == 0)
a = new Object[s.length];
a[c++] = slot.name != null
? slot.name
: Integer.valueOf(slot.indexOrHash);
}
slot = slot.orderedNext;
while (slot != null && slot.wasDeleted) {
// skip deleted slots, see comment above
slot = slot.orderedNext;
}
}
if (c == a.length)
return a;
Object[] result = new Object[c];
System.arraycopy(a, 0, result, 0, c);
return result;
}
private synchronized void writeObject(ObjectOutputStream out)
throws IOException
{
out.defaultWriteObject();
int objectsCount = count;
if (objectsCount < 0) {
// "this" was sealed
objectsCount = ~objectsCount;
}
if (objectsCount == 0) {
out.writeInt(0);
} else {
out.writeInt(slots.length);
Slot slot = firstAdded;
while (slot != null && slot.wasDeleted) {
// as long as we're traversing the order-added linked list,
// remove deleted slots
slot = slot.orderedNext;
}
firstAdded = slot;
while (slot != null) {
out.writeObject(slot);
Slot next = slot.orderedNext;
while (next != null && next.wasDeleted) {
// remove deleted slots
next = next.orderedNext;
}
slot.orderedNext = next;
slot = next;
}
}
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
int tableSize = in.readInt();
if (tableSize != 0) {
// If tableSize is not a power of 2 find the closest
// power of 2 >= the original size.
if ((tableSize & (tableSize - 1)) != 0) {
if (tableSize > 1 << 30)
throw new RuntimeException("Property table overflow");
int newSize = INITIAL_SLOT_SIZE;
while (newSize < tableSize)
newSize <<= 1;
tableSize = newSize;
}
slots = new Slot[tableSize];
int objectsCount = count;
if (objectsCount < 0) {
// "this" was sealed
objectsCount = ~objectsCount;
}
Slot prev = null;
for (int i=0; i != objectsCount; ++i) {
lastAdded = (Slot)in.readObject();
if (i==0) {
firstAdded = lastAdded;
} else {
prev.orderedNext = lastAdded;
}
int slotIndex = getSlotIndex(tableSize, lastAdded.indexOrHash);
addKnownAbsentSlot(slots, lastAdded, slotIndex);
prev = lastAdded;
}
}
}
protected ScriptableObject getOwnPropertyDescriptor(Context cx, Object id) {
Slot slot = getSlot(cx, id, SLOT_QUERY);
if (slot == null) return null;
Scriptable scope = getParentScope();
return slot.getPropertyDescriptor(cx, (scope == null ? this : scope));
}
protected Slot getSlot(Context cx, Object id, int accessType) {
String name = ScriptRuntime.toStringIdOrIndex(cx, id);
if (name == null) {
return getSlot(null, ScriptRuntime.lastIndexResult(cx), accessType);
} else {
return getSlot(name, 0, accessType);
}
}
// Partial implementation of java.util.Map. See NativeObject for
// a subclass that implements java.util.Map.
public int size() {
return count;
}
public boolean isEmpty() {
return count == 0;
}
public Object get(Object key) {
Object value = null;
if (key instanceof String) {
value = get((String) key, this);
} else if (key instanceof Number) {
value = get(((Number) key).intValue(), this);
}
if (value == Scriptable.NOT_FOUND || value == Undefined.instance) {
return null;
} else if (value instanceof Wrapper) {
return ((Wrapper) value).unwrap();
} else {
return value;
}
}
}
|
Fix size() and isEmpty() for sealed ScriptableObjects.
|
src/org/mozilla/javascript/ScriptableObject.java
|
Fix size() and isEmpty() for sealed ScriptableObjects.
|
|
Java
|
lgpl-2.1
|
7af8e2d267fd0c4c7a774d6bebb2efaf5fc10030
| 0
|
levants/lightmare
|
package org.lightmare.rest.utils;
import java.lang.reflect.Method;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import org.lightmare.rest.RestConfig;
import org.lightmare.utils.ObjectUtils;
/**
* Utility class for REST resources
*
* @author levan
*
*/
public class RestUtils {
private static boolean checkAnnotation(Method method) {
boolean valid = method.isAccessible()
&& method.isAnnotationPresent(GET.class)
|| method.isAnnotationPresent(POST.class)
|| method.isAnnotationPresent(PUT.class)
|| method.isAnnotationPresent(DELETE.class);
return valid;
}
private static boolean check(Class<?> resourceClass) {
boolean valid = resourceClass.isAnnotationPresent(Path.class);
Method[] methods = resourceClass.getDeclaredMethods();
int length = methods.length;
boolean isMethod = Boolean.FALSE;
Method method;
for (int i = 0; i < length && !isMethod; i++) {
method = methods[i];
isMethod = checkAnnotation(method);
}
return valid && isMethod;
}
public static void add(Class<?> beanClass) {
boolean valid = check(beanClass);
if (valid) {
RestConfig config = RestConfig.get();
if (ObjectUtils.notNull(config)) {
config.registerClass(beanClass);
}
}
}
public static void remove(Class<?> beanClass) {
RestConfig config = RestConfig.get();
if (ObjectUtils.notNull(config)) {
config.unregister(beanClass);
}
}
}
|
src/main/java/org/lightmare/rest/utils/RestUtils.java
|
package org.lightmare.rest.utils;
import java.lang.reflect.Method;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import org.lightmare.rest.RestConfig;
/**
* Utility class for REST resources
*
* @author levan
*
*/
public class RestUtils {
private static boolean checkAnnotation(Method method) {
boolean valid = method.isAccessible()
&& method.isAnnotationPresent(GET.class)
|| method.isAnnotationPresent(POST.class)
|| method.isAnnotationPresent(PUT.class)
|| method.isAnnotationPresent(DELETE.class);
return valid;
}
private static boolean check(Class<?> resourceClass) {
boolean valid = resourceClass.isAnnotationPresent(Path.class);
Method[] methods = resourceClass.getDeclaredMethods();
int length = methods.length;
boolean isMethod = Boolean.FALSE;
Method method;
for (int i = 0; i < length && !isMethod; i++) {
method = methods[i];
isMethod = checkAnnotation(method);
}
return valid && isMethod;
}
public static void add(Class<?> beanClass) {
boolean valid = check(beanClass);
if (valid) {
RestConfig config = RestConfig.get();
config.registerClass(beanClass);
}
}
public static void remove(Class<?> beanClass) {
RestConfig config = RestConfig.get();
config.unregister(beanClass);
}
}
|
improved RestUtils register and remove resources
|
src/main/java/org/lightmare/rest/utils/RestUtils.java
|
improved RestUtils register and remove resources
|
|
Java
|
apache-2.0
|
37c1508f1684e92e2b4b510f62189370817238cb
| 0
|
delzak/java_course,delzak/java_course
|
package ru.stqa.pft.homework;
public class Main {
public static void main(String[] args) {
Point p1 = new Point(20, 20);
Point p2 = new Point(40, 40);
CalculateDistance d = new CalculateDistance();
System.out.println("Точка 1 имеет координаты x = " + p1.x + " и y = " + p1.y + "\n" +
"Точка 2 имеет координаты x = " + p2.x + " и y = " + p2.y + "\n" +
"Расстояние между двумя точками = " + d.distance(p1, p2));
}
}
|
sandbox/src/main/java/ru/stqa/pft/homework/Main.java
|
package ru.stqa.pft.homework;
public class Main {
public static void main(String[] args) {
Point p1 = new Point(20, 20);
Point p2 = new Point(40, 40);
CalculateDistance d = new CalculateDistance();
System.out.println("Расстояние между двумя точками = " + d.distance(p1, p2));
}
}
|
Добавился вывод координат каждой из созданных точек
|
sandbox/src/main/java/ru/stqa/pft/homework/Main.java
|
Добавился вывод координат каждой из созданных точек
|
|
Java
|
apache-2.0
|
3621933c5eff4b14a07e99036e911e64ea4a46d2
| 0
|
BuddhistDigitalResourceCenter/xmltoldmigration,BuddhistDigitalResourceCenter/xmltoldmigration
|
package io.bdrc.xmltoldmigration;
/*******************************************************************************
* Copyright (c) 2014 Tibetan Buddhist Resource Center (TBRC)
*
* If this file is a derivation of another work the license header will appear below;
* otherwise, this work is licensed under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
/* This Java package implements the conversion between Unicode Tibetan text, and
Converter (EWTS) transliteration.
It is based on the equivalent Perl module, Lingua::BO::Converter, found at
http://www.digitaltibetan.org/cgi-bin/wylie.pl
The Extended Converter Transliteration System is documented at:
http://www.thlib.org/reference/transliteration/#essay=/thl/ewts/
OVERVIEW
========
This code is a library; it is meant to be embedded in other software.
import org.rigpa.wylie.Wylie;
...
Converter wl = new Converter();
System.out.println(wl.toUnicode("sems can thams cad"));
System.out.println(wl.toWylie("\u0f66\u0f44\u0f66\u0f0b\u0f62\u0f92\u0fb1\u0f66\u000a"));
From the command-line, you can use the provided "Test" and "TestToWylie"
programs, which requests lines in Converter from the user and prints the unicode to
stdout, and vice versa. Run them with:
java Test
java TestToWylie
To run the test suite, run this command:
javac -g RunTests.java && java RunTests < test.txt
CONSTRUCTOR
===========
Two constructors are available:
Converter wl = new Converter(); // uses all the default options
and
Converter wl = new Converter(check, check_strict, print_warnings, fix_spacing);
The meanings of the parameters are:
- check (boolean) : generate warnings for illegal consonant sequences; default is true.
- check_strict (boolean) : stricter checking, examine the whole stack; default is true.
- print_warnings (boolean) : print generated warnings to STDOUT; default is false.
- fix_spacing (boolean) : remove spaces after newlines, collapse multiple tseks into one, etc;
default is true.
PUBLIC METHODS
==============
String toUnicode(String wylie_string);
Converts from Converter (EWTS) to Unicode.
String toUnicode(String wylie_string, ArrayList<String> warns);
Converts from Converter (EWTS) to Unicode; puts the generated warnings in the list.
String toWylie(String unicode_string);
Converts from Unicode to Converter.
Anything that is not Tibetan Unicode is converted to EWTS comment blocks [between brackets].
String toWylie(String unicode_string, ArrayList<String> warns, boolean escape);
Converts from Unicode to Converter. Puts the generated warnings in the list.
If escape is false, anything that is not Tibetan Unicode is just passed through as it is.
PERFORMANCE AND CONCURRENCY
===========================
This code should perform quite decently. When converting from Converter to
Unicode, the entire string is split into tokens, which are themselves
strings. If this takes too much memory, consider converting your text in
smaller chunks. With today's computers, it should not be a problem to
convert several megabytes of tibetan text in one call. Otherwise, it could
be worthwhile to tokenize the input on the fly, rather than all at once.
This class is entirely thread-safe. In a multi-threaded environment,
multiple threads can share the same instance without any problems.
AUTHOR AND LICENSE
==================
Copyright (C) 2010 Roger Espel Llima
This library is Free Software. You can redistribute it or modify it, under
the terms of, at your choice, the GNU General Public License (version 2 or
higher), the GNU Lesser General Public License (version 2 or higher), the
Mozilla Public License (any version) or the Apache License version 2 or
higher.
Please contact the author if you wish to use it under some terms not covered
here.
Copyright 2011 TBRC
This library is Free Software. You can redistribute it or modify it, under
the terms of, at your choice, the GNU General Public License (version 2 or
higher), the GNU Lesser General Public License (version 2 or higher), the
Mozilla Public License (any version) or the Apache License version 2 or
higher.
Please contact support@tbrc.org if you wish to use it under some terms not covered
here.
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Converter {
// various options for Converter conversion
private boolean check, check_strict, print_warnings, fix_spacing;
// constant hashes and sets to help with the conversion
private static HashMap<String, String> m_consonant, m_subjoined, m_vowel, m_final_uni, m_final_class,
m_other, m_ambiguous_wylie, m_tib_vowel_long, m_tib_caret;
private static HashMap<Character, String> m_tib_top, m_tib_subjoined, m_tib_vowel, m_tib_final_wylie, m_tib_final_class,
m_tib_other;
private static HashMap<String, Integer> m_ambiguous_key;
private static HashMap<Character, Integer> m_tokens_start;
private static HashSet<String> m_special, m_suffixes, m_tib_stacks, m_tokens;
private static HashMap<String, HashSet<String>> m_superscripts, m_subscripts, m_prefixes, m_suff2;
// initialize all the hashes with the correspondences between Converter and Unicode.
// this gets called from a 'static section' to initialize the hashes the moment the
// class gets loaded.
private static final void initHashes() {
HashSet<String> tmpSet;
// mappings auto-generated from the Perl code
// *** Converter to Unicode mappings ***
// list of wylie consonant => unicode
m_consonant = new HashMap<String, String>();
m_consonant.put("k", "\u0f40");
m_consonant.put("kh", "\u0f41");
m_consonant.put("g", "\u0f42");
m_consonant.put("gh", "\u0f42\u0fb7");
m_consonant.put("g+h", "\u0f42\u0fb7");
m_consonant.put("ng", "\u0f44");
m_consonant.put("c", "\u0f45");
m_consonant.put("ch", "\u0f46");
m_consonant.put("j", "\u0f47");
m_consonant.put("ny", "\u0f49");
m_consonant.put("T", "\u0f4a");
m_consonant.put("-t", "\u0f4a");
m_consonant.put("Th", "\u0f4b");
m_consonant.put("-th", "\u0f4b");
m_consonant.put("D", "\u0f4c");
m_consonant.put("-d", "\u0f4c");
m_consonant.put("Dh", "\u0f4c\u0fb7");
m_consonant.put("D+h", "\u0f4c\u0fb7");
m_consonant.put("-dh", "\u0f4c\u0fb7");
m_consonant.put("-d+h", "\u0f4c\u0fb7");
m_consonant.put("N", "\u0f4e");
m_consonant.put("-n", "\u0f4e");
m_consonant.put("t", "\u0f4f");
m_consonant.put("th", "\u0f50");
m_consonant.put("d", "\u0f51");
m_consonant.put("dh", "\u0f51\u0fb7");
m_consonant.put("d+h", "\u0f51\u0fb7");
m_consonant.put("n", "\u0f53");
m_consonant.put("p", "\u0f54");
m_consonant.put("ph", "\u0f55");
m_consonant.put("b", "\u0f56");
m_consonant.put("bh", "\u0f56\u0fb7");
m_consonant.put("b+h", "\u0f56\u0fb7");
m_consonant.put("m", "\u0f58");
m_consonant.put("ts", "\u0f59");
m_consonant.put("tsh", "\u0f5a");
m_consonant.put("dz", "\u0f5b");
m_consonant.put("dzh", "\u0f5b\u0fb7");
m_consonant.put("dz+h", "\u0f5b\u0fb7");
m_consonant.put("w", "\u0f5d");
m_consonant.put("zh", "\u0f5e");
m_consonant.put("z", "\u0f5f");
m_consonant.put("'", "\u0f60");
m_consonant.put("\u2018", "\u0f60"); // typographic quotes
m_consonant.put("\u2019", "\u0f60");
m_consonant.put("y", "\u0f61");
m_consonant.put("r", "\u0f62");
m_consonant.put("l", "\u0f63");
m_consonant.put("sh", "\u0f64");
m_consonant.put("Sh", "\u0f65");
m_consonant.put("-sh", "\u0f65");
m_consonant.put("s", "\u0f66");
m_consonant.put("h", "\u0f67");
m_consonant.put("W", "\u0f5d");
m_consonant.put("Y", "\u0f61");
m_consonant.put("R", "\u0f6a");
m_consonant.put("f", "\u0f55\u0f39");
m_consonant.put("v", "\u0f56\u0f39");
// subjoined letters
m_subjoined = new HashMap<String, String>();
m_subjoined.put("k", "\u0f90");
m_subjoined.put("kh", "\u0f91");
m_subjoined.put("g", "\u0f92");
m_subjoined.put("gh", "\u0f92\u0fb7");
m_subjoined.put("g+h", "\u0f92\u0fb7");
m_subjoined.put("ng", "\u0f94");
m_subjoined.put("c", "\u0f95");
m_subjoined.put("ch", "\u0f96");
m_subjoined.put("j", "\u0f97");
m_subjoined.put("ny", "\u0f99");
m_subjoined.put("T", "\u0f9a");
m_subjoined.put("-t", "\u0f9a");
m_subjoined.put("Th", "\u0f9b");
m_subjoined.put("-th", "\u0f9b");
m_subjoined.put("D", "\u0f9c");
m_subjoined.put("-d", "\u0f9c");
m_subjoined.put("Dh", "\u0f9c\u0fb7");
m_subjoined.put("D+h", "\u0f9c\u0fb7");
m_subjoined.put("-dh", "\u0f9c\u0fb7");
m_subjoined.put("-d+h", "\u0f9c\u0fb7");
m_subjoined.put("N", "\u0f9e");
m_subjoined.put("-n", "\u0f9e");
m_subjoined.put("t", "\u0f9f");
m_subjoined.put("th", "\u0fa0");
m_subjoined.put("d", "\u0fa1");
m_subjoined.put("dh", "\u0fa1\u0fb7");
m_subjoined.put("d+h", "\u0fa1\u0fb7");
m_subjoined.put("n", "\u0fa3");
m_subjoined.put("p", "\u0fa4");
m_subjoined.put("ph", "\u0fa5");
m_subjoined.put("b", "\u0fa6");
m_subjoined.put("bh", "\u0fa6\u0fb7");
m_subjoined.put("b+h", "\u0fa6\u0fb7");
m_subjoined.put("m", "\u0fa8");
m_subjoined.put("ts", "\u0fa9");
m_subjoined.put("tsh", "\u0faa");
m_subjoined.put("dz", "\u0fab");
m_subjoined.put("dzh", "\u0fab\u0fb7");
m_subjoined.put("dz+h", "\u0fab\u0fb7");
m_subjoined.put("w", "\u0fad");
m_subjoined.put("zh", "\u0fae");
m_subjoined.put("z", "\u0faf");
m_subjoined.put("'", "\u0fb0");
m_subjoined.put("\u2018", "\u0fb0"); // typographic quotes
m_subjoined.put("\u2019", "\u0fb0");
m_subjoined.put("y", "\u0fb1");
m_subjoined.put("r", "\u0fb2");
m_subjoined.put("l", "\u0fb3");
m_subjoined.put("sh", "\u0fb4");
m_subjoined.put("Sh", "\u0fb5");
m_subjoined.put("-sh", "\u0fb5");
m_subjoined.put("s", "\u0fb6");
m_subjoined.put("h", "\u0fb7");
m_subjoined.put("a", "\u0fb8");
m_subjoined.put("W", "\u0fba");
m_subjoined.put("Y", "\u0fbb");
m_subjoined.put("R", "\u0fbc");
// vowels
m_vowel = new HashMap<String, String>();
m_vowel.put("a", "\u0f68");
m_vowel.put("A", "\u0f71");
m_vowel.put("i", "\u0f72");
m_vowel.put("I", "\u0f71\u0f72");
m_vowel.put("u", "\u0f74");
m_vowel.put("U", "\u0f71\u0f74");
m_vowel.put("e", "\u0f7a");
m_vowel.put("ai", "\u0f7b");
m_vowel.put("o", "\u0f7c");
m_vowel.put("au", "\u0f7d");
m_vowel.put("-i", "\u0f80");
m_vowel.put("-I", "\u0f71\u0f80");
// final symbols to unicode
m_final_uni = new HashMap<String, String>();
m_final_uni.put("M", "\u0f7e");
m_final_uni.put("~M`", "\u0f82");
m_final_uni.put("~M", "\u0f83");
m_final_uni.put("X", "\u0f37");
m_final_uni.put("~X", "\u0f35");
m_final_uni.put("H", "\u0f7f");
m_final_uni.put("?", "\u0f84");
m_final_uni.put("^", "\u0f39");
// final symbols organized by class
m_final_class = new HashMap<String, String>();
m_final_class.put("M", "M");
m_final_class.put("~M`", "M");
m_final_class.put("~M", "M");
m_final_class.put("X", "X");
m_final_class.put("~X", "X");
m_final_class.put("H", "H");
m_final_class.put("?", "?");
m_final_class.put("^", "^");
// other stand-alone symbols
m_other = new HashMap<String, String>();
m_other.put("0", "\u0f20");
m_other.put("1", "\u0f21");
m_other.put("2", "\u0f22");
m_other.put("3", "\u0f23");
m_other.put("4", "\u0f24");
m_other.put("5", "\u0f25");
m_other.put("6", "\u0f26");
m_other.put("7", "\u0f27");
m_other.put("8", "\u0f28");
m_other.put("9", "\u0f29");
m_other.put(" ", "\u0f0b");
m_other.put("*", "\u0f0c");
m_other.put("/", "\u0f0d");
m_other.put("//", "\u0f0e");
m_other.put(";", "\u0f0f");
m_other.put("|", "\u0f11");
m_other.put("!", "\u0f08");
m_other.put(":", "\u0f14");
m_other.put("_", " ");
m_other.put("=", "\u0f34");
m_other.put("<", "\u0f3a");
m_other.put(">", "\u0f3b");
m_other.put("(", "\u0f3c");
m_other.put(")", "\u0f3d");
m_other.put("@", "\u0f04");
m_other.put("#", "\u0f05");
m_other.put("$", "\u0f06");
m_other.put("%", "\u0f07");
// special characters: flag those if they occur out of context
m_special = new HashSet<String>();
m_special.add(".");
m_special.add("+");
m_special.add("-");
m_special.add("~");
m_special.add("^");
m_special.add("?");
m_special.add("`");
m_special.add("]");
// superscripts: hashmap of superscript => set of letters or stacks below
m_superscripts = new HashMap<String, HashSet<String>>();
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("g");
tmpSet.add("ng");
tmpSet.add("j");
tmpSet.add("ny");
tmpSet.add("t");
tmpSet.add("d");
tmpSet.add("n");
tmpSet.add("b");
tmpSet.add("m");
tmpSet.add("ts");
tmpSet.add("dz");
tmpSet.add("k+y");
tmpSet.add("g+y");
tmpSet.add("m+y");
tmpSet.add("b+w");
tmpSet.add("ts+w");
tmpSet.add("g+w");
m_superscripts.put("r", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("g");
tmpSet.add("ng");
tmpSet.add("c");
tmpSet.add("j");
tmpSet.add("t");
tmpSet.add("d");
tmpSet.add("p");
tmpSet.add("b");
tmpSet.add("h");
m_superscripts.put("l", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("g");
tmpSet.add("ng");
tmpSet.add("ny");
tmpSet.add("t");
tmpSet.add("d");
tmpSet.add("n");
tmpSet.add("p");
tmpSet.add("b");
tmpSet.add("m");
tmpSet.add("ts");
tmpSet.add("k+y");
tmpSet.add("g+y");
tmpSet.add("p+y");
tmpSet.add("b+y");
tmpSet.add("m+y");
tmpSet.add("k+r");
tmpSet.add("g+r");
tmpSet.add("p+r");
tmpSet.add("b+r");
tmpSet.add("m+r");
tmpSet.add("n+r");
m_superscripts.put("s", tmpSet);
// subscripts => set of letters above
m_subscripts = new HashMap<String, HashSet<String>>();
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("kh");
tmpSet.add("g");
tmpSet.add("p");
tmpSet.add("ph");
tmpSet.add("b");
tmpSet.add("m");
tmpSet.add("r+k");
tmpSet.add("r+g");
tmpSet.add("r+m");
tmpSet.add("s+k");
tmpSet.add("s+g");
tmpSet.add("s+p");
tmpSet.add("s+b");
tmpSet.add("s+m");
m_subscripts.put("y", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("kh");
tmpSet.add("g");
tmpSet.add("t");
tmpSet.add("th");
tmpSet.add("d");
tmpSet.add("n");
tmpSet.add("p");
tmpSet.add("ph");
tmpSet.add("b");
tmpSet.add("m");
tmpSet.add("sh");
tmpSet.add("s");
tmpSet.add("h");
tmpSet.add("dz");
tmpSet.add("s+k");
tmpSet.add("s+g");
tmpSet.add("s+p");
tmpSet.add("s+b");
tmpSet.add("s+m");
tmpSet.add("s+n");
m_subscripts.put("r", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("g");
tmpSet.add("b");
tmpSet.add("r");
tmpSet.add("s");
tmpSet.add("z");
m_subscripts.put("l", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("kh");
tmpSet.add("g");
tmpSet.add("c");
tmpSet.add("ny");
tmpSet.add("t");
tmpSet.add("d");
tmpSet.add("ts");
tmpSet.add("tsh");
tmpSet.add("zh");
tmpSet.add("z");
tmpSet.add("r");
tmpSet.add("l");
tmpSet.add("sh");
tmpSet.add("s");
tmpSet.add("h");
tmpSet.add("g+r");
tmpSet.add("d+r");
tmpSet.add("ph+y");
tmpSet.add("r+g");
tmpSet.add("r+ts");
m_subscripts.put("w", tmpSet);
// prefixes => set of consonants or stacks after
m_prefixes = new HashMap<String, HashSet<String>>();
tmpSet = new HashSet<String>();
tmpSet.add("c");
tmpSet.add("ny");
tmpSet.add("t");
tmpSet.add("d");
tmpSet.add("n");
tmpSet.add("ts");
tmpSet.add("zh");
tmpSet.add("z");
tmpSet.add("y");
tmpSet.add("sh");
tmpSet.add("s");
m_prefixes.put("g", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("g");
tmpSet.add("ng");
tmpSet.add("p");
tmpSet.add("b");
tmpSet.add("m");
tmpSet.add("k+y");
tmpSet.add("g+y");
tmpSet.add("p+y");
tmpSet.add("b+y");
tmpSet.add("m+y");
tmpSet.add("k+r");
tmpSet.add("g+r");
tmpSet.add("p+r");
tmpSet.add("b+r");
m_prefixes.put("d", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("g");
tmpSet.add("c");
tmpSet.add("t");
tmpSet.add("d");
tmpSet.add("ts");
tmpSet.add("zh");
tmpSet.add("z");
tmpSet.add("sh");
tmpSet.add("s");
tmpSet.add("r");
tmpSet.add("l");
tmpSet.add("k+y");
tmpSet.add("g+y");
tmpSet.add("k+r");
tmpSet.add("g+r");
tmpSet.add("r+l");
tmpSet.add("s+l");
tmpSet.add("r+k");
tmpSet.add("r+g");
tmpSet.add("r+ng");
tmpSet.add("r+j");
tmpSet.add("r+ny");
tmpSet.add("r+t");
tmpSet.add("r+d");
tmpSet.add("r+n");
tmpSet.add("r+ts");
tmpSet.add("r+dz");
tmpSet.add("s+k");
tmpSet.add("s+g");
tmpSet.add("s+ng");
tmpSet.add("s+ny");
tmpSet.add("s+t");
tmpSet.add("s+d");
tmpSet.add("s+n");
tmpSet.add("s+ts");
tmpSet.add("r+k+y");
tmpSet.add("r+g+y");
tmpSet.add("s+k+y");
tmpSet.add("s+g+y");
tmpSet.add("s+k+r");
tmpSet.add("s+g+r");
tmpSet.add("l+d");
tmpSet.add("l+t");
tmpSet.add("k+l");
tmpSet.add("s+r");
tmpSet.add("z+l");
tmpSet.add("s+w");
m_prefixes.put("b", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("kh");
tmpSet.add("g");
tmpSet.add("ng");
tmpSet.add("ch");
tmpSet.add("j");
tmpSet.add("ny");
tmpSet.add("th");
tmpSet.add("d");
tmpSet.add("n");
tmpSet.add("tsh");
tmpSet.add("dz");
tmpSet.add("kh+y");
tmpSet.add("g+y");
tmpSet.add("kh+r");
tmpSet.add("g+r");
m_prefixes.put("m", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("kh");
tmpSet.add("g");
tmpSet.add("ch");
tmpSet.add("j");
tmpSet.add("th");
tmpSet.add("d");
tmpSet.add("ph");
tmpSet.add("b");
tmpSet.add("tsh");
tmpSet.add("dz");
tmpSet.add("kh+y");
tmpSet.add("g+y");
tmpSet.add("ph+y");
tmpSet.add("b+y");
tmpSet.add("kh+r");
tmpSet.add("g+r");
tmpSet.add("d+r");
tmpSet.add("ph+r");
tmpSet.add("b+r");
m_prefixes.put("'", tmpSet);
m_prefixes.put("\u2018", tmpSet);
m_prefixes.put("\u2019", tmpSet);
// set of suffix letters
// also included are some Skt letters b/c they occur often in suffix position in Skt words
m_suffixes = new HashSet<String>();
m_suffixes.add("'");
m_suffixes.add("\u2018");
m_suffixes.add("\u2019");
m_suffixes.add("g");
m_suffixes.add("ng");
m_suffixes.add("d");
m_suffixes.add("n");
m_suffixes.add("b");
m_suffixes.add("m");
m_suffixes.add("r");
m_suffixes.add("l");
m_suffixes.add("s");
m_suffixes.add("N");
m_suffixes.add("T");
m_suffixes.add("-n");
m_suffixes.add("-t");
// suffix2 => set of letters before
m_suff2 = new HashMap<String, HashSet<String>>();
tmpSet = new HashSet<String>();
tmpSet.add("g");
tmpSet.add("ng");
tmpSet.add("b");
tmpSet.add("m");
m_suff2.put("s", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("n");
tmpSet.add("r");
tmpSet.add("l");
m_suff2.put("d", tmpSet);
// root letter index for very ambiguous three-stack syllables
m_ambiguous_key = new HashMap<String, Integer>();
m_ambiguous_key.put("dgs", 1);
m_ambiguous_key.put("dms", 1);
m_ambiguous_key.put("'gs", 1);
m_ambiguous_key.put("mngs", 0);
m_ambiguous_key.put("bgs", 0);
m_ambiguous_key.put("dbs", 1);
m_ambiguous_wylie = new HashMap<String, String>();
m_ambiguous_wylie.put("dgs", "dgas");
m_ambiguous_wylie.put("dms", "dmas");
m_ambiguous_wylie.put("'gs", "'gas");
m_ambiguous_wylie.put("mngs", "mangs");
m_ambiguous_wylie.put("bgs", "bags");
m_ambiguous_wylie.put("dbs", "dbas");
// *** Unicode to Converter mappings ***
// top letters
m_tib_top = new HashMap<Character, String>();
m_tib_top.put('\u0f40', "k");
m_tib_top.put('\u0f41', "kh");
m_tib_top.put('\u0f42', "g");
m_tib_top.put('\u0f43', "g+h");
m_tib_top.put('\u0f44', "ng");
m_tib_top.put('\u0f45', "c");
m_tib_top.put('\u0f46', "ch");
m_tib_top.put('\u0f47', "j");
m_tib_top.put('\u0f49', "ny");
m_tib_top.put('\u0f4a', "T");
m_tib_top.put('\u0f4b', "Th");
m_tib_top.put('\u0f4c', "D");
m_tib_top.put('\u0f4d', "D+h");
m_tib_top.put('\u0f4e', "N");
m_tib_top.put('\u0f4f', "t");
m_tib_top.put('\u0f50', "th");
m_tib_top.put('\u0f51', "d");
m_tib_top.put('\u0f52', "d+h");
m_tib_top.put('\u0f53', "n");
m_tib_top.put('\u0f54', "p");
m_tib_top.put('\u0f55', "ph");
m_tib_top.put('\u0f56', "b");
m_tib_top.put('\u0f57', "b+h");
m_tib_top.put('\u0f58', "m");
m_tib_top.put('\u0f59', "ts");
m_tib_top.put('\u0f5a', "tsh");
m_tib_top.put('\u0f5b', "dz");
m_tib_top.put('\u0f5c', "dz+h");
m_tib_top.put('\u0f5d', "w");
m_tib_top.put('\u0f5e', "zh");
m_tib_top.put('\u0f5f', "z");
m_tib_top.put('\u0f60', "'");
m_tib_top.put('\u0f61', "y");
m_tib_top.put('\u0f62', "r");
m_tib_top.put('\u0f63', "l");
m_tib_top.put('\u0f64', "sh");
m_tib_top.put('\u0f65', "Sh");
m_tib_top.put('\u0f66', "s");
m_tib_top.put('\u0f67', "h");
m_tib_top.put('\u0f68', "a");
m_tib_top.put('\u0f69', "k+Sh");
m_tib_top.put('\u0f6a', "R");
// subjoined letters
m_tib_subjoined = new HashMap<Character, String>();
m_tib_subjoined.put('\u0f90', "k");
m_tib_subjoined.put('\u0f91', "kh");
m_tib_subjoined.put('\u0f92', "g");
m_tib_subjoined.put('\u0f93', "g+h");
m_tib_subjoined.put('\u0f94', "ng");
m_tib_subjoined.put('\u0f95', "c");
m_tib_subjoined.put('\u0f96', "ch");
m_tib_subjoined.put('\u0f97', "j");
m_tib_subjoined.put('\u0f99', "ny");
m_tib_subjoined.put('\u0f9a', "T");
m_tib_subjoined.put('\u0f9b', "Th");
m_tib_subjoined.put('\u0f9c', "D");
m_tib_subjoined.put('\u0f9d', "D+h");
m_tib_subjoined.put('\u0f9e', "N");
m_tib_subjoined.put('\u0f9f', "t");
m_tib_subjoined.put('\u0fa0', "th");
m_tib_subjoined.put('\u0fa1', "d");
m_tib_subjoined.put('\u0fa2', "d+h");
m_tib_subjoined.put('\u0fa3', "n");
m_tib_subjoined.put('\u0fa4', "p");
m_tib_subjoined.put('\u0fa5', "ph");
m_tib_subjoined.put('\u0fa6', "b");
m_tib_subjoined.put('\u0fa7', "b+h");
m_tib_subjoined.put('\u0fa8', "m");
m_tib_subjoined.put('\u0fa9', "ts");
m_tib_subjoined.put('\u0faa', "tsh");
m_tib_subjoined.put('\u0fab', "dz");
m_tib_subjoined.put('\u0fac', "dz+h");
m_tib_subjoined.put('\u0fad', "w");
m_tib_subjoined.put('\u0fae', "zh");
m_tib_subjoined.put('\u0faf', "z");
m_tib_subjoined.put('\u0fb0', "'");
m_tib_subjoined.put('\u0fb1', "y");
m_tib_subjoined.put('\u0fb2', "r");
m_tib_subjoined.put('\u0fb3', "l");
m_tib_subjoined.put('\u0fb4', "sh");
m_tib_subjoined.put('\u0fb5', "Sh");
m_tib_subjoined.put('\u0fb6', "s");
m_tib_subjoined.put('\u0fb7', "h");
m_tib_subjoined.put('\u0fb8', "a");
m_tib_subjoined.put('\u0fb9', "k+Sh");
m_tib_subjoined.put('\u0fba', "W");
m_tib_subjoined.put('\u0fbb', "Y");
m_tib_subjoined.put('\u0fbc', "R");
// vowel signs:
// a-chen is not here because that's a top character, not a vowel sign.
// pre-composed "I" and "U" are dealt here; other pre-composed Skt vowels are more
// easily handled by a global replace in toWylie(), b/c they turn into subjoined "r"/"l".
m_tib_vowel = new HashMap<Character, String>();
m_tib_vowel.put('\u0f71', "A");
m_tib_vowel.put('\u0f72', "i");
m_tib_vowel.put('\u0f73', "I");
m_tib_vowel.put('\u0f74', "u");
m_tib_vowel.put('\u0f75', "U");
m_tib_vowel.put('\u0f7a', "e");
m_tib_vowel.put('\u0f7b', "ai");
m_tib_vowel.put('\u0f7c', "o");
m_tib_vowel.put('\u0f7d', "au");
m_tib_vowel.put('\u0f80', "-i");
// long (Skt) vowels
m_tib_vowel_long = new HashMap<String, String>();
m_tib_vowel_long.put("i", "I");
m_tib_vowel_long.put("u", "U");
m_tib_vowel_long.put("-i", "-I");
// final symbols => wylie
m_tib_final_wylie = new HashMap<Character, String>();
m_tib_final_wylie.put('\u0f7e', "M");
m_tib_final_wylie.put('\u0f82', "~M`");
m_tib_final_wylie.put('\u0f83', "~M");
m_tib_final_wylie.put('\u0f37', "X");
m_tib_final_wylie.put('\u0f35', "~X");
m_tib_final_wylie.put('\u0f39', "^");
m_tib_final_wylie.put('\u0f7f', "H");
m_tib_final_wylie.put('\u0f84', "?");
// final symbols by class
m_tib_final_class = new HashMap<Character, String>();
m_tib_final_class.put('\u0f7e', "M");
m_tib_final_class.put('\u0f82', "M");
m_tib_final_class.put('\u0f83', "M");
m_tib_final_class.put('\u0f37', "X");
m_tib_final_class.put('\u0f35', "X");
m_tib_final_class.put('\u0f39', "^");
m_tib_final_class.put('\u0f7f', "H");
m_tib_final_class.put('\u0f84', "?");
// special characters introduced by ^
m_tib_caret = new HashMap<String, String>();
m_tib_caret.put("ph", "f");
m_tib_caret.put("b", "v");
// other stand-alone characters
m_tib_other = new HashMap<Character, String>();
m_tib_other.put(' ', "_");
m_tib_other.put('\u0f04', "@");
m_tib_other.put('\u0f05', "#");
m_tib_other.put('\u0f06', "$");
m_tib_other.put('\u0f07', "%");
m_tib_other.put('\u0f08', "!");
m_tib_other.put('\u0f0b', " ");
m_tib_other.put('\u0f0c', "*");
m_tib_other.put('\u0f0d', "/");
m_tib_other.put('\u0f0e', "//");
m_tib_other.put('\u0f0f', ";");
m_tib_other.put('\u0f11', "|");
m_tib_other.put('\u0f14', ":");
m_tib_other.put('\u0f20', "0");
m_tib_other.put('\u0f21', "1");
m_tib_other.put('\u0f22', "2");
m_tib_other.put('\u0f23', "3");
m_tib_other.put('\u0f24', "4");
m_tib_other.put('\u0f25', "5");
m_tib_other.put('\u0f26', "6");
m_tib_other.put('\u0f27', "7");
m_tib_other.put('\u0f28', "8");
m_tib_other.put('\u0f29', "9");
m_tib_other.put('\u0f34', "=");
m_tib_other.put('\u0f3a', "<");
m_tib_other.put('\u0f3b', ">");
m_tib_other.put('\u0f3c', "(");
m_tib_other.put('\u0f3d', ")");
// all these stacked consonant combinations don't need "+"s in them
m_tib_stacks = new HashSet<String>();
m_tib_stacks.add("b+l");
m_tib_stacks.add("b+r");
m_tib_stacks.add("b+y");
m_tib_stacks.add("c+w");
m_tib_stacks.add("d+r");
m_tib_stacks.add("d+r+w");
m_tib_stacks.add("d+w");
m_tib_stacks.add("dz+r");
m_tib_stacks.add("g+l");
m_tib_stacks.add("g+r");
m_tib_stacks.add("g+r+w");
m_tib_stacks.add("g+w");
m_tib_stacks.add("g+y");
m_tib_stacks.add("h+r");
m_tib_stacks.add("h+w");
m_tib_stacks.add("k+l");
m_tib_stacks.add("k+r");
m_tib_stacks.add("k+w");
m_tib_stacks.add("k+y");
m_tib_stacks.add("kh+r");
m_tib_stacks.add("kh+w");
m_tib_stacks.add("kh+y");
m_tib_stacks.add("l+b");
m_tib_stacks.add("l+c");
m_tib_stacks.add("l+d");
m_tib_stacks.add("l+g");
m_tib_stacks.add("l+h");
m_tib_stacks.add("l+j");
m_tib_stacks.add("l+k");
m_tib_stacks.add("l+ng");
m_tib_stacks.add("l+p");
m_tib_stacks.add("l+t");
m_tib_stacks.add("l+w");
m_tib_stacks.add("m+r");
m_tib_stacks.add("m+y");
m_tib_stacks.add("n+r");
m_tib_stacks.add("ny+w");
m_tib_stacks.add("p+r");
m_tib_stacks.add("p+y");
m_tib_stacks.add("ph+r");
m_tib_stacks.add("ph+y");
m_tib_stacks.add("ph+y+w");
m_tib_stacks.add("r+b");
m_tib_stacks.add("r+d");
m_tib_stacks.add("r+dz");
m_tib_stacks.add("r+g");
m_tib_stacks.add("r+g+w");
m_tib_stacks.add("r+g+y");
m_tib_stacks.add("r+j");
m_tib_stacks.add("r+k");
m_tib_stacks.add("r+k+y");
m_tib_stacks.add("r+l");
m_tib_stacks.add("r+m");
m_tib_stacks.add("r+m+y");
m_tib_stacks.add("r+n");
m_tib_stacks.add("r+ng");
m_tib_stacks.add("r+ny");
m_tib_stacks.add("r+t");
m_tib_stacks.add("r+ts");
m_tib_stacks.add("r+ts+w");
m_tib_stacks.add("r+w");
m_tib_stacks.add("s+b");
m_tib_stacks.add("s+b+r");
m_tib_stacks.add("s+b+y");
m_tib_stacks.add("s+d");
m_tib_stacks.add("s+g");
m_tib_stacks.add("s+g+r");
m_tib_stacks.add("s+g+y");
m_tib_stacks.add("s+k");
m_tib_stacks.add("s+k+r");
m_tib_stacks.add("s+k+y");
m_tib_stacks.add("s+l");
m_tib_stacks.add("s+m");
m_tib_stacks.add("s+m+r");
m_tib_stacks.add("s+m+y");
m_tib_stacks.add("s+n");
m_tib_stacks.add("s+n+r");
m_tib_stacks.add("s+ng");
m_tib_stacks.add("s+ny");
m_tib_stacks.add("s+p");
m_tib_stacks.add("s+p+r");
m_tib_stacks.add("s+p+y");
m_tib_stacks.add("s+r");
m_tib_stacks.add("s+t");
m_tib_stacks.add("s+ts");
m_tib_stacks.add("s+w");
m_tib_stacks.add("sh+r");
m_tib_stacks.add("sh+w");
m_tib_stacks.add("t+r");
m_tib_stacks.add("t+w");
m_tib_stacks.add("th+r");
m_tib_stacks.add("ts+w");
m_tib_stacks.add("tsh+w");
m_tib_stacks.add("z+l");
m_tib_stacks.add("z+w");
m_tib_stacks.add("zh+w");
// a map used to split the input string into tokens for toUnicode().
// all letters which start tokens longer than one letter are mapped to the max length of
// tokens starting with that letter.
m_tokens_start = new HashMap<Character, Integer>();
m_tokens_start.put('S', 2);
m_tokens_start.put('/', 2);
m_tokens_start.put('d', 4);
m_tokens_start.put('g', 3);
m_tokens_start.put('b', 3);
m_tokens_start.put('D', 3);
m_tokens_start.put('z', 2);
m_tokens_start.put('~', 3);
m_tokens_start.put('-', 4);
m_tokens_start.put('T', 2);
m_tokens_start.put('a', 2);
m_tokens_start.put('k', 2);
m_tokens_start.put('t', 3);
m_tokens_start.put('s', 2);
m_tokens_start.put('c', 2);
m_tokens_start.put('n', 2);
m_tokens_start.put('p', 2);
m_tokens_start.put('\r', 2);
// also for tokenization - a set of tokens longer than one letter
m_tokens = new HashSet<String>();
m_tokens.add("-d+h");
m_tokens.add("dz+h");
m_tokens.add("-dh");
m_tokens.add("-sh");
m_tokens.add("-th");
m_tokens.add("D+h");
m_tokens.add("b+h");
m_tokens.add("d+h");
m_tokens.add("dzh");
m_tokens.add("g+h");
m_tokens.add("tsh");
m_tokens.add("~M`");
m_tokens.add("-I");
m_tokens.add("-d");
m_tokens.add("-i");
m_tokens.add("-n");
m_tokens.add("-t");
m_tokens.add("//");
m_tokens.add("Dh");
m_tokens.add("Sh");
m_tokens.add("Th");
m_tokens.add("ai");
m_tokens.add("au");
m_tokens.add("bh");
m_tokens.add("ch");
m_tokens.add("dh");
m_tokens.add("dz");
m_tokens.add("gh");
m_tokens.add("kh");
m_tokens.add("ng");
m_tokens.add("ny");
m_tokens.add("ph");
m_tokens.add("sh");
m_tokens.add("th");
m_tokens.add("ts");
m_tokens.add("zh");
m_tokens.add("~M");
m_tokens.add("~X");
m_tokens.add("\r\n");
}
static {
initHashes();
}
// setup a wylie object
private void initWylie(boolean check, boolean check_strict, boolean print_warnings, boolean fix_spacing) {
// check_strict requires check
if (check_strict && !check) {
throw new RuntimeException("check_strict requires check.");
}
this.check = check;
this.check_strict = check_strict;
this.print_warnings = print_warnings;
this.fix_spacing = fix_spacing;
}
// constructor passing all options
// see the comments at the beginning of this file for more details.
public Converter(boolean check, boolean check_strict, boolean print_warnings, boolean fix_spacing) {
initWylie(check, check_strict, print_warnings, fix_spacing);
}
// constructor with default options
public Converter() {
initWylie(true, true, false, true);
}
// helper functions to access the various hash tables
private final String consonant(String s) {
return m_consonant.get(s);
}
private final String subjoined(String s) {
return m_subjoined.get(s);
}
private final String vowel(String s) {
return m_vowel.get(s);
}
private final String final_uni(String s) {
return m_final_uni.get(s);
}
private final String final_class(String s) {
return m_final_class.get(s);
}
private final String other(String s) {
return m_other.get(s);
}
private final boolean isSpecial(String s) {
return m_special.contains(s);
}
private final boolean isSuperscript(String s) {
return m_superscripts.containsKey(s);
}
private final boolean superscript(String sup, String below) {
HashSet<?> tmpSet = m_superscripts.get(sup);
if (tmpSet == null) return false;
return tmpSet.contains(below);
}
private final boolean isSubscript(String s) {
return m_subscripts.containsKey(s);
}
private final boolean subscript(String sub, String above) {
HashSet<?> tmpSet = m_subscripts.get(sub);
if (tmpSet == null) return false;
return tmpSet.contains(above);
}
private final boolean isPrefix(String s) {
return m_prefixes.containsKey(s);
}
private final boolean prefix(String pref, String after) {
HashSet<?> tmpSet = m_prefixes.get(pref);
if (tmpSet == null) return false;
return tmpSet.contains(after);
}
private final boolean isSuffix(String s) {
return m_suffixes.contains(s);
}
private final boolean isSuff2(String s) {
return m_suff2.containsKey(s);
}
private final boolean suff2(String suff, String before) {
HashSet<?> tmpSet = m_suff2.get(suff);
if (tmpSet == null) return false;
return tmpSet.contains(before);
}
private final Integer ambiguous_key(String syll) {
return m_ambiguous_key.get(syll);
}
private final String ambiguous_wylie(String syll) {
return m_ambiguous_wylie.get(syll);
}
private final String tib_top(Character c) {
return m_tib_top.get(c);
}
private final String tib_subjoined(Character c) {
return m_tib_subjoined.get(c);
}
private final String tib_vowel(Character c) {
return m_tib_vowel.get(c);
}
private final String tib_vowel_long(String s) {
return m_tib_vowel_long.get(s);
}
private final String tib_final_wylie(Character c) {
return m_tib_final_wylie.get(c);
}
private final String tib_final_class(Character c) {
return m_tib_final_class.get(c);
}
private final String tib_caret(String s) {
return m_tib_caret.get(s);
}
private final String tib_other(Character c) {
return m_tib_other.get(c);
}
private final boolean tib_stack(String s) {
return m_tib_stacks.contains(s);
}
// split a string into Converter tokens;
// make sure there is room for at least one null element at the end of the array
private String[] splitIntoTokens(String str) {
String[] tokens = new String[str.length() + 2];
int o = 0, i = 0;
int maxlen = str.length();
TOKEN:
while (i < maxlen) {
char c = str.charAt(i);
Integer mlo = m_tokens_start.get(c);
// if there are multi-char tokens starting with this char, try them
if (mlo != null) {
for (int len = mlo.intValue(); len > 1; len--) {
if (i <= maxlen - len) {
String tr = str.substring(i, i + len);
if (m_tokens.contains(tr)) {
tokens[o++] = tr;
i += len;
continue TOKEN;
}
}
}
}
// things starting with backslash are special
if (c == '\\' && i <= maxlen - 2) {
if (str.charAt(i + 1) == 'u' && i <= maxlen - 6) {
tokens[o++] = str.substring(i, i + 6); // \\uxxxx
i += 6;
} else if (str.charAt(i + 1) == 'U' && i <= maxlen - 10) {
tokens[o++] = str.substring(i, i + 10); // \\Uxxxxxxxx
i += 10;
} else {
tokens[o++] = str.substring(i, i + 2); // \\x
i += 2;
}
continue TOKEN;
}
// otherwise just take one char
tokens[o++] = Character.toString(c);
i += 1;
}
return tokens;
}
/**
* Adjusts the input string based on the idea that people often are sloppy when writing
* Wylie and use ' ' instead of '_' when a space is actually meant in the output. This is
* written is a really simple brute force way to avoid issues of which regex's are supported
* in Javascript when translated via GWT. This routine does not handle the case of " /" which
* requires more care to accomodate "ng /" and "ngi /" and so on which are intentional since
* a tsheg is required in these cases. Also it is not feasible to handle "g " for a final "ga"
* at the end of a phrase where the '/' is usually omitted in favor of the descender on the
* "ga". Detecting this is non-trivial.
*
* @param str String to be normalized
* @return normalized String
*/
private String sloppyWylie(String str) {
str = str.replace(" (", "_(");
str = str.replace(") ", ")_");
str = str.replace("/ ", "/_");
str = str.replace(" 0", "_0");
str = str.replace(" 1", "_1");
str = str.replace(" 2", "_2");
str = str.replace(" 3", "_3");
str = str.replace(" 4", "_4");
str = str.replace(" 5", "_5");
str = str.replace(" 6", "_6");
str = str.replace(" 7", "_7");
str = str.replace(" 8", "_8");
str = str.replace(" 9", "_9");
str = str.replace("0 ", "0_");
str = str.replace("1 ", "1_");
str = str.replace("2 ", "2_");
str = str.replace("3 ", "3_");
str = str.replace("4 ", "4_");
str = str.replace("5 ", "5_");
str = str.replace("6 ", "6_");
str = str.replace("7 ", "7_");
str = str.replace("8 ", "8_");
str = str.replace("9 ", "9_");
str = str.replace("_ ", "__");
//str = str.replace("G", "g"); not converting because some strings contain things like "G844" which should output an error
str = str.replace("K", "k");
str = str.replace("Ch", "ch");
str = str.replace("B", "b");
str = str.replace(" M", "m");
str = str.replace("(M", "(m");
// convert S but not Sh:
str = str.replace("Sh", "ZZZ");
str = str.replace("S", "s");
str = str.replace("ZZZ", "Sh");
if (str.startsWith("M")) str = "m"+str.substring(1);
if (str.startsWith("G")) str = "g"+str.substring(1);
return str;
}
// Convenience function; convert to Converter to Unicode, without returning warnings
public String toUnicode(String str) {
return toUnicode(str, null, true);
}
// Converts a Converter (EWTS) string to unicode. If 'warns' is not the null List, puts warnings into it.
public String toUnicode(String str, List<String> warns, boolean sloppy) {
if (str == null) {
return " - no data - ";
}
if (sloppy) {
str = sloppyWylie(str);
}
StringBuilder out = new StringBuilder();
int line = 1;
int units = 0;
// remove initial spaces if required
if (this.fix_spacing) {
str = str.replaceFirst("^\\s+", "");
}
// split into tokens
String[] tokens = splitIntoTokens(str);
int i = 0;
// iterate over the tokens
ITER:
while (tokens[i] != null) {
String t = tokens[i];
String o;
// [non-tibetan text] : pass through, nesting brackets
if (t.equals("[")) {
int nesting = 1;
i++;
ESC:
while (tokens[i] != null) {
t = tokens[i++];
if (t.equals("[")) nesting++;
if (t.equals("]")) nesting--;
if (nesting == 0) continue ITER;
// handle unicode escapes and \1-char escapes within [comments]...
if (t.startsWith("\\u") || t.startsWith("\\U")) {
o = unicodeEscape(warns, line, t);
if (o != null) {
out.append(o);
continue ESC;
}
}
if (t.startsWith("\\")) {
o = t.substring(1);
} else {
o = t;
}
out.append(o);
}
warnl(warns, line, "Unfinished [non-Converter stuff].");
break ITER;
}
// punctuation, numbers, etc
o = other(t);
if (o != null) {
out.append(o);
i++;
units++;
// collapse multiple spaces?
if (t.equals(" ") && this.fix_spacing) {
while (tokens[i] != null && tokens[i].equals(" ")) i++;
}
continue ITER;
}
// vowels & consonants: process tibetan script up to a tsek, punctuation or line noise
if (vowel(t) != null || consonant(t) != null) {
WylieTsekbar tb = toUnicodeOneTsekbar(tokens, i);
StringBuilder word = new StringBuilder();
for (int j = 0; j < tb.tokens_used; j++) {
word.append(tokens[i+j]);
}
out.append(tb.uni_string);
i += tb.tokens_used;
units++;
for (String w : tb.warns) {
warnl(warns, line, "\"" + word.toString() + "\": " + w);
}
continue ITER;
}
// *** misc unicode and line handling stuff ***
// ignore BOM and zero-width space
if (t.equals("\ufeff") || t.equals("\u200b")) {
i++;
continue ITER;
}
// \\u, \\U unicode characters
if (t.startsWith("\\u") || t.startsWith("\\U")) {
o = unicodeEscape(warns, line, t);
if (o != null) {
i++;
out.append(o);
continue ITER;
}
}
// backslashed characters
if (t.startsWith("\\")) {
out.append(t.substring(1));
i++;
continue ITER;
}
// count lines
if (t.equals("\r\n") || t.equals("\n") || t.equals("\r")) {
line++;
out.append(t);
i++;
// also eat spaces after newlines (optional)
if (this.fix_spacing) {
while (tokens[i] != null && tokens[i].equals(" ")) i++;
}
continue ITER;
}
// stuff that shouldn't occur out of context: special chars and remaining [a-zA-Z]
char c = t.charAt(0);
if (isSpecial(t) || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
warnl(warns, line, "Unexpected character \"" + t + "\".");
}
// anything else: pass through
out.append(t);
i++;
}
if (units == 0) warn(warns, "No Tibetan characters found!");
return out.toString();
}
// does this string consist of only hexadecimal digits?
private boolean validHex(String t) {
for (int i = 0; i < t.length(); i++) {
char c = t.charAt(i);
if (!((c >= 'a' && c <= 'f') || (c >= '0' && c <= '9'))) return false;
}
return true;
}
// handle a Converter unicode escape, \\uxxxx or \\Uxxxxxxxx
private String unicodeEscape(List<String> warns, int line, String t) {
String hex = t.substring(2);
if (hex.isEmpty()) return null;
if (!validHex(hex)) {
warnl(warns, line, "\"" + t + "\": invalid hex code.");
return "";
}
return Character.valueOf((char)Integer.parseInt(hex, 16)).toString();
}
// generate a warning if we are keeping them; prints it out if we were asked to
private void warn (List<String> warns, String str) {
if (warns != null) warns.add(str);
if (this.print_warnings) System.out.println(str);
}
// warn with line number
private void warnl(List<String> warns, int line, String str) {
warn(warns, "line " + line + ": " + str);
}
// debug print
@SuppressWarnings("unused")
private void debug (String str) {
System.out.println(str);
}
// debug variable value
@SuppressWarnings("unused")
private void debugvar(Object o, String name) {
System.out.println(">>" + name + "<< : (" + (o == null ? "NULL" : o.toString()) + ")");
}
// join a list (ArrayList or LinkedList) of strings into a single string
private String joinStrings(List<String> a, String sep) {
StringBuilder out = new StringBuilder();
int len = a.size();
int i = 0;
for (String v : a) {
out.append(v);
if (sep != null && i < len - 1) out.append(sep);
i++;
}
return out.toString();
}
// Converts one stack's worth of Converter into unicode, starting at the given index
// within the array of tokens.
// Assumes that the first available token is valid, and is either a vowel or a consonant.
// Returns a WylieStack object.
@SuppressWarnings("unused")
private WylieStack toUnicodeOneStack(String[] tokens, int i) {
int orig_i = i;
String t, t2, o;
StringBuilder out = new StringBuilder();
ArrayList<String> warns = new ArrayList<String>();
int consonants = 0; // how many consonants found
String vowel_found = null; // any vowels (including a-chen)
String vowel_sign = null; // any vowel signs (that go under or above the main stack)
String single_consonant = null; // did we find just a single consonant?
boolean plus = false; // any explicit subjoining via '+'?
int caret = 0; // find any '^'?
HashMap<String, String> final_found = new HashMap<String, String>(); // keep track of finals (H, M, etc) by class
// do we have a superscript?
t = tokens[i];
t2 = tokens[i+1];
if (t2 != null && isSuperscript(t) && superscript(t, t2)) {
if (this.check_strict) {
String next = consonantString(tokens, i+1);
if (!superscript(t, next)) {
next = next.replace("+", "");
warns.add("Superscript \"" + t + "\" does not occur above combination \"" + next + "\".");
}
}
out.append(consonant(t));
consonants++;
i++;
while (tokens[i] != null && tokens[i].equals("^")) {
caret++;
i++;
}
}
// main consonant + stuff underneath.
// this is usually executed just once, but the "+" subjoining operator makes it come back here
MAIN:
while (true) {
// main consonant (or a "a" after a "+")
t = tokens[i];
if (consonant(t) != null || (out.length() > 0 && subjoined(t) != null)) {
if (out.length() > 0) {
out.append(subjoined(t));
} else {
out.append(consonant(t));
}
i++;
if (t.equals("a")) {
vowel_found = "a";
} else {
consonants++;
single_consonant = t;
}
while (tokens[i] != null && tokens[i].equals("^")) {
caret++;
i++;
}
// subjoined: rata, yata, lata, wazur. there can be up two subjoined letters in a stack.
for (int z = 0; z < 2; z++) {
t2 = tokens[i];
if (t2 != null && isSubscript(t2)) {
// lata does not occur below multiple consonants
// (otherwise we mess up "brla" = "b.r+la")
if (t2.equals("l") && consonants > 1) break;
// full stack checking (disabled by "+")
if (this.check_strict && !plus) {
String prev = consonantStringBackwards(tokens, i-1, orig_i);
if (!subscript(t2, prev)) {
prev = prev.replace("+", "");
warns.add("Subjoined \"" + t2 + "\" not expected after \"" + prev + "\".");
}
// simple check only
} else if (this.check) {
if (!subscript(t2, t) && !(z == 1 && t2.equals("w") && t.equals("y"))) {
warns.add("Subjoined \"" + t2 + "\"not expected after \"" + t + "\".");
}
}
out.append(subjoined(t2));
i++;
consonants++;
while (tokens[i] != null && tokens[i].equals("^")) {
caret++;
i++;
}
t = t2;
} else {
break;
}
}
}
// caret (^) can come anywhere in Converter but in Unicode we generate it at the end of
// the stack but before vowels if it came there (seems to be what OpenOffice expects),
// or at the very end of the stack if that's how it was in the Converter.
if (caret > 0) {
if (caret > 1) {
warns.add("Cannot have more than one \"^\" applied to the same stack.");
}
final_found.put(final_class("^"), "^");
out.append(final_uni("^"));
caret = 0;
}
// vowel(s)
t = tokens[i];
if (t != null && vowel(t) != null) {
if (out.length() == 0) out.append(vowel("a"));
if (!t.equals("a")) out.append(vowel(t));
i++;
vowel_found = t;
if (!t.equals("a")) vowel_sign = t;
}
// plus sign: forces more subjoining
t = tokens[i];
if (t != null && t.equals("+")) {
i++;
plus = true;
// sanity check: next token must be vowel or subjoinable consonant.
t = tokens[i];
if (t == null || (vowel(t) == null && subjoined(t) == null)) {
if (this.check) warns.add("Expected vowel or consonant after \"+\".");
break MAIN;
}
// consonants after vowels doesn't make much sense but process it anyway
if (this.check) {
if (vowel(t) == null && vowel_sign != null) {
warns.add("Cannot subjoin consonant (" + t + ") after vowel (" + vowel_sign + ") in same stack.");
} else if (t.equals("a") && vowel_sign != null) {
warns.add("Cannot subjoin a-chen (a) after vowel (" + vowel_sign + ") in same stack.");
}
}
continue MAIN;
}
break MAIN;
}
// final tokens
t = tokens[i];
while (t != null && final_class(t) != null) {
String uni = final_uni(t);
String klass = final_class(t);
// check for duplicates
if (final_found.containsKey(klass)) {
if (final_found.get(klass).equals(t)) {
warns.add("Cannot have two \"" + t + "\" applied to the same stack.");
} else {
warns.add("Cannot have \"" + t + "\" and \"" + final_found.get(klass) + "\" applied to the same stack.");
}
} else {
final_found.put(klass, t);
out.append(uni);
}
i++;
single_consonant = null;
t = tokens[i];
}
// if next is a dot "." (stack separator), skip it.
if (tokens[i] != null && tokens[i].equals(".")) i++;
// if we had more than a consonant and no vowel, and no explicit "+" joining, backtrack and
// return the 1st consonant alone
if (consonants > 1 && vowel_found == null) {
if (plus) {
if (this.check) warns.add("Stack with multiple consonants should end with vowel.");
} else {
i = orig_i + 1;
consonants = 1;
single_consonant = tokens[orig_i];
out.setLength(0);
out.append(consonant(single_consonant));
}
}
// calculate "single consonant"
if (consonants != 1 || plus) {
single_consonant = null;
}
// return the stuff as a WylieStack struct
WylieStack ret = new WylieStack();
ret.uni_string = out.toString();
ret.tokens_used = i - orig_i;
if (vowel_found != null) {
ret.single_consonant = null;
} else {
ret.single_consonant = single_consonant;
}
if (vowel_found != null && vowel_found.equals("a")) {
ret.single_cons_a = single_consonant;
} else {
ret.single_cons_a = null;
}
ret.warns = warns;
ret.visarga = final_found.containsKey("H");
return ret;
}
// Converts successive stacks of Converter into unicode, starting at the given index
// within the array of tokens.
//
// Assumes that the first available token is valid, and is either a vowel or a consonant.
// Returns a WylieTsekbar object
@SuppressWarnings("unused")
private WylieTsekbar toUnicodeOneTsekbar(String[] tokens, int i) {
int orig_i = i;
String t = tokens[i];
// variables for tracking the state within the syllable as we parse it
WylieStack stack = null;
String prev_cons = null;
boolean visarga = false;
// variables for checking the root letter, after parsing a whole tsekbar made of only single
// consonants and one consonant with "a" vowel
boolean check_root = true;
ArrayList<String> consonants = new ArrayList<String>();
int root_idx = -1;
StringBuilder out = new StringBuilder();
ArrayList<String> warns = new ArrayList<String>();
// the type of token that we are expecting next in the input stream
// - PREFIX : expect a prefix consonant, or a main stack
// - MAIN : expect only a main stack
// - SUFF1 : expect a 1st suffix
// - SUFF2 : expect a 2nd suffix
// - NONE : expect nothing (after a 2nd suffix)
//
// the state machine is actually more lenient than this, in that a "main stack" is allowed
// to come at any moment, even after suffixes. this is because such syllables are sometimes
// found in abbreviations or other places. basically what we check is that prefixes and
// suffixes go with what they are attached to.
//
// valid tsek-bars end in one of these states: SUFF1, SUFF2, NONE
State state = State.PREFIX;
// iterate over the stacks of a tsek-bar
STACK:
while (t != null && (vowel(t) != null || consonant(t) != null) && !visarga) {
// translate a stack
if (stack != null) prev_cons = stack.single_consonant;
stack = toUnicodeOneStack(tokens, i);
i += stack.tokens_used;
t = tokens[i];
out.append(stack.uni_string);
warns.addAll(stack.warns);
visarga = stack.visarga;
if (!this.check) continue;
// check for syllable structure consistency by iterating a simple state machine
// - prefix consonant
if (state == State.PREFIX && stack.single_consonant != null) {
consonants.add(stack.single_consonant);
if (isPrefix(stack.single_consonant)) {
String next = t;
if (this.check_strict) next = consonantString(tokens, i);
if (next != null && !prefix(stack.single_consonant, next)) {
next = next.replace("+", "");
warns.add("Prefix \"" + stack.single_consonant + "\" does not occur before \"" + next + "\".");
}
} else {
warns.add("Invalid prefix consonant: \"" + stack.single_consonant + "\".");
}
state = State.MAIN;
// - main stack with vowel or multiple consonants
} else if (stack.single_consonant == null) {
state = State.SUFF1;
// keep track of the root consonant if it was a single cons with an "a" vowel
if (root_idx >= 0) {
check_root = false;
} else if (stack.single_cons_a != null) {
consonants.add(stack.single_cons_a);
root_idx = consonants.size() - 1;
}
// - unexpected single consonant after prefix
} else if (state == State.MAIN) {
warns.add("Expected vowel after \"" + stack.single_consonant + "\".");
// - 1st suffix
} else if (state == State.SUFF1) {
consonants.add(stack.single_consonant);
// check this one only in strict mode b/c it trips on lots of Skt stuff
if (this.check_strict) {
if (!isSuffix(stack.single_consonant)) {
warns.add("Invalid suffix consonant: \"" + stack.single_consonant + "\".");
}
}
state = State.SUFF2;
// - 2nd suffix
} else if (state == State.SUFF2) {
consonants.add(stack.single_consonant);
if (isSuff2(stack.single_consonant)) {
if (!suff2(stack.single_consonant, prev_cons)) {
warns.add("Second suffix \"" + stack.single_consonant + "\" does not occur after \"" + prev_cons + "\".");
}
} else {
warns.add("Invalid 2nd suffix consonant: \"" + stack.single_consonant + "\".");
}
state = State.NONE;
// - more crap after a 2nd suffix
} else if (state == State.NONE) {
warns.add("Cannot have another consonant \"" + stack.single_consonant + "\" after 2nd suffix.");
}
}
if (state == State.MAIN && stack.single_consonant != null && isPrefix(stack.single_consonant)) {
warns.add("Vowel expected after \"" + stack.single_consonant + "\".");
}
// check root consonant placement only if there were no warnings so far, and the syllable
// looks ambiguous. not many checks are needed here because the previous state machine
// already takes care of most illegal combinations.
if (this.check && warns.size() == 0 && check_root && root_idx >= 0) {
// 2 letters where each could be prefix/suffix: root is 1st
if (consonants.size() == 2 && root_idx != 0 &&
prefix(consonants.get(0), consonants.get(1)) &&
isSuffix(consonants.get(1)))
{
warns.add("Syllable should probably be \"" + consonants.get(0) + "a" + consonants.get(1) + "\".");
// 3 letters where 1st can be prefix, 2nd can be postfix before "s" and last is "s":
// use a lookup table as this is completely ambiguous.
} else if (consonants.size() == 3 && isPrefix(consonants.get(0)) &&
suff2("s", consonants.get(1)) && consonants.get(2).equals("s"))
{
String cc = joinStrings(consonants, "");
cc = cc.replace('\u2018', '\'');
cc = cc.replace('\u2019', '\''); // typographical quotes
Integer expect_key = ambiguous_key(cc);
if (expect_key != null && expect_key.intValue() != root_idx) {
warns.add("Syllable should probably be \"" + ambiguous_wylie(cc) + "\".");
}
}
}
// return the stuff as a WylieTsekbar struct
WylieTsekbar ret = new WylieTsekbar();
ret.uni_string = out.toString();
ret.tokens_used = i - orig_i;
ret.warns = warns;
return ret;
}
// Looking from i onwards within tokens, returns as many consonants as it finds,
// up to and not including the next vowel or punctuation. Skips the caret "^".
// Returns: a string of consonants joined by "+" signs.
private String consonantString(String[] tokens, int i) {
ArrayList<String> out = new ArrayList<String>();
String t;
while (tokens[i] != null) {
t = tokens[i++];
if (t.equals("+") || t.equals("^")) continue;
if (consonant(t) == null) break;
out.add(t);
}
return joinStrings(out, "+");
}
// Looking from i backwards within tokens, at most up to orig_i, returns as
// many consonants as it finds, up to and not including the next vowel or
// punctuation. Skips the caret "^".
// Returns: a string of consonants (in forward order) joined by "+" signs.
private String consonantStringBackwards(String[] tokens, int i, int orig_i) {
LinkedList<String> out = new LinkedList<String>();
String t;
while (i >= orig_i && tokens[i] != null) {
t = tokens[i--];
if (t.equals("+") || t.equals("^")) continue;
if (consonant(t) == null) break;
out.addFirst(t);
}
return joinStrings(out, "+");
}
// Converts from Unicode strings to Converter (EWTS) transliteration, without warnings,
// including escaping of non-tibetan into [comments].
public String toWylie(String str) {
return toWylie(str, null, true);
}
// Converts from Unicode strings to Converter (EWTS) transliteration.
//
// Arguments are:
// str : the unicode string to be converted
// escape: whether to escape non-tibetan characters according to Converter encoding.
// if escape == false, anything that is not tibetan will be just passed through.
//
// Returns: the transliterated string.
//
// To get the warnings, call getWarnings() afterwards.
public String toWylie(String str, List<String> warns, boolean escape) {
StringBuilder out = new StringBuilder();
int line = 1;
int units = 0;
// globally search and replace some deprecated pre-composed Sanskrit vowels
str = str.replace("\u0f76", "\u0fb2\u0f80");
str = str.replace("\u0f77", "\u0fb2\u0f71\u0f80");
str = str.replace("\u0f78", "\u0fb3\u0f80");
str = str.replace("\u0f79", "\u0fb3\u0f71\u0f80");
str = str.replace("\u0f81", "\u0f71\u0f80");
int i = 0;
int len = str.length();
// iterate over the string, codepoint by codepoint
ITER:
while (i < len) {
char t = str.charAt(i);
// found tibetan script - handle one tsekbar
if (tib_top(t) != null) {
ToWylieTsekbar tb = toWylieOneTsekbar(str, len, i);
out.append(tb.wylie);
i += tb.tokens_used;
units++;
for (String w : tb.warns) {
warnl(warns, line, w);
}
if (!escape) i += handleSpaces(str, i, out);
continue ITER;
}
// punctuation and special stuff. spaces are tricky:
// - in non-escaping mode: spaces are not turned to '_' here (handled by handleSpaces)
// - in escaping mode: don't do spaces if there is non-tibetan coming, so they become part
// of the [ escaped block].
String o = tib_other(t);
if (o != null && (t != ' ' || (escape && !followedByNonTibetan(str, i)))) {
out.append(o);
i++;
units++;
if (!escape) i += handleSpaces(str, i, out);
continue ITER;
}
// newlines, count lines. "\r\n" together count as one newline.
if (t == '\r' || t == '\n') {
line++;
i++;
out.append(t);
if (t == '\r' && i < len && str.charAt(i) == '\n') {
i++;
out.append('\n');
}
continue ITER;
}
// ignore BOM and zero-width space
if (t == '\ufeff' || t == '\u200b') {
i++;
continue ITER;
}
// anything else - pass along?
if (!escape) {
out.append(t);
i++;
continue ITER;
}
// other characters in the tibetan plane, escape with \\u0fxx
if (t >= '\u0f00' && t <= '\u0fff') {
String c = formatHex(t);
out.append(c);
i++;
// warn for tibetan codepoints that should appear only after a tib_top
if (tib_subjoined(t) != null || tib_vowel(t) != null || tib_final_wylie(t) != null) {
warnl(warns, line, "Tibetan sign " + c + " needs a top symbol to attach to.");
}
continue ITER;
}
// ... or escape according to Converter:
// put it in [comments], escaping [] sequences and closing at line ends
out.append("[");
while (tib_top(t) == null && (tib_other(t) == null || t == ' ') && t != '\r' && t != '\n') {
// \escape [opening and closing] brackets
if (t == '[' || t == ']') {
out.append("\\");
out.append(t);
// unicode-escape anything in the tibetan plane (i.e characters not handled by Converter)
} else if (t >= '\u0f00' && t <= '\u0fff') {
out.append(formatHex(t));
// and just pass through anything else!
} else {
out.append(t);
}
if (++i >= len) break;
t = str.charAt(i);
}
out.append("]");
}
return out.toString();
}
// given a character, return a string like "\\uxxxx", with its code in hex
private final String formatHex(char t) {
// not compatible with GWT...
// return String.format("\\u%04x", (int)t);
StringBuilder sb = new StringBuilder();
sb.append("\\u");
String s = Integer.toHexString((int)t);
for (int i = s.length(); i < 4; i++) {
sb.append('0');
}
sb.append(s);
return sb.toString();
}
// handles spaces (if any) in the input stream, turning them into '_'.
// this is abstracted out because in non-escaping mode, we only want to turn spaces into _
// when they come in the middle of Tibetan script.
private int handleSpaces(String str, int i, StringBuilder out) {
int found = 0;
@SuppressWarnings("unused")
int orig_i = i;
while (i < str.length() && str.charAt(i) == ' ') {
i++;
found++;
}
if (found == 0 || i == str.length()) return 0;
char t = str.charAt(i);
if (tib_top(t) == null && tib_other(t) == null) return 0;
// found 'found' spaces between two tibetan bits; generate the same number of '_'s
for (i = 0; i < found; i++) {
out.append('_');
}
return found;
}
// for space-handling in escaping mode: is the next thing coming (after a number of spaces)
// some non-tibetan bit, within the same line?
private boolean followedByNonTibetan(String str, int i) {
int len = str.length();
while (i < len && str.charAt(i) == ' ') {
i++;
}
if (i == len) return false;
char t = str.charAt(i);
return tib_top(t) == null && tib_other(t) == null && t != '\r' && t != '\n';
}
// Convert Unicode to Converter: one tsekbar
private ToWylieTsekbar toWylieOneTsekbar(String str, int len, int i) {
int orig_i = i;
ArrayList<String> warns = new ArrayList<String>();
ArrayList<ToWylieStack> stacks = new ArrayList<ToWylieStack>();
ITER:
while (true) {
ToWylieStack st = toWylieOneStack(str, len, i);
stacks.add(st);
warns.addAll(st.warns);
i += st.tokens_used;
if (st.visarga) break ITER;
if (i >= len || tib_top(str.charAt(i)) == null) break ITER;
}
// figure out if some of these stacks can be prefixes or suffixes (in which case
// they don't need their "a" vowels)
int last = stacks.size() - 1;
if (stacks.size() > 1 && stacks.get(0).single_cons != null) {
// we don't count the wazur in the root stack, for prefix checking
String cs = stacks.get(1).cons_str.replace("+w", "");
if (prefix(stacks.get(0).single_cons, cs)) {
stacks.get(0).prefix = true;
}
}
if (stacks.size() > 1 && stacks.get(last).single_cons != null && isSuffix(stacks.get(last).single_cons)) {
stacks.get(last).suffix = true;
}
if (stacks.size() > 2 && stacks.get(last).single_cons != null && stacks.get(last - 1).single_cons != null &&
isSuffix(stacks.get(last - 1).single_cons) &&
suff2(stacks.get(last).single_cons, stacks.get(last - 1).single_cons)) {
stacks.get(last).suff2 = true;
stacks.get(last - 1).suffix = true;
}
// if there are two stacks and both can be prefix-suffix, then 1st is root
if (stacks.size() == 2 && stacks.get(0).prefix && stacks.get(1).suffix) {
stacks.get(0).prefix = false;
}
// if there are three stacks and they can be prefix, suffix and suff2, then check w/ a table
if (stacks.size() == 3 && stacks.get(0).prefix && stacks.get(1).suffix && stacks.get(2).suff2) {
StringBuilder strb = new StringBuilder();
for (ToWylieStack st : stacks) {
strb.append(st.single_cons);
}
String ztr = strb.toString();
Integer root = ambiguous_key(ztr);
if (root == null) {
warns.add("Ambiguous syllable found: root consonant not known for \"" + ztr + "\".");
// make it up... (ex. "mgas" for ma, ga, sa)
root = 1;
}
stacks.get(root).prefix = stacks.get(root).suffix = false;
stacks.get(root + 1).suff2 = false;
}
// if the prefix together with the main stack could be mistaken for a single stack, add a "."
if (stacks.get(0).prefix && tib_stack(stacks.get(0).single_cons + "+" + stacks.get(1).cons_str)) {
stacks.get(0).dot = true;
}
// put it all together
StringBuilder out = new StringBuilder();
for (ToWylieStack st : stacks) {
out.append(putStackTogether(st));
}
ToWylieTsekbar ret = new ToWylieTsekbar();
ret.wylie = out.toString();
ret.tokens_used = i - orig_i;
ret.warns = warns;
return ret;
}
// Unicode to Converter: one stack at a time
private ToWylieStack toWylieOneStack(String str, int len, int i) {
int orig_i = i;
String ffinal = null, vowel = null, klass = null;
// split the stack into a ToWylieStack object:
// - top symbol
// - stacked signs (first is the top symbol again, then subscribed main characters...)
// - caret (did we find a stray tsa-phru or not?)
// - vowel signs (including small subscribed a-chung, "-i" Skt signs, etc)
// - final stuff (including anusvara, visarga, halanta...)
// - and some more variables to keep track of what has been found
ToWylieStack st = new ToWylieStack();
// assume: tib_top(t) exists
char t = str.charAt(i++);
st.top = tib_top(t);
st.stack.add(tib_top(t));
// grab everything else below the top sign and classify in various categories
while (i < len) {
t = str.charAt(i);
String o;
if ((o = tib_subjoined(t)) != null) {
i++;
st.stack.add(o);
// check for bad ordering
if (!st.finals.isEmpty()) {
st.warns.add("Subjoined sign \"" + o + "\" found after final sign \"" + ffinal + "\".");
} else if (!st.vowels.isEmpty()) {
st.warns.add("Subjoined sign \"" + o + "\" found after vowel sign \"" + vowel + "\".");
}
} else if ((o = tib_vowel(t)) != null) {
i++;
st.vowels.add(o);
if (vowel == null) vowel = o;
// check for bad ordering
if (!st.finals.isEmpty()) {
st.warns.add("Vowel sign \"" + o + "\" found after final sign \"" + ffinal + "\".");
}
} else if ((o = tib_final_wylie(t)) != null) {
i++;
klass = tib_final_class(t);
if (o.equals("^")) {
st.caret = true;
} else {
if (o.equals("H")) st.visarga = true;
st.finals.add(o);
if (ffinal == null) ffinal = o;
// check for invalid combinations
if (st.finals_found.containsKey(klass)) {
st.warns.add("Final sign \"" + o + "\" should not combine with found after final sign \"" + ffinal + "\".");
} else {
st.finals_found.put(klass, o);
}
}
} else {
break;
}
}
// now analyze the stack according to various rules
// a-chen with vowel signs: remove the "a" and keep the vowel signs
if (st.top.equals("a") && st.stack.size() == 1 && !st.vowels.isEmpty()) {
st.stack.removeFirst();
}
// handle long vowels: A+i becomes I, etc.
if (st.vowels.size() > 1 &&
st.vowels.get(0).equals("A") &&
tib_vowel_long(st.vowels.get(1)) != null) {
String l = tib_vowel_long(st.vowels.get(1));
st.vowels.removeFirst();
st.vowels.removeFirst();
st.vowels.addFirst(l);
}
// special cases: "ph^" becomes "f", "b^" becomes "v"
if (st.caret && st.stack.size() == 1 && tib_caret(st.top) != null) {
String l = tib_caret(st.top);
st.top = l;
st.stack.removeFirst();
st.stack.addFirst(l);
st.caret = false;
}
st.cons_str = joinStrings(st.stack, "+");
// if this is a single consonant, keep track of it (useful for prefix/suffix analysis)
if (st.stack.size() == 1 &&
!st.stack.get(0).equals("a") &&
!st.caret &&
st.vowels.isEmpty() &&
st.finals.isEmpty()) {
st.single_cons = st.cons_str;
}
// return the analyzed stack
st.tokens_used = i - orig_i;
return st;
}
// Puts an analyzed stack together into Converter output, adding an implicit "a" if needed.
private String putStackTogether(ToWylieStack st) {
StringBuilder out = new StringBuilder();
// put the main elements together... stacked with "+" unless it's a regular stack
if (tib_stack(st.cons_str)) {
out.append(joinStrings(st.stack, ""));
} else {
out.append(st.cons_str);
}
// caret (tsa-phru) goes here as per some (halfway broken) Unicode specs...
if (st.caret) {
out.append("^");
}
// vowels...
if (!st.vowels.isEmpty()) {
out.append(joinStrings(st.vowels, "+"));
} else if (!st.prefix && !st.suffix && !st.suff2 &&
(st.cons_str.isEmpty() || st.cons_str.charAt(st.cons_str.length() - 1) != 'a')) {
out.append("a");
}
// final stuff
out.append(joinStrings(st.finals, ""));
if (st.dot) out.append(".");
return out.toString();
}
// HELPER CLASSES AND STRUCTURES
// An Enum for the list of states used to check the consistency of a Tibetan tsekbar.
private static enum State {
PREFIX, MAIN, SUFF1, SUFF2, NONE
}
// A simple class to encapsulate the return value of toUnicodeOneStack.
// Quick and dirty and not particularly OO.
private static class WylieStack {
// the converted unicode string
public String uni_string;
// how many tokens from the stream were used
public int tokens_used;
// did we find a single consonant without vowel? if so which one
public String single_consonant;
// did we find a single consonant with an "a"? if so which one
public String single_cons_a;
// list of warnings
public ArrayList<String> warns;
// found a visarga?
public boolean visarga;
}
// A simple class to encapsulate the return value of toUnicodeOneTsekbar.
// Quick and dirty and not particularly OO.
private static class WylieTsekbar {
// the converted unicode string
public String uni_string;
// how many tokens from the stream were used
public int tokens_used;
// list of warnings
public ArrayList<String> warns;
}
// A simple class to encapsulate an analyzed tibetan stack, while
// converting Unicode to Converter.
private static class ToWylieStack {
// top symbol
public String top;
// the entire stack of consonants, as a List of Strings
public LinkedList<String> stack;
// found a caret (^) or not
public boolean caret;
// vowels found, as a List of Strings
public LinkedList<String> vowels;
// finals found, as a List of Strings
public ArrayList<String> finals;
// finals found, as a HashMap of Strings to Strings (klass => wylie)
public HashMap<String, String> finals_found;
// did we see a visarga?
public boolean visarga;
// all consonants separated by '+'
public String cons_str;
// is this a single consonant with no vowel signs or finals?
public String single_cons;
// boolean, later set to true if this is a prefix, suffix, 2nd suffix, or if we need a dot as in "g.yag"
public boolean prefix, suffix, suff2, dot;
// how many tokens from the stream were used
public int tokens_used;
// list of warnings
public ArrayList<String> warns;
// constructor - initialize a few arrays
public ToWylieStack() {
this.stack = new LinkedList<String>();
this.vowels = new LinkedList<String>();
this.finals = new ArrayList<String>();
this.finals_found = new HashMap<String, String>();
this.warns = new ArrayList<String>();
}
}
// A simple class to encapsulate the return value of toWylieOneTsekbar.
// Quick and dirty and not particularly OO.
private static class ToWylieTsekbar {
// the converted wylie string
public String wylie;
// how many tokens from the stream were used
public int tokens_used;
// list of warnings
public ArrayList<String> warns;
}
}
|
src/main/java/io/bdrc/xmltoldmigration/Converter.java
|
package io.bdrc.xmltoldmigration;
/*******************************************************************************
* Copyright (c) 2014 Tibetan Buddhist Resource Center (TBRC)
*
* If this file is a derivation of another work the license header will appear below;
* otherwise, this work is licensed under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
/* This Java package implements the conversion between Unicode Tibetan text, and
Converter (EWTS) transliteration.
It is based on the equivalent Perl module, Lingua::BO::Converter, found at
http://www.digitaltibetan.org/cgi-bin/wylie.pl
The Extended Converter Transliteration System is documented at:
http://www.thlib.org/reference/transliteration/#essay=/thl/ewts/
OVERVIEW
========
This code is a library; it is meant to be embedded in other software.
import org.rigpa.wylie.Wylie;
...
Converter wl = new Converter();
System.out.println(wl.toUnicode("sems can thams cad"));
System.out.println(wl.toWylie("\u0f66\u0f44\u0f66\u0f0b\u0f62\u0f92\u0fb1\u0f66\u000a"));
From the command-line, you can use the provided "Test" and "TestToWylie"
programs, which requests lines in Converter from the user and prints the unicode to
stdout, and vice versa. Run them with:
java Test
java TestToWylie
To run the test suite, run this command:
javac -g RunTests.java && java RunTests < test.txt
CONSTRUCTOR
===========
Two constructors are available:
Converter wl = new Converter(); // uses all the default options
and
Converter wl = new Converter(check, check_strict, print_warnings, fix_spacing);
The meanings of the parameters are:
- check (boolean) : generate warnings for illegal consonant sequences; default is true.
- check_strict (boolean) : stricter checking, examine the whole stack; default is true.
- print_warnings (boolean) : print generated warnings to STDOUT; default is false.
- fix_spacing (boolean) : remove spaces after newlines, collapse multiple tseks into one, etc;
default is true.
PUBLIC METHODS
==============
String toUnicode(String wylie_string);
Converts from Converter (EWTS) to Unicode.
String toUnicode(String wylie_string, ArrayList<String> warns);
Converts from Converter (EWTS) to Unicode; puts the generated warnings in the list.
String toWylie(String unicode_string);
Converts from Unicode to Converter.
Anything that is not Tibetan Unicode is converted to EWTS comment blocks [between brackets].
String toWylie(String unicode_string, ArrayList<String> warns, boolean escape);
Converts from Unicode to Converter. Puts the generated warnings in the list.
If escape is false, anything that is not Tibetan Unicode is just passed through as it is.
PERFORMANCE AND CONCURRENCY
===========================
This code should perform quite decently. When converting from Converter to
Unicode, the entire string is split into tokens, which are themselves
strings. If this takes too much memory, consider converting your text in
smaller chunks. With today's computers, it should not be a problem to
convert several megabytes of tibetan text in one call. Otherwise, it could
be worthwhile to tokenize the input on the fly, rather than all at once.
This class is entirely thread-safe. In a multi-threaded environment,
multiple threads can share the same instance without any problems.
AUTHOR AND LICENSE
==================
Copyright (C) 2010 Roger Espel Llima
This library is Free Software. You can redistribute it or modify it, under
the terms of, at your choice, the GNU General Public License (version 2 or
higher), the GNU Lesser General Public License (version 2 or higher), the
Mozilla Public License (any version) or the Apache License version 2 or
higher.
Please contact the author if you wish to use it under some terms not covered
here.
Copyright 2011 TBRC
This library is Free Software. You can redistribute it or modify it, under
the terms of, at your choice, the GNU General Public License (version 2 or
higher), the GNU Lesser General Public License (version 2 or higher), the
Mozilla Public License (any version) or the Apache License version 2 or
higher.
Please contact support@tbrc.org if you wish to use it under some terms not covered
here.
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Converter {
// various options for Converter conversion
private boolean check, check_strict, print_warnings, fix_spacing;
// constant hashes and sets to help with the conversion
private static HashMap<String, String> m_consonant, m_subjoined, m_vowel, m_final_uni, m_final_class,
m_other, m_ambiguous_wylie, m_tib_vowel_long, m_tib_caret;
private static HashMap<Character, String> m_tib_top, m_tib_subjoined, m_tib_vowel, m_tib_final_wylie, m_tib_final_class,
m_tib_other;
private static HashMap<String, Integer> m_ambiguous_key;
private static HashMap<Character, Integer> m_tokens_start;
private static HashSet<String> m_special, m_suffixes, m_tib_stacks, m_tokens;
private static HashMap<String, HashSet<String>> m_superscripts, m_subscripts, m_prefixes, m_suff2;
// initialize all the hashes with the correspondences between Converter and Unicode.
// this gets called from a 'static section' to initialize the hashes the moment the
// class gets loaded.
private static final void initHashes() {
HashSet<String> tmpSet;
// mappings auto-generated from the Perl code
// *** Converter to Unicode mappings ***
// list of wylie consonant => unicode
m_consonant = new HashMap<String, String>();
m_consonant.put("k", "\u0f40");
m_consonant.put("kh", "\u0f41");
m_consonant.put("g", "\u0f42");
m_consonant.put("gh", "\u0f42\u0fb7");
m_consonant.put("g+h", "\u0f42\u0fb7");
m_consonant.put("ng", "\u0f44");
m_consonant.put("c", "\u0f45");
m_consonant.put("ch", "\u0f46");
m_consonant.put("j", "\u0f47");
m_consonant.put("ny", "\u0f49");
m_consonant.put("T", "\u0f4a");
m_consonant.put("-t", "\u0f4a");
m_consonant.put("Th", "\u0f4b");
m_consonant.put("-th", "\u0f4b");
m_consonant.put("D", "\u0f4c");
m_consonant.put("-d", "\u0f4c");
m_consonant.put("Dh", "\u0f4c\u0fb7");
m_consonant.put("D+h", "\u0f4c\u0fb7");
m_consonant.put("-dh", "\u0f4c\u0fb7");
m_consonant.put("-d+h", "\u0f4c\u0fb7");
m_consonant.put("N", "\u0f4e");
m_consonant.put("-n", "\u0f4e");
m_consonant.put("t", "\u0f4f");
m_consonant.put("th", "\u0f50");
m_consonant.put("d", "\u0f51");
m_consonant.put("dh", "\u0f51\u0fb7");
m_consonant.put("d+h", "\u0f51\u0fb7");
m_consonant.put("n", "\u0f53");
m_consonant.put("p", "\u0f54");
m_consonant.put("ph", "\u0f55");
m_consonant.put("b", "\u0f56");
m_consonant.put("bh", "\u0f56\u0fb7");
m_consonant.put("b+h", "\u0f56\u0fb7");
m_consonant.put("m", "\u0f58");
m_consonant.put("ts", "\u0f59");
m_consonant.put("tsh", "\u0f5a");
m_consonant.put("dz", "\u0f5b");
m_consonant.put("dzh", "\u0f5b\u0fb7");
m_consonant.put("dz+h", "\u0f5b\u0fb7");
m_consonant.put("w", "\u0f5d");
m_consonant.put("zh", "\u0f5e");
m_consonant.put("z", "\u0f5f");
m_consonant.put("'", "\u0f60");
m_consonant.put("\u2018", "\u0f60"); // typographic quotes
m_consonant.put("\u2019", "\u0f60");
m_consonant.put("y", "\u0f61");
m_consonant.put("r", "\u0f62");
m_consonant.put("l", "\u0f63");
m_consonant.put("sh", "\u0f64");
m_consonant.put("Sh", "\u0f65");
m_consonant.put("-sh", "\u0f65");
m_consonant.put("s", "\u0f66");
m_consonant.put("h", "\u0f67");
m_consonant.put("W", "\u0f5d");
m_consonant.put("Y", "\u0f61");
m_consonant.put("R", "\u0f6a");
m_consonant.put("f", "\u0f55\u0f39");
m_consonant.put("v", "\u0f56\u0f39");
// subjoined letters
m_subjoined = new HashMap<String, String>();
m_subjoined.put("k", "\u0f90");
m_subjoined.put("kh", "\u0f91");
m_subjoined.put("g", "\u0f92");
m_subjoined.put("gh", "\u0f92\u0fb7");
m_subjoined.put("g+h", "\u0f92\u0fb7");
m_subjoined.put("ng", "\u0f94");
m_subjoined.put("c", "\u0f95");
m_subjoined.put("ch", "\u0f96");
m_subjoined.put("j", "\u0f97");
m_subjoined.put("ny", "\u0f99");
m_subjoined.put("T", "\u0f9a");
m_subjoined.put("-t", "\u0f9a");
m_subjoined.put("Th", "\u0f9b");
m_subjoined.put("-th", "\u0f9b");
m_subjoined.put("D", "\u0f9c");
m_subjoined.put("-d", "\u0f9c");
m_subjoined.put("Dh", "\u0f9c\u0fb7");
m_subjoined.put("D+h", "\u0f9c\u0fb7");
m_subjoined.put("-dh", "\u0f9c\u0fb7");
m_subjoined.put("-d+h", "\u0f9c\u0fb7");
m_subjoined.put("N", "\u0f9e");
m_subjoined.put("-n", "\u0f9e");
m_subjoined.put("t", "\u0f9f");
m_subjoined.put("th", "\u0fa0");
m_subjoined.put("d", "\u0fa1");
m_subjoined.put("dh", "\u0fa1\u0fb7");
m_subjoined.put("d+h", "\u0fa1\u0fb7");
m_subjoined.put("n", "\u0fa3");
m_subjoined.put("p", "\u0fa4");
m_subjoined.put("ph", "\u0fa5");
m_subjoined.put("b", "\u0fa6");
m_subjoined.put("bh", "\u0fa6\u0fb7");
m_subjoined.put("b+h", "\u0fa6\u0fb7");
m_subjoined.put("m", "\u0fa8");
m_subjoined.put("ts", "\u0fa9");
m_subjoined.put("tsh", "\u0faa");
m_subjoined.put("dz", "\u0fab");
m_subjoined.put("dzh", "\u0fab\u0fb7");
m_subjoined.put("dz+h", "\u0fab\u0fb7");
m_subjoined.put("w", "\u0fad");
m_subjoined.put("zh", "\u0fae");
m_subjoined.put("z", "\u0faf");
m_subjoined.put("'", "\u0fb0");
m_subjoined.put("\u2018", "\u0fb0"); // typographic quotes
m_subjoined.put("\u2019", "\u0fb0");
m_subjoined.put("y", "\u0fb1");
m_subjoined.put("r", "\u0fb2");
m_subjoined.put("l", "\u0fb3");
m_subjoined.put("sh", "\u0fb4");
m_subjoined.put("Sh", "\u0fb5");
m_subjoined.put("-sh", "\u0fb5");
m_subjoined.put("s", "\u0fb6");
m_subjoined.put("h", "\u0fb7");
m_subjoined.put("a", "\u0fb8");
m_subjoined.put("W", "\u0fba");
m_subjoined.put("Y", "\u0fbb");
m_subjoined.put("R", "\u0fbc");
// vowels
m_vowel = new HashMap<String, String>();
m_vowel.put("a", "\u0f68");
m_vowel.put("A", "\u0f71");
m_vowel.put("i", "\u0f72");
m_vowel.put("I", "\u0f71\u0f72");
m_vowel.put("u", "\u0f74");
m_vowel.put("U", "\u0f71\u0f74");
m_vowel.put("e", "\u0f7a");
m_vowel.put("ai", "\u0f7b");
m_vowel.put("o", "\u0f7c");
m_vowel.put("au", "\u0f7d");
m_vowel.put("-i", "\u0f80");
m_vowel.put("-I", "\u0f71\u0f80");
// final symbols to unicode
m_final_uni = new HashMap<String, String>();
m_final_uni.put("M", "\u0f7e");
m_final_uni.put("~M`", "\u0f82");
m_final_uni.put("~M", "\u0f83");
m_final_uni.put("X", "\u0f37");
m_final_uni.put("~X", "\u0f35");
m_final_uni.put("H", "\u0f7f");
m_final_uni.put("?", "\u0f84");
m_final_uni.put("^", "\u0f39");
// final symbols organized by class
m_final_class = new HashMap<String, String>();
m_final_class.put("M", "M");
m_final_class.put("~M`", "M");
m_final_class.put("~M", "M");
m_final_class.put("X", "X");
m_final_class.put("~X", "X");
m_final_class.put("H", "H");
m_final_class.put("?", "?");
m_final_class.put("^", "^");
// other stand-alone symbols
m_other = new HashMap<String, String>();
m_other.put("0", "\u0f20");
m_other.put("1", "\u0f21");
m_other.put("2", "\u0f22");
m_other.put("3", "\u0f23");
m_other.put("4", "\u0f24");
m_other.put("5", "\u0f25");
m_other.put("6", "\u0f26");
m_other.put("7", "\u0f27");
m_other.put("8", "\u0f28");
m_other.put("9", "\u0f29");
m_other.put(" ", "\u0f0b");
m_other.put("*", "\u0f0c");
m_other.put("/", "\u0f0d");
m_other.put("//", "\u0f0e");
m_other.put(";", "\u0f0f");
m_other.put("|", "\u0f11");
m_other.put("!", "\u0f08");
m_other.put(":", "\u0f14");
m_other.put("_", " ");
m_other.put("=", "\u0f34");
m_other.put("<", "\u0f3a");
m_other.put(">", "\u0f3b");
m_other.put("(", "\u0f3c");
m_other.put(")", "\u0f3d");
m_other.put("@", "\u0f04");
m_other.put("#", "\u0f05");
m_other.put("$", "\u0f06");
m_other.put("%", "\u0f07");
// special characters: flag those if they occur out of context
m_special = new HashSet<String>();
m_special.add(".");
m_special.add("+");
m_special.add("-");
m_special.add("~");
m_special.add("^");
m_special.add("?");
m_special.add("`");
m_special.add("]");
// superscripts: hashmap of superscript => set of letters or stacks below
m_superscripts = new HashMap<String, HashSet<String>>();
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("g");
tmpSet.add("ng");
tmpSet.add("j");
tmpSet.add("ny");
tmpSet.add("t");
tmpSet.add("d");
tmpSet.add("n");
tmpSet.add("b");
tmpSet.add("m");
tmpSet.add("ts");
tmpSet.add("dz");
tmpSet.add("k+y");
tmpSet.add("g+y");
tmpSet.add("m+y");
tmpSet.add("b+w");
tmpSet.add("ts+w");
tmpSet.add("g+w");
m_superscripts.put("r", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("g");
tmpSet.add("ng");
tmpSet.add("c");
tmpSet.add("j");
tmpSet.add("t");
tmpSet.add("d");
tmpSet.add("p");
tmpSet.add("b");
tmpSet.add("h");
m_superscripts.put("l", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("g");
tmpSet.add("ng");
tmpSet.add("ny");
tmpSet.add("t");
tmpSet.add("d");
tmpSet.add("n");
tmpSet.add("p");
tmpSet.add("b");
tmpSet.add("m");
tmpSet.add("ts");
tmpSet.add("k+y");
tmpSet.add("g+y");
tmpSet.add("p+y");
tmpSet.add("b+y");
tmpSet.add("m+y");
tmpSet.add("k+r");
tmpSet.add("g+r");
tmpSet.add("p+r");
tmpSet.add("b+r");
tmpSet.add("m+r");
tmpSet.add("n+r");
m_superscripts.put("s", tmpSet);
// subscripts => set of letters above
m_subscripts = new HashMap<String, HashSet<String>>();
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("kh");
tmpSet.add("g");
tmpSet.add("p");
tmpSet.add("ph");
tmpSet.add("b");
tmpSet.add("m");
tmpSet.add("r+k");
tmpSet.add("r+g");
tmpSet.add("r+m");
tmpSet.add("s+k");
tmpSet.add("s+g");
tmpSet.add("s+p");
tmpSet.add("s+b");
tmpSet.add("s+m");
m_subscripts.put("y", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("kh");
tmpSet.add("g");
tmpSet.add("t");
tmpSet.add("th");
tmpSet.add("d");
tmpSet.add("n");
tmpSet.add("p");
tmpSet.add("ph");
tmpSet.add("b");
tmpSet.add("m");
tmpSet.add("sh");
tmpSet.add("s");
tmpSet.add("h");
tmpSet.add("dz");
tmpSet.add("s+k");
tmpSet.add("s+g");
tmpSet.add("s+p");
tmpSet.add("s+b");
tmpSet.add("s+m");
tmpSet.add("s+n");
m_subscripts.put("r", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("g");
tmpSet.add("b");
tmpSet.add("r");
tmpSet.add("s");
tmpSet.add("z");
m_subscripts.put("l", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("kh");
tmpSet.add("g");
tmpSet.add("c");
tmpSet.add("ny");
tmpSet.add("t");
tmpSet.add("d");
tmpSet.add("ts");
tmpSet.add("tsh");
tmpSet.add("zh");
tmpSet.add("z");
tmpSet.add("r");
tmpSet.add("l");
tmpSet.add("sh");
tmpSet.add("s");
tmpSet.add("h");
tmpSet.add("g+r");
tmpSet.add("d+r");
tmpSet.add("ph+y");
tmpSet.add("r+g");
tmpSet.add("r+ts");
m_subscripts.put("w", tmpSet);
// prefixes => set of consonants or stacks after
m_prefixes = new HashMap<String, HashSet<String>>();
tmpSet = new HashSet<String>();
tmpSet.add("c");
tmpSet.add("ny");
tmpSet.add("t");
tmpSet.add("d");
tmpSet.add("n");
tmpSet.add("ts");
tmpSet.add("zh");
tmpSet.add("z");
tmpSet.add("y");
tmpSet.add("sh");
tmpSet.add("s");
m_prefixes.put("g", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("g");
tmpSet.add("ng");
tmpSet.add("p");
tmpSet.add("b");
tmpSet.add("m");
tmpSet.add("k+y");
tmpSet.add("g+y");
tmpSet.add("p+y");
tmpSet.add("b+y");
tmpSet.add("m+y");
tmpSet.add("k+r");
tmpSet.add("g+r");
tmpSet.add("p+r");
tmpSet.add("b+r");
m_prefixes.put("d", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("k");
tmpSet.add("g");
tmpSet.add("c");
tmpSet.add("t");
tmpSet.add("d");
tmpSet.add("ts");
tmpSet.add("zh");
tmpSet.add("z");
tmpSet.add("sh");
tmpSet.add("s");
tmpSet.add("r");
tmpSet.add("l");
tmpSet.add("k+y");
tmpSet.add("g+y");
tmpSet.add("k+r");
tmpSet.add("g+r");
tmpSet.add("r+l");
tmpSet.add("s+l");
tmpSet.add("r+k");
tmpSet.add("r+g");
tmpSet.add("r+ng");
tmpSet.add("r+j");
tmpSet.add("r+ny");
tmpSet.add("r+t");
tmpSet.add("r+d");
tmpSet.add("r+n");
tmpSet.add("r+ts");
tmpSet.add("r+dz");
tmpSet.add("s+k");
tmpSet.add("s+g");
tmpSet.add("s+ng");
tmpSet.add("s+ny");
tmpSet.add("s+t");
tmpSet.add("s+d");
tmpSet.add("s+n");
tmpSet.add("s+ts");
tmpSet.add("r+k+y");
tmpSet.add("r+g+y");
tmpSet.add("s+k+y");
tmpSet.add("s+g+y");
tmpSet.add("s+k+r");
tmpSet.add("s+g+r");
tmpSet.add("l+d");
tmpSet.add("l+t");
tmpSet.add("k+l");
tmpSet.add("s+r");
tmpSet.add("z+l");
tmpSet.add("s+w");
m_prefixes.put("b", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("kh");
tmpSet.add("g");
tmpSet.add("ng");
tmpSet.add("ch");
tmpSet.add("j");
tmpSet.add("ny");
tmpSet.add("th");
tmpSet.add("d");
tmpSet.add("n");
tmpSet.add("tsh");
tmpSet.add("dz");
tmpSet.add("kh+y");
tmpSet.add("g+y");
tmpSet.add("kh+r");
tmpSet.add("g+r");
m_prefixes.put("m", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("kh");
tmpSet.add("g");
tmpSet.add("ch");
tmpSet.add("j");
tmpSet.add("th");
tmpSet.add("d");
tmpSet.add("ph");
tmpSet.add("b");
tmpSet.add("tsh");
tmpSet.add("dz");
tmpSet.add("kh+y");
tmpSet.add("g+y");
tmpSet.add("ph+y");
tmpSet.add("b+y");
tmpSet.add("kh+r");
tmpSet.add("g+r");
tmpSet.add("d+r");
tmpSet.add("ph+r");
tmpSet.add("b+r");
m_prefixes.put("'", tmpSet);
m_prefixes.put("\u2018", tmpSet);
m_prefixes.put("\u2019", tmpSet);
// set of suffix letters
// also included are some Skt letters b/c they occur often in suffix position in Skt words
m_suffixes = new HashSet<String>();
m_suffixes.add("'");
m_suffixes.add("\u2018");
m_suffixes.add("\u2019");
m_suffixes.add("g");
m_suffixes.add("ng");
m_suffixes.add("d");
m_suffixes.add("n");
m_suffixes.add("b");
m_suffixes.add("m");
m_suffixes.add("r");
m_suffixes.add("l");
m_suffixes.add("s");
m_suffixes.add("N");
m_suffixes.add("T");
m_suffixes.add("-n");
m_suffixes.add("-t");
// suffix2 => set of letters before
m_suff2 = new HashMap<String, HashSet<String>>();
tmpSet = new HashSet<String>();
tmpSet.add("g");
tmpSet.add("ng");
tmpSet.add("b");
tmpSet.add("m");
m_suff2.put("s", tmpSet);
tmpSet = new HashSet<String>();
tmpSet.add("n");
tmpSet.add("r");
tmpSet.add("l");
m_suff2.put("d", tmpSet);
// root letter index for very ambiguous three-stack syllables
m_ambiguous_key = new HashMap<String, Integer>();
m_ambiguous_key.put("dgs", 1);
m_ambiguous_key.put("dms", 1);
m_ambiguous_key.put("'gs", 1);
m_ambiguous_key.put("mngs", 0);
m_ambiguous_key.put("bgs", 0);
m_ambiguous_key.put("dbs", 1);
m_ambiguous_wylie = new HashMap<String, String>();
m_ambiguous_wylie.put("dgs", "dgas");
m_ambiguous_wylie.put("dms", "dmas");
m_ambiguous_wylie.put("'gs", "'gas");
m_ambiguous_wylie.put("mngs", "mangs");
m_ambiguous_wylie.put("bgs", "bags");
m_ambiguous_wylie.put("dbs", "dbas");
// *** Unicode to Converter mappings ***
// top letters
m_tib_top = new HashMap<Character, String>();
m_tib_top.put('\u0f40', "k");
m_tib_top.put('\u0f41', "kh");
m_tib_top.put('\u0f42', "g");
m_tib_top.put('\u0f43', "g+h");
m_tib_top.put('\u0f44', "ng");
m_tib_top.put('\u0f45', "c");
m_tib_top.put('\u0f46', "ch");
m_tib_top.put('\u0f47', "j");
m_tib_top.put('\u0f49', "ny");
m_tib_top.put('\u0f4a', "T");
m_tib_top.put('\u0f4b', "Th");
m_tib_top.put('\u0f4c', "D");
m_tib_top.put('\u0f4d', "D+h");
m_tib_top.put('\u0f4e', "N");
m_tib_top.put('\u0f4f', "t");
m_tib_top.put('\u0f50', "th");
m_tib_top.put('\u0f51', "d");
m_tib_top.put('\u0f52', "d+h");
m_tib_top.put('\u0f53', "n");
m_tib_top.put('\u0f54', "p");
m_tib_top.put('\u0f55', "ph");
m_tib_top.put('\u0f56', "b");
m_tib_top.put('\u0f57', "b+h");
m_tib_top.put('\u0f58', "m");
m_tib_top.put('\u0f59', "ts");
m_tib_top.put('\u0f5a', "tsh");
m_tib_top.put('\u0f5b', "dz");
m_tib_top.put('\u0f5c', "dz+h");
m_tib_top.put('\u0f5d', "w");
m_tib_top.put('\u0f5e', "zh");
m_tib_top.put('\u0f5f', "z");
m_tib_top.put('\u0f60', "'");
m_tib_top.put('\u0f61', "y");
m_tib_top.put('\u0f62', "r");
m_tib_top.put('\u0f63', "l");
m_tib_top.put('\u0f64', "sh");
m_tib_top.put('\u0f65', "Sh");
m_tib_top.put('\u0f66', "s");
m_tib_top.put('\u0f67', "h");
m_tib_top.put('\u0f68', "a");
m_tib_top.put('\u0f69', "k+Sh");
m_tib_top.put('\u0f6a', "R");
// subjoined letters
m_tib_subjoined = new HashMap<Character, String>();
m_tib_subjoined.put('\u0f90', "k");
m_tib_subjoined.put('\u0f91', "kh");
m_tib_subjoined.put('\u0f92', "g");
m_tib_subjoined.put('\u0f93', "g+h");
m_tib_subjoined.put('\u0f94', "ng");
m_tib_subjoined.put('\u0f95', "c");
m_tib_subjoined.put('\u0f96', "ch");
m_tib_subjoined.put('\u0f97', "j");
m_tib_subjoined.put('\u0f99', "ny");
m_tib_subjoined.put('\u0f9a', "T");
m_tib_subjoined.put('\u0f9b', "Th");
m_tib_subjoined.put('\u0f9c', "D");
m_tib_subjoined.put('\u0f9d', "D+h");
m_tib_subjoined.put('\u0f9e', "N");
m_tib_subjoined.put('\u0f9f', "t");
m_tib_subjoined.put('\u0fa0', "th");
m_tib_subjoined.put('\u0fa1', "d");
m_tib_subjoined.put('\u0fa2', "d+h");
m_tib_subjoined.put('\u0fa3', "n");
m_tib_subjoined.put('\u0fa4', "p");
m_tib_subjoined.put('\u0fa5', "ph");
m_tib_subjoined.put('\u0fa6', "b");
m_tib_subjoined.put('\u0fa7', "b+h");
m_tib_subjoined.put('\u0fa8', "m");
m_tib_subjoined.put('\u0fa9', "ts");
m_tib_subjoined.put('\u0faa', "tsh");
m_tib_subjoined.put('\u0fab', "dz");
m_tib_subjoined.put('\u0fac', "dz+h");
m_tib_subjoined.put('\u0fad', "w");
m_tib_subjoined.put('\u0fae', "zh");
m_tib_subjoined.put('\u0faf', "z");
m_tib_subjoined.put('\u0fb0', "'");
m_tib_subjoined.put('\u0fb1', "y");
m_tib_subjoined.put('\u0fb2', "r");
m_tib_subjoined.put('\u0fb3', "l");
m_tib_subjoined.put('\u0fb4', "sh");
m_tib_subjoined.put('\u0fb5', "Sh");
m_tib_subjoined.put('\u0fb6', "s");
m_tib_subjoined.put('\u0fb7', "h");
m_tib_subjoined.put('\u0fb8', "a");
m_tib_subjoined.put('\u0fb9', "k+Sh");
m_tib_subjoined.put('\u0fba', "W");
m_tib_subjoined.put('\u0fbb', "Y");
m_tib_subjoined.put('\u0fbc', "R");
// vowel signs:
// a-chen is not here because that's a top character, not a vowel sign.
// pre-composed "I" and "U" are dealt here; other pre-composed Skt vowels are more
// easily handled by a global replace in toWylie(), b/c they turn into subjoined "r"/"l".
m_tib_vowel = new HashMap<Character, String>();
m_tib_vowel.put('\u0f71', "A");
m_tib_vowel.put('\u0f72', "i");
m_tib_vowel.put('\u0f73', "I");
m_tib_vowel.put('\u0f74', "u");
m_tib_vowel.put('\u0f75', "U");
m_tib_vowel.put('\u0f7a', "e");
m_tib_vowel.put('\u0f7b', "ai");
m_tib_vowel.put('\u0f7c', "o");
m_tib_vowel.put('\u0f7d', "au");
m_tib_vowel.put('\u0f80', "-i");
// long (Skt) vowels
m_tib_vowel_long = new HashMap<String, String>();
m_tib_vowel_long.put("i", "I");
m_tib_vowel_long.put("u", "U");
m_tib_vowel_long.put("-i", "-I");
// final symbols => wylie
m_tib_final_wylie = new HashMap<Character, String>();
m_tib_final_wylie.put('\u0f7e', "M");
m_tib_final_wylie.put('\u0f82', "~M`");
m_tib_final_wylie.put('\u0f83', "~M");
m_tib_final_wylie.put('\u0f37', "X");
m_tib_final_wylie.put('\u0f35', "~X");
m_tib_final_wylie.put('\u0f39', "^");
m_tib_final_wylie.put('\u0f7f', "H");
m_tib_final_wylie.put('\u0f84', "?");
// final symbols by class
m_tib_final_class = new HashMap<Character, String>();
m_tib_final_class.put('\u0f7e', "M");
m_tib_final_class.put('\u0f82', "M");
m_tib_final_class.put('\u0f83', "M");
m_tib_final_class.put('\u0f37', "X");
m_tib_final_class.put('\u0f35', "X");
m_tib_final_class.put('\u0f39', "^");
m_tib_final_class.put('\u0f7f', "H");
m_tib_final_class.put('\u0f84', "?");
// special characters introduced by ^
m_tib_caret = new HashMap<String, String>();
m_tib_caret.put("ph", "f");
m_tib_caret.put("b", "v");
// other stand-alone characters
m_tib_other = new HashMap<Character, String>();
m_tib_other.put(' ', "_");
m_tib_other.put('\u0f04', "@");
m_tib_other.put('\u0f05', "#");
m_tib_other.put('\u0f06', "$");
m_tib_other.put('\u0f07', "%");
m_tib_other.put('\u0f08', "!");
m_tib_other.put('\u0f0b', " ");
m_tib_other.put('\u0f0c', "*");
m_tib_other.put('\u0f0d', "/");
m_tib_other.put('\u0f0e', "//");
m_tib_other.put('\u0f0f', ";");
m_tib_other.put('\u0f11', "|");
m_tib_other.put('\u0f14', ":");
m_tib_other.put('\u0f20', "0");
m_tib_other.put('\u0f21', "1");
m_tib_other.put('\u0f22', "2");
m_tib_other.put('\u0f23', "3");
m_tib_other.put('\u0f24', "4");
m_tib_other.put('\u0f25', "5");
m_tib_other.put('\u0f26', "6");
m_tib_other.put('\u0f27', "7");
m_tib_other.put('\u0f28', "8");
m_tib_other.put('\u0f29', "9");
m_tib_other.put('\u0f34', "=");
m_tib_other.put('\u0f3a', "<");
m_tib_other.put('\u0f3b', ">");
m_tib_other.put('\u0f3c', "(");
m_tib_other.put('\u0f3d', ")");
// all these stacked consonant combinations don't need "+"s in them
m_tib_stacks = new HashSet<String>();
m_tib_stacks.add("b+l");
m_tib_stacks.add("b+r");
m_tib_stacks.add("b+y");
m_tib_stacks.add("c+w");
m_tib_stacks.add("d+r");
m_tib_stacks.add("d+r+w");
m_tib_stacks.add("d+w");
m_tib_stacks.add("dz+r");
m_tib_stacks.add("g+l");
m_tib_stacks.add("g+r");
m_tib_stacks.add("g+r+w");
m_tib_stacks.add("g+w");
m_tib_stacks.add("g+y");
m_tib_stacks.add("h+r");
m_tib_stacks.add("h+w");
m_tib_stacks.add("k+l");
m_tib_stacks.add("k+r");
m_tib_stacks.add("k+w");
m_tib_stacks.add("k+y");
m_tib_stacks.add("kh+r");
m_tib_stacks.add("kh+w");
m_tib_stacks.add("kh+y");
m_tib_stacks.add("l+b");
m_tib_stacks.add("l+c");
m_tib_stacks.add("l+d");
m_tib_stacks.add("l+g");
m_tib_stacks.add("l+h");
m_tib_stacks.add("l+j");
m_tib_stacks.add("l+k");
m_tib_stacks.add("l+ng");
m_tib_stacks.add("l+p");
m_tib_stacks.add("l+t");
m_tib_stacks.add("l+w");
m_tib_stacks.add("m+r");
m_tib_stacks.add("m+y");
m_tib_stacks.add("n+r");
m_tib_stacks.add("ny+w");
m_tib_stacks.add("p+r");
m_tib_stacks.add("p+y");
m_tib_stacks.add("ph+r");
m_tib_stacks.add("ph+y");
m_tib_stacks.add("ph+y+w");
m_tib_stacks.add("r+b");
m_tib_stacks.add("r+d");
m_tib_stacks.add("r+dz");
m_tib_stacks.add("r+g");
m_tib_stacks.add("r+g+w");
m_tib_stacks.add("r+g+y");
m_tib_stacks.add("r+j");
m_tib_stacks.add("r+k");
m_tib_stacks.add("r+k+y");
m_tib_stacks.add("r+l");
m_tib_stacks.add("r+m");
m_tib_stacks.add("r+m+y");
m_tib_stacks.add("r+n");
m_tib_stacks.add("r+ng");
m_tib_stacks.add("r+ny");
m_tib_stacks.add("r+t");
m_tib_stacks.add("r+ts");
m_tib_stacks.add("r+ts+w");
m_tib_stacks.add("r+w");
m_tib_stacks.add("s+b");
m_tib_stacks.add("s+b+r");
m_tib_stacks.add("s+b+y");
m_tib_stacks.add("s+d");
m_tib_stacks.add("s+g");
m_tib_stacks.add("s+g+r");
m_tib_stacks.add("s+g+y");
m_tib_stacks.add("s+k");
m_tib_stacks.add("s+k+r");
m_tib_stacks.add("s+k+y");
m_tib_stacks.add("s+l");
m_tib_stacks.add("s+m");
m_tib_stacks.add("s+m+r");
m_tib_stacks.add("s+m+y");
m_tib_stacks.add("s+n");
m_tib_stacks.add("s+n+r");
m_tib_stacks.add("s+ng");
m_tib_stacks.add("s+ny");
m_tib_stacks.add("s+p");
m_tib_stacks.add("s+p+r");
m_tib_stacks.add("s+p+y");
m_tib_stacks.add("s+r");
m_tib_stacks.add("s+t");
m_tib_stacks.add("s+ts");
m_tib_stacks.add("s+w");
m_tib_stacks.add("sh+r");
m_tib_stacks.add("sh+w");
m_tib_stacks.add("t+r");
m_tib_stacks.add("t+w");
m_tib_stacks.add("th+r");
m_tib_stacks.add("ts+w");
m_tib_stacks.add("tsh+w");
m_tib_stacks.add("z+l");
m_tib_stacks.add("z+w");
m_tib_stacks.add("zh+w");
// a map used to split the input string into tokens for toUnicode().
// all letters which start tokens longer than one letter are mapped to the max length of
// tokens starting with that letter.
m_tokens_start = new HashMap<Character, Integer>();
m_tokens_start.put('S', 2);
m_tokens_start.put('/', 2);
m_tokens_start.put('d', 4);
m_tokens_start.put('g', 3);
m_tokens_start.put('b', 3);
m_tokens_start.put('D', 3);
m_tokens_start.put('z', 2);
m_tokens_start.put('~', 3);
m_tokens_start.put('-', 4);
m_tokens_start.put('T', 2);
m_tokens_start.put('a', 2);
m_tokens_start.put('k', 2);
m_tokens_start.put('t', 3);
m_tokens_start.put('s', 2);
m_tokens_start.put('c', 2);
m_tokens_start.put('n', 2);
m_tokens_start.put('p', 2);
m_tokens_start.put('\r', 2);
// also for tokenization - a set of tokens longer than one letter
m_tokens = new HashSet<String>();
m_tokens.add("-d+h");
m_tokens.add("dz+h");
m_tokens.add("-dh");
m_tokens.add("-sh");
m_tokens.add("-th");
m_tokens.add("D+h");
m_tokens.add("b+h");
m_tokens.add("d+h");
m_tokens.add("dzh");
m_tokens.add("g+h");
m_tokens.add("tsh");
m_tokens.add("~M`");
m_tokens.add("-I");
m_tokens.add("-d");
m_tokens.add("-i");
m_tokens.add("-n");
m_tokens.add("-t");
m_tokens.add("//");
m_tokens.add("Dh");
m_tokens.add("Sh");
m_tokens.add("Th");
m_tokens.add("ai");
m_tokens.add("au");
m_tokens.add("bh");
m_tokens.add("ch");
m_tokens.add("dh");
m_tokens.add("dz");
m_tokens.add("gh");
m_tokens.add("kh");
m_tokens.add("ng");
m_tokens.add("ny");
m_tokens.add("ph");
m_tokens.add("sh");
m_tokens.add("th");
m_tokens.add("ts");
m_tokens.add("zh");
m_tokens.add("~M");
m_tokens.add("~X");
m_tokens.add("\r\n");
}
static {
initHashes();
}
// setup a wylie object
private void initWylie(boolean check, boolean check_strict, boolean print_warnings, boolean fix_spacing) {
// check_strict requires check
if (check_strict && !check) {
throw new RuntimeException("check_strict requires check.");
}
this.check = check;
this.check_strict = check_strict;
this.print_warnings = print_warnings;
this.fix_spacing = fix_spacing;
}
// constructor passing all options
// see the comments at the beginning of this file for more details.
public Converter(boolean check, boolean check_strict, boolean print_warnings, boolean fix_spacing) {
initWylie(check, check_strict, print_warnings, fix_spacing);
}
// constructor with default options
public Converter() {
initWylie(true, true, false, true);
}
// helper functions to access the various hash tables
private final String consonant(String s) {
return m_consonant.get(s);
}
private final String subjoined(String s) {
return m_subjoined.get(s);
}
private final String vowel(String s) {
return m_vowel.get(s);
}
private final String final_uni(String s) {
return m_final_uni.get(s);
}
private final String final_class(String s) {
return m_final_class.get(s);
}
private final String other(String s) {
return m_other.get(s);
}
private final boolean isSpecial(String s) {
return m_special.contains(s);
}
private final boolean isSuperscript(String s) {
return m_superscripts.containsKey(s);
}
private final boolean superscript(String sup, String below) {
HashSet<?> tmpSet = m_superscripts.get(sup);
if (tmpSet == null) return false;
return tmpSet.contains(below);
}
private final boolean isSubscript(String s) {
return m_subscripts.containsKey(s);
}
private final boolean subscript(String sub, String above) {
HashSet<?> tmpSet = m_subscripts.get(sub);
if (tmpSet == null) return false;
return tmpSet.contains(above);
}
private final boolean isPrefix(String s) {
return m_prefixes.containsKey(s);
}
private final boolean prefix(String pref, String after) {
HashSet<?> tmpSet = m_prefixes.get(pref);
if (tmpSet == null) return false;
return tmpSet.contains(after);
}
private final boolean isSuffix(String s) {
return m_suffixes.contains(s);
}
private final boolean isSuff2(String s) {
return m_suff2.containsKey(s);
}
private final boolean suff2(String suff, String before) {
HashSet<?> tmpSet = m_suff2.get(suff);
if (tmpSet == null) return false;
return tmpSet.contains(before);
}
private final Integer ambiguous_key(String syll) {
return m_ambiguous_key.get(syll);
}
private final String ambiguous_wylie(String syll) {
return m_ambiguous_wylie.get(syll);
}
private final String tib_top(Character c) {
return m_tib_top.get(c);
}
private final String tib_subjoined(Character c) {
return m_tib_subjoined.get(c);
}
private final String tib_vowel(Character c) {
return m_tib_vowel.get(c);
}
private final String tib_vowel_long(String s) {
return m_tib_vowel_long.get(s);
}
private final String tib_final_wylie(Character c) {
return m_tib_final_wylie.get(c);
}
private final String tib_final_class(Character c) {
return m_tib_final_class.get(c);
}
private final String tib_caret(String s) {
return m_tib_caret.get(s);
}
private final String tib_other(Character c) {
return m_tib_other.get(c);
}
private final boolean tib_stack(String s) {
return m_tib_stacks.contains(s);
}
// split a string into Converter tokens;
// make sure there is room for at least one null element at the end of the array
private String[] splitIntoTokens(String str) {
String[] tokens = new String[str.length() + 2];
int o = 0, i = 0;
int maxlen = str.length();
TOKEN:
while (i < maxlen) {
char c = str.charAt(i);
Integer mlo = m_tokens_start.get(c);
// if there are multi-char tokens starting with this char, try them
if (mlo != null) {
for (int len = mlo.intValue(); len > 1; len--) {
if (i <= maxlen - len) {
String tr = str.substring(i, i + len);
if (m_tokens.contains(tr)) {
tokens[o++] = tr;
i += len;
continue TOKEN;
}
}
}
}
// things starting with backslash are special
if (c == '\\' && i <= maxlen - 2) {
if (str.charAt(i + 1) == 'u' && i <= maxlen - 6) {
tokens[o++] = str.substring(i, i + 6); // \\uxxxx
i += 6;
} else if (str.charAt(i + 1) == 'U' && i <= maxlen - 10) {
tokens[o++] = str.substring(i, i + 10); // \\Uxxxxxxxx
i += 10;
} else {
tokens[o++] = str.substring(i, i + 2); // \\x
i += 2;
}
continue TOKEN;
}
// otherwise just take one char
tokens[o++] = Character.toString(c);
i += 1;
}
return tokens;
}
/**
* Adjusts the input string based on the idea that people often are sloppy when writing
* Wylie and use ' ' instead of '_' when a space is actually meant in the output. This is
* written is a really simple brute force way to avoid issues of which regex's are supported
* in Javascript when translated via GWT. This routine does not handle the case of " /" which
* requires more care to accomodate "ng /" and "ngi /" and so on which are intentional since
* a tsheg is required in these cases. Also it is not feasible to handle "g " for a final "ga"
* at the end of a phrase where the '/' is usually omitted in favor of the descender on the
* "ga". Detecting this is non-trivial.
*
* @param str String to be normalized
* @return normalized String
*/
private String sloppyWylie(String str) {
str = str.replace(" (", "_(");
str = str.replace(") ", ")_");
str = str.replace("/ ", "/_");
str = str.replace(" 0", "_0");
str = str.replace(" 1", "_1");
str = str.replace(" 2", "_2");
str = str.replace(" 3", "_3");
str = str.replace(" 4", "_4");
str = str.replace(" 5", "_5");
str = str.replace(" 6", "_6");
str = str.replace(" 7", "_7");
str = str.replace(" 8", "_8");
str = str.replace(" 9", "_9");
str = str.replace("0 ", "0_");
str = str.replace("1 ", "1_");
str = str.replace("2 ", "2_");
str = str.replace("3 ", "3_");
str = str.replace("4 ", "4_");
str = str.replace("5 ", "5_");
str = str.replace("6 ", "6_");
str = str.replace("7 ", "7_");
str = str.replace("8 ", "8_");
str = str.replace("9 ", "9_");
str = str.replace("_ ", "__");
return str;
}
// Convenience function; convert to Converter to Unicode, without returning warnings
public String toUnicode(String str) {
return toUnicode(str, null, true);
}
// Converts a Converter (EWTS) string to unicode. If 'warns' is not the null List, puts warnings into it.
public String toUnicode(String str, List<String> warns, boolean sloppy) {
if (str == null) {
return " - no data - ";
}
if (sloppy) {
str = sloppyWylie(str);
}
StringBuilder out = new StringBuilder();
int line = 1;
int units = 0;
// remove initial spaces if required
if (this.fix_spacing) {
str = str.replaceFirst("^\\s+", "");
}
// split into tokens
String[] tokens = splitIntoTokens(str);
int i = 0;
// iterate over the tokens
ITER:
while (tokens[i] != null) {
String t = tokens[i];
String o;
// [non-tibetan text] : pass through, nesting brackets
if (t.equals("[")) {
int nesting = 1;
i++;
ESC:
while (tokens[i] != null) {
t = tokens[i++];
if (t.equals("[")) nesting++;
if (t.equals("]")) nesting--;
if (nesting == 0) continue ITER;
// handle unicode escapes and \1-char escapes within [comments]...
if (t.startsWith("\\u") || t.startsWith("\\U")) {
o = unicodeEscape(warns, line, t);
if (o != null) {
out.append(o);
continue ESC;
}
}
if (t.startsWith("\\")) {
o = t.substring(1);
} else {
o = t;
}
out.append(o);
}
warnl(warns, line, "Unfinished [non-Converter stuff].");
break ITER;
}
// punctuation, numbers, etc
o = other(t);
if (o != null) {
out.append(o);
i++;
units++;
// collapse multiple spaces?
if (t.equals(" ") && this.fix_spacing) {
while (tokens[i] != null && tokens[i].equals(" ")) i++;
}
continue ITER;
}
// vowels & consonants: process tibetan script up to a tsek, punctuation or line noise
if (vowel(t) != null || consonant(t) != null) {
WylieTsekbar tb = toUnicodeOneTsekbar(tokens, i);
StringBuilder word = new StringBuilder();
for (int j = 0; j < tb.tokens_used; j++) {
word.append(tokens[i+j]);
}
out.append(tb.uni_string);
i += tb.tokens_used;
units++;
for (String w : tb.warns) {
warnl(warns, line, "\"" + word.toString() + "\": " + w);
}
continue ITER;
}
// *** misc unicode and line handling stuff ***
// ignore BOM and zero-width space
if (t.equals("\ufeff") || t.equals("\u200b")) {
i++;
continue ITER;
}
// \\u, \\U unicode characters
if (t.startsWith("\\u") || t.startsWith("\\U")) {
o = unicodeEscape(warns, line, t);
if (o != null) {
i++;
out.append(o);
continue ITER;
}
}
// backslashed characters
if (t.startsWith("\\")) {
out.append(t.substring(1));
i++;
continue ITER;
}
// count lines
if (t.equals("\r\n") || t.equals("\n") || t.equals("\r")) {
line++;
out.append(t);
i++;
// also eat spaces after newlines (optional)
if (this.fix_spacing) {
while (tokens[i] != null && tokens[i].equals(" ")) i++;
}
continue ITER;
}
// stuff that shouldn't occur out of context: special chars and remaining [a-zA-Z]
char c = t.charAt(0);
if (isSpecial(t) || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
warnl(warns, line, "Unexpected character \"" + t + "\".");
}
// anything else: pass through
out.append(t);
i++;
}
if (units == 0) warn(warns, "No Tibetan characters found!");
return out.toString();
}
// does this string consist of only hexadecimal digits?
private boolean validHex(String t) {
for (int i = 0; i < t.length(); i++) {
char c = t.charAt(i);
if (!((c >= 'a' && c <= 'f') || (c >= '0' && c <= '9'))) return false;
}
return true;
}
// handle a Converter unicode escape, \\uxxxx or \\Uxxxxxxxx
private String unicodeEscape(List<String> warns, int line, String t) {
String hex = t.substring(2);
if (hex.isEmpty()) return null;
if (!validHex(hex)) {
warnl(warns, line, "\"" + t + "\": invalid hex code.");
return "";
}
return Character.valueOf((char)Integer.parseInt(hex, 16)).toString();
}
// generate a warning if we are keeping them; prints it out if we were asked to
private void warn (List<String> warns, String str) {
if (warns != null) warns.add(str);
if (this.print_warnings) System.out.println(str);
}
// warn with line number
private void warnl(List<String> warns, int line, String str) {
warn(warns, "line " + line + ": " + str);
}
// debug print
@SuppressWarnings("unused")
private void debug (String str) {
System.out.println(str);
}
// debug variable value
@SuppressWarnings("unused")
private void debugvar(Object o, String name) {
System.out.println(">>" + name + "<< : (" + (o == null ? "NULL" : o.toString()) + ")");
}
// join a list (ArrayList or LinkedList) of strings into a single string
private String joinStrings(List<String> a, String sep) {
StringBuilder out = new StringBuilder();
int len = a.size();
int i = 0;
for (String v : a) {
out.append(v);
if (sep != null && i < len - 1) out.append(sep);
i++;
}
return out.toString();
}
// Converts one stack's worth of Converter into unicode, starting at the given index
// within the array of tokens.
// Assumes that the first available token is valid, and is either a vowel or a consonant.
// Returns a WylieStack object.
@SuppressWarnings("unused")
private WylieStack toUnicodeOneStack(String[] tokens, int i) {
int orig_i = i;
String t, t2, o;
StringBuilder out = new StringBuilder();
ArrayList<String> warns = new ArrayList<String>();
int consonants = 0; // how many consonants found
String vowel_found = null; // any vowels (including a-chen)
String vowel_sign = null; // any vowel signs (that go under or above the main stack)
String single_consonant = null; // did we find just a single consonant?
boolean plus = false; // any explicit subjoining via '+'?
int caret = 0; // find any '^'?
HashMap<String, String> final_found = new HashMap<String, String>(); // keep track of finals (H, M, etc) by class
// do we have a superscript?
t = tokens[i];
t2 = tokens[i+1];
if (t2 != null && isSuperscript(t) && superscript(t, t2)) {
if (this.check_strict) {
String next = consonantString(tokens, i+1);
if (!superscript(t, next)) {
next = next.replace("+", "");
warns.add("Superscript \"" + t + "\" does not occur above combination \"" + next + "\".");
}
}
out.append(consonant(t));
consonants++;
i++;
while (tokens[i] != null && tokens[i].equals("^")) {
caret++;
i++;
}
}
// main consonant + stuff underneath.
// this is usually executed just once, but the "+" subjoining operator makes it come back here
MAIN:
while (true) {
// main consonant (or a "a" after a "+")
t = tokens[i];
if (consonant(t) != null || (out.length() > 0 && subjoined(t) != null)) {
if (out.length() > 0) {
out.append(subjoined(t));
} else {
out.append(consonant(t));
}
i++;
if (t.equals("a")) {
vowel_found = "a";
} else {
consonants++;
single_consonant = t;
}
while (tokens[i] != null && tokens[i].equals("^")) {
caret++;
i++;
}
// subjoined: rata, yata, lata, wazur. there can be up two subjoined letters in a stack.
for (int z = 0; z < 2; z++) {
t2 = tokens[i];
if (t2 != null && isSubscript(t2)) {
// lata does not occur below multiple consonants
// (otherwise we mess up "brla" = "b.r+la")
if (t2.equals("l") && consonants > 1) break;
// full stack checking (disabled by "+")
if (this.check_strict && !plus) {
String prev = consonantStringBackwards(tokens, i-1, orig_i);
if (!subscript(t2, prev)) {
prev = prev.replace("+", "");
warns.add("Subjoined \"" + t2 + "\" not expected after \"" + prev + "\".");
}
// simple check only
} else if (this.check) {
if (!subscript(t2, t) && !(z == 1 && t2.equals("w") && t.equals("y"))) {
warns.add("Subjoined \"" + t2 + "\"not expected after \"" + t + "\".");
}
}
out.append(subjoined(t2));
i++;
consonants++;
while (tokens[i] != null && tokens[i].equals("^")) {
caret++;
i++;
}
t = t2;
} else {
break;
}
}
}
// caret (^) can come anywhere in Converter but in Unicode we generate it at the end of
// the stack but before vowels if it came there (seems to be what OpenOffice expects),
// or at the very end of the stack if that's how it was in the Converter.
if (caret > 0) {
if (caret > 1) {
warns.add("Cannot have more than one \"^\" applied to the same stack.");
}
final_found.put(final_class("^"), "^");
out.append(final_uni("^"));
caret = 0;
}
// vowel(s)
t = tokens[i];
if (t != null && vowel(t) != null) {
if (out.length() == 0) out.append(vowel("a"));
if (!t.equals("a")) out.append(vowel(t));
i++;
vowel_found = t;
if (!t.equals("a")) vowel_sign = t;
}
// plus sign: forces more subjoining
t = tokens[i];
if (t != null && t.equals("+")) {
i++;
plus = true;
// sanity check: next token must be vowel or subjoinable consonant.
t = tokens[i];
if (t == null || (vowel(t) == null && subjoined(t) == null)) {
if (this.check) warns.add("Expected vowel or consonant after \"+\".");
break MAIN;
}
// consonants after vowels doesn't make much sense but process it anyway
if (this.check) {
if (vowel(t) == null && vowel_sign != null) {
warns.add("Cannot subjoin consonant (" + t + ") after vowel (" + vowel_sign + ") in same stack.");
} else if (t.equals("a") && vowel_sign != null) {
warns.add("Cannot subjoin a-chen (a) after vowel (" + vowel_sign + ") in same stack.");
}
}
continue MAIN;
}
break MAIN;
}
// final tokens
t = tokens[i];
while (t != null && final_class(t) != null) {
String uni = final_uni(t);
String klass = final_class(t);
// check for duplicates
if (final_found.containsKey(klass)) {
if (final_found.get(klass).equals(t)) {
warns.add("Cannot have two \"" + t + "\" applied to the same stack.");
} else {
warns.add("Cannot have \"" + t + "\" and \"" + final_found.get(klass) + "\" applied to the same stack.");
}
} else {
final_found.put(klass, t);
out.append(uni);
}
i++;
single_consonant = null;
t = tokens[i];
}
// if next is a dot "." (stack separator), skip it.
if (tokens[i] != null && tokens[i].equals(".")) i++;
// if we had more than a consonant and no vowel, and no explicit "+" joining, backtrack and
// return the 1st consonant alone
if (consonants > 1 && vowel_found == null) {
if (plus) {
if (this.check) warns.add("Stack with multiple consonants should end with vowel.");
} else {
i = orig_i + 1;
consonants = 1;
single_consonant = tokens[orig_i];
out.setLength(0);
out.append(consonant(single_consonant));
}
}
// calculate "single consonant"
if (consonants != 1 || plus) {
single_consonant = null;
}
// return the stuff as a WylieStack struct
WylieStack ret = new WylieStack();
ret.uni_string = out.toString();
ret.tokens_used = i - orig_i;
if (vowel_found != null) {
ret.single_consonant = null;
} else {
ret.single_consonant = single_consonant;
}
if (vowel_found != null && vowel_found.equals("a")) {
ret.single_cons_a = single_consonant;
} else {
ret.single_cons_a = null;
}
ret.warns = warns;
ret.visarga = final_found.containsKey("H");
return ret;
}
// Converts successive stacks of Converter into unicode, starting at the given index
// within the array of tokens.
//
// Assumes that the first available token is valid, and is either a vowel or a consonant.
// Returns a WylieTsekbar object
@SuppressWarnings("unused")
private WylieTsekbar toUnicodeOneTsekbar(String[] tokens, int i) {
int orig_i = i;
String t = tokens[i];
// variables for tracking the state within the syllable as we parse it
WylieStack stack = null;
String prev_cons = null;
boolean visarga = false;
// variables for checking the root letter, after parsing a whole tsekbar made of only single
// consonants and one consonant with "a" vowel
boolean check_root = true;
ArrayList<String> consonants = new ArrayList<String>();
int root_idx = -1;
StringBuilder out = new StringBuilder();
ArrayList<String> warns = new ArrayList<String>();
// the type of token that we are expecting next in the input stream
// - PREFIX : expect a prefix consonant, or a main stack
// - MAIN : expect only a main stack
// - SUFF1 : expect a 1st suffix
// - SUFF2 : expect a 2nd suffix
// - NONE : expect nothing (after a 2nd suffix)
//
// the state machine is actually more lenient than this, in that a "main stack" is allowed
// to come at any moment, even after suffixes. this is because such syllables are sometimes
// found in abbreviations or other places. basically what we check is that prefixes and
// suffixes go with what they are attached to.
//
// valid tsek-bars end in one of these states: SUFF1, SUFF2, NONE
State state = State.PREFIX;
// iterate over the stacks of a tsek-bar
STACK:
while (t != null && (vowel(t) != null || consonant(t) != null) && !visarga) {
// translate a stack
if (stack != null) prev_cons = stack.single_consonant;
stack = toUnicodeOneStack(tokens, i);
i += stack.tokens_used;
t = tokens[i];
out.append(stack.uni_string);
warns.addAll(stack.warns);
visarga = stack.visarga;
if (!this.check) continue;
// check for syllable structure consistency by iterating a simple state machine
// - prefix consonant
if (state == State.PREFIX && stack.single_consonant != null) {
consonants.add(stack.single_consonant);
if (isPrefix(stack.single_consonant)) {
String next = t;
if (this.check_strict) next = consonantString(tokens, i);
if (next != null && !prefix(stack.single_consonant, next)) {
next = next.replace("+", "");
warns.add("Prefix \"" + stack.single_consonant + "\" does not occur before \"" + next + "\".");
}
} else {
warns.add("Invalid prefix consonant: \"" + stack.single_consonant + "\".");
}
state = State.MAIN;
// - main stack with vowel or multiple consonants
} else if (stack.single_consonant == null) {
state = State.SUFF1;
// keep track of the root consonant if it was a single cons with an "a" vowel
if (root_idx >= 0) {
check_root = false;
} else if (stack.single_cons_a != null) {
consonants.add(stack.single_cons_a);
root_idx = consonants.size() - 1;
}
// - unexpected single consonant after prefix
} else if (state == State.MAIN) {
warns.add("Expected vowel after \"" + stack.single_consonant + "\".");
// - 1st suffix
} else if (state == State.SUFF1) {
consonants.add(stack.single_consonant);
// check this one only in strict mode b/c it trips on lots of Skt stuff
if (this.check_strict) {
if (!isSuffix(stack.single_consonant)) {
warns.add("Invalid suffix consonant: \"" + stack.single_consonant + "\".");
}
}
state = State.SUFF2;
// - 2nd suffix
} else if (state == State.SUFF2) {
consonants.add(stack.single_consonant);
if (isSuff2(stack.single_consonant)) {
if (!suff2(stack.single_consonant, prev_cons)) {
warns.add("Second suffix \"" + stack.single_consonant + "\" does not occur after \"" + prev_cons + "\".");
}
} else {
warns.add("Invalid 2nd suffix consonant: \"" + stack.single_consonant + "\".");
}
state = State.NONE;
// - more crap after a 2nd suffix
} else if (state == State.NONE) {
warns.add("Cannot have another consonant \"" + stack.single_consonant + "\" after 2nd suffix.");
}
}
if (state == State.MAIN && stack.single_consonant != null && isPrefix(stack.single_consonant)) {
warns.add("Vowel expected after \"" + stack.single_consonant + "\".");
}
// check root consonant placement only if there were no warnings so far, and the syllable
// looks ambiguous. not many checks are needed here because the previous state machine
// already takes care of most illegal combinations.
if (this.check && warns.size() == 0 && check_root && root_idx >= 0) {
// 2 letters where each could be prefix/suffix: root is 1st
if (consonants.size() == 2 && root_idx != 0 &&
prefix(consonants.get(0), consonants.get(1)) &&
isSuffix(consonants.get(1)))
{
warns.add("Syllable should probably be \"" + consonants.get(0) + "a" + consonants.get(1) + "\".");
// 3 letters where 1st can be prefix, 2nd can be postfix before "s" and last is "s":
// use a lookup table as this is completely ambiguous.
} else if (consonants.size() == 3 && isPrefix(consonants.get(0)) &&
suff2("s", consonants.get(1)) && consonants.get(2).equals("s"))
{
String cc = joinStrings(consonants, "");
cc = cc.replace('\u2018', '\'');
cc = cc.replace('\u2019', '\''); // typographical quotes
Integer expect_key = ambiguous_key(cc);
if (expect_key != null && expect_key.intValue() != root_idx) {
warns.add("Syllable should probably be \"" + ambiguous_wylie(cc) + "\".");
}
}
}
// return the stuff as a WylieTsekbar struct
WylieTsekbar ret = new WylieTsekbar();
ret.uni_string = out.toString();
ret.tokens_used = i - orig_i;
ret.warns = warns;
return ret;
}
// Looking from i onwards within tokens, returns as many consonants as it finds,
// up to and not including the next vowel or punctuation. Skips the caret "^".
// Returns: a string of consonants joined by "+" signs.
private String consonantString(String[] tokens, int i) {
ArrayList<String> out = new ArrayList<String>();
String t;
while (tokens[i] != null) {
t = tokens[i++];
if (t.equals("+") || t.equals("^")) continue;
if (consonant(t) == null) break;
out.add(t);
}
return joinStrings(out, "+");
}
// Looking from i backwards within tokens, at most up to orig_i, returns as
// many consonants as it finds, up to and not including the next vowel or
// punctuation. Skips the caret "^".
// Returns: a string of consonants (in forward order) joined by "+" signs.
private String consonantStringBackwards(String[] tokens, int i, int orig_i) {
LinkedList<String> out = new LinkedList<String>();
String t;
while (i >= orig_i && tokens[i] != null) {
t = tokens[i--];
if (t.equals("+") || t.equals("^")) continue;
if (consonant(t) == null) break;
out.addFirst(t);
}
return joinStrings(out, "+");
}
// Converts from Unicode strings to Converter (EWTS) transliteration, without warnings,
// including escaping of non-tibetan into [comments].
public String toWylie(String str) {
return toWylie(str, null, true);
}
// Converts from Unicode strings to Converter (EWTS) transliteration.
//
// Arguments are:
// str : the unicode string to be converted
// escape: whether to escape non-tibetan characters according to Converter encoding.
// if escape == false, anything that is not tibetan will be just passed through.
//
// Returns: the transliterated string.
//
// To get the warnings, call getWarnings() afterwards.
public String toWylie(String str, List<String> warns, boolean escape) {
StringBuilder out = new StringBuilder();
int line = 1;
int units = 0;
// globally search and replace some deprecated pre-composed Sanskrit vowels
str = str.replace("\u0f76", "\u0fb2\u0f80");
str = str.replace("\u0f77", "\u0fb2\u0f71\u0f80");
str = str.replace("\u0f78", "\u0fb3\u0f80");
str = str.replace("\u0f79", "\u0fb3\u0f71\u0f80");
str = str.replace("\u0f81", "\u0f71\u0f80");
int i = 0;
int len = str.length();
// iterate over the string, codepoint by codepoint
ITER:
while (i < len) {
char t = str.charAt(i);
// found tibetan script - handle one tsekbar
if (tib_top(t) != null) {
ToWylieTsekbar tb = toWylieOneTsekbar(str, len, i);
out.append(tb.wylie);
i += tb.tokens_used;
units++;
for (String w : tb.warns) {
warnl(warns, line, w);
}
if (!escape) i += handleSpaces(str, i, out);
continue ITER;
}
// punctuation and special stuff. spaces are tricky:
// - in non-escaping mode: spaces are not turned to '_' here (handled by handleSpaces)
// - in escaping mode: don't do spaces if there is non-tibetan coming, so they become part
// of the [ escaped block].
String o = tib_other(t);
if (o != null && (t != ' ' || (escape && !followedByNonTibetan(str, i)))) {
out.append(o);
i++;
units++;
if (!escape) i += handleSpaces(str, i, out);
continue ITER;
}
// newlines, count lines. "\r\n" together count as one newline.
if (t == '\r' || t == '\n') {
line++;
i++;
out.append(t);
if (t == '\r' && i < len && str.charAt(i) == '\n') {
i++;
out.append('\n');
}
continue ITER;
}
// ignore BOM and zero-width space
if (t == '\ufeff' || t == '\u200b') {
i++;
continue ITER;
}
// anything else - pass along?
if (!escape) {
out.append(t);
i++;
continue ITER;
}
// other characters in the tibetan plane, escape with \\u0fxx
if (t >= '\u0f00' && t <= '\u0fff') {
String c = formatHex(t);
out.append(c);
i++;
// warn for tibetan codepoints that should appear only after a tib_top
if (tib_subjoined(t) != null || tib_vowel(t) != null || tib_final_wylie(t) != null) {
warnl(warns, line, "Tibetan sign " + c + " needs a top symbol to attach to.");
}
continue ITER;
}
// ... or escape according to Converter:
// put it in [comments], escaping [] sequences and closing at line ends
out.append("[");
while (tib_top(t) == null && (tib_other(t) == null || t == ' ') && t != '\r' && t != '\n') {
// \escape [opening and closing] brackets
if (t == '[' || t == ']') {
out.append("\\");
out.append(t);
// unicode-escape anything in the tibetan plane (i.e characters not handled by Converter)
} else if (t >= '\u0f00' && t <= '\u0fff') {
out.append(formatHex(t));
// and just pass through anything else!
} else {
out.append(t);
}
if (++i >= len) break;
t = str.charAt(i);
}
out.append("]");
}
return out.toString();
}
// given a character, return a string like "\\uxxxx", with its code in hex
private final String formatHex(char t) {
// not compatible with GWT...
// return String.format("\\u%04x", (int)t);
StringBuilder sb = new StringBuilder();
sb.append("\\u");
String s = Integer.toHexString((int)t);
for (int i = s.length(); i < 4; i++) {
sb.append('0');
}
sb.append(s);
return sb.toString();
}
// handles spaces (if any) in the input stream, turning them into '_'.
// this is abstracted out because in non-escaping mode, we only want to turn spaces into _
// when they come in the middle of Tibetan script.
private int handleSpaces(String str, int i, StringBuilder out) {
int found = 0;
@SuppressWarnings("unused")
int orig_i = i;
while (i < str.length() && str.charAt(i) == ' ') {
i++;
found++;
}
if (found == 0 || i == str.length()) return 0;
char t = str.charAt(i);
if (tib_top(t) == null && tib_other(t) == null) return 0;
// found 'found' spaces between two tibetan bits; generate the same number of '_'s
for (i = 0; i < found; i++) {
out.append('_');
}
return found;
}
// for space-handling in escaping mode: is the next thing coming (after a number of spaces)
// some non-tibetan bit, within the same line?
private boolean followedByNonTibetan(String str, int i) {
int len = str.length();
while (i < len && str.charAt(i) == ' ') {
i++;
}
if (i == len) return false;
char t = str.charAt(i);
return tib_top(t) == null && tib_other(t) == null && t != '\r' && t != '\n';
}
// Convert Unicode to Converter: one tsekbar
private ToWylieTsekbar toWylieOneTsekbar(String str, int len, int i) {
int orig_i = i;
ArrayList<String> warns = new ArrayList<String>();
ArrayList<ToWylieStack> stacks = new ArrayList<ToWylieStack>();
ITER:
while (true) {
ToWylieStack st = toWylieOneStack(str, len, i);
stacks.add(st);
warns.addAll(st.warns);
i += st.tokens_used;
if (st.visarga) break ITER;
if (i >= len || tib_top(str.charAt(i)) == null) break ITER;
}
// figure out if some of these stacks can be prefixes or suffixes (in which case
// they don't need their "a" vowels)
int last = stacks.size() - 1;
if (stacks.size() > 1 && stacks.get(0).single_cons != null) {
// we don't count the wazur in the root stack, for prefix checking
String cs = stacks.get(1).cons_str.replace("+w", "");
if (prefix(stacks.get(0).single_cons, cs)) {
stacks.get(0).prefix = true;
}
}
if (stacks.size() > 1 && stacks.get(last).single_cons != null && isSuffix(stacks.get(last).single_cons)) {
stacks.get(last).suffix = true;
}
if (stacks.size() > 2 && stacks.get(last).single_cons != null && stacks.get(last - 1).single_cons != null &&
isSuffix(stacks.get(last - 1).single_cons) &&
suff2(stacks.get(last).single_cons, stacks.get(last - 1).single_cons)) {
stacks.get(last).suff2 = true;
stacks.get(last - 1).suffix = true;
}
// if there are two stacks and both can be prefix-suffix, then 1st is root
if (stacks.size() == 2 && stacks.get(0).prefix && stacks.get(1).suffix) {
stacks.get(0).prefix = false;
}
// if there are three stacks and they can be prefix, suffix and suff2, then check w/ a table
if (stacks.size() == 3 && stacks.get(0).prefix && stacks.get(1).suffix && stacks.get(2).suff2) {
StringBuilder strb = new StringBuilder();
for (ToWylieStack st : stacks) {
strb.append(st.single_cons);
}
String ztr = strb.toString();
Integer root = ambiguous_key(ztr);
if (root == null) {
warns.add("Ambiguous syllable found: root consonant not known for \"" + ztr + "\".");
// make it up... (ex. "mgas" for ma, ga, sa)
root = 1;
}
stacks.get(root).prefix = stacks.get(root).suffix = false;
stacks.get(root + 1).suff2 = false;
}
// if the prefix together with the main stack could be mistaken for a single stack, add a "."
if (stacks.get(0).prefix && tib_stack(stacks.get(0).single_cons + "+" + stacks.get(1).cons_str)) {
stacks.get(0).dot = true;
}
// put it all together
StringBuilder out = new StringBuilder();
for (ToWylieStack st : stacks) {
out.append(putStackTogether(st));
}
ToWylieTsekbar ret = new ToWylieTsekbar();
ret.wylie = out.toString();
ret.tokens_used = i - orig_i;
ret.warns = warns;
return ret;
}
// Unicode to Converter: one stack at a time
private ToWylieStack toWylieOneStack(String str, int len, int i) {
int orig_i = i;
String ffinal = null, vowel = null, klass = null;
// split the stack into a ToWylieStack object:
// - top symbol
// - stacked signs (first is the top symbol again, then subscribed main characters...)
// - caret (did we find a stray tsa-phru or not?)
// - vowel signs (including small subscribed a-chung, "-i" Skt signs, etc)
// - final stuff (including anusvara, visarga, halanta...)
// - and some more variables to keep track of what has been found
ToWylieStack st = new ToWylieStack();
// assume: tib_top(t) exists
char t = str.charAt(i++);
st.top = tib_top(t);
st.stack.add(tib_top(t));
// grab everything else below the top sign and classify in various categories
while (i < len) {
t = str.charAt(i);
String o;
if ((o = tib_subjoined(t)) != null) {
i++;
st.stack.add(o);
// check for bad ordering
if (!st.finals.isEmpty()) {
st.warns.add("Subjoined sign \"" + o + "\" found after final sign \"" + ffinal + "\".");
} else if (!st.vowels.isEmpty()) {
st.warns.add("Subjoined sign \"" + o + "\" found after vowel sign \"" + vowel + "\".");
}
} else if ((o = tib_vowel(t)) != null) {
i++;
st.vowels.add(o);
if (vowel == null) vowel = o;
// check for bad ordering
if (!st.finals.isEmpty()) {
st.warns.add("Vowel sign \"" + o + "\" found after final sign \"" + ffinal + "\".");
}
} else if ((o = tib_final_wylie(t)) != null) {
i++;
klass = tib_final_class(t);
if (o.equals("^")) {
st.caret = true;
} else {
if (o.equals("H")) st.visarga = true;
st.finals.add(o);
if (ffinal == null) ffinal = o;
// check for invalid combinations
if (st.finals_found.containsKey(klass)) {
st.warns.add("Final sign \"" + o + "\" should not combine with found after final sign \"" + ffinal + "\".");
} else {
st.finals_found.put(klass, o);
}
}
} else {
break;
}
}
// now analyze the stack according to various rules
// a-chen with vowel signs: remove the "a" and keep the vowel signs
if (st.top.equals("a") && st.stack.size() == 1 && !st.vowels.isEmpty()) {
st.stack.removeFirst();
}
// handle long vowels: A+i becomes I, etc.
if (st.vowels.size() > 1 &&
st.vowels.get(0).equals("A") &&
tib_vowel_long(st.vowels.get(1)) != null) {
String l = tib_vowel_long(st.vowels.get(1));
st.vowels.removeFirst();
st.vowels.removeFirst();
st.vowels.addFirst(l);
}
// special cases: "ph^" becomes "f", "b^" becomes "v"
if (st.caret && st.stack.size() == 1 && tib_caret(st.top) != null) {
String l = tib_caret(st.top);
st.top = l;
st.stack.removeFirst();
st.stack.addFirst(l);
st.caret = false;
}
st.cons_str = joinStrings(st.stack, "+");
// if this is a single consonant, keep track of it (useful for prefix/suffix analysis)
if (st.stack.size() == 1 &&
!st.stack.get(0).equals("a") &&
!st.caret &&
st.vowels.isEmpty() &&
st.finals.isEmpty()) {
st.single_cons = st.cons_str;
}
// return the analyzed stack
st.tokens_used = i - orig_i;
return st;
}
// Puts an analyzed stack together into Converter output, adding an implicit "a" if needed.
private String putStackTogether(ToWylieStack st) {
StringBuilder out = new StringBuilder();
// put the main elements together... stacked with "+" unless it's a regular stack
if (tib_stack(st.cons_str)) {
out.append(joinStrings(st.stack, ""));
} else {
out.append(st.cons_str);
}
// caret (tsa-phru) goes here as per some (halfway broken) Unicode specs...
if (st.caret) {
out.append("^");
}
// vowels...
if (!st.vowels.isEmpty()) {
out.append(joinStrings(st.vowels, "+"));
} else if (!st.prefix && !st.suffix && !st.suff2 &&
(st.cons_str.isEmpty() || st.cons_str.charAt(st.cons_str.length() - 1) != 'a')) {
out.append("a");
}
// final stuff
out.append(joinStrings(st.finals, ""));
if (st.dot) out.append(".");
return out.toString();
}
// HELPER CLASSES AND STRUCTURES
// An Enum for the list of states used to check the consistency of a Tibetan tsekbar.
private static enum State {
PREFIX, MAIN, SUFF1, SUFF2, NONE
}
// A simple class to encapsulate the return value of toUnicodeOneStack.
// Quick and dirty and not particularly OO.
private static class WylieStack {
// the converted unicode string
public String uni_string;
// how many tokens from the stream were used
public int tokens_used;
// did we find a single consonant without vowel? if so which one
public String single_consonant;
// did we find a single consonant with an "a"? if so which one
public String single_cons_a;
// list of warnings
public ArrayList<String> warns;
// found a visarga?
public boolean visarga;
}
// A simple class to encapsulate the return value of toUnicodeOneTsekbar.
// Quick and dirty and not particularly OO.
private static class WylieTsekbar {
// the converted unicode string
public String uni_string;
// how many tokens from the stream were used
public int tokens_used;
// list of warnings
public ArrayList<String> warns;
}
// A simple class to encapsulate an analyzed tibetan stack, while
// converting Unicode to Converter.
private static class ToWylieStack {
// top symbol
public String top;
// the entire stack of consonants, as a List of Strings
public LinkedList<String> stack;
// found a caret (^) or not
public boolean caret;
// vowels found, as a List of Strings
public LinkedList<String> vowels;
// finals found, as a List of Strings
public ArrayList<String> finals;
// finals found, as a HashMap of Strings to Strings (klass => wylie)
public HashMap<String, String> finals_found;
// did we see a visarga?
public boolean visarga;
// all consonants separated by '+'
public String cons_str;
// is this a single consonant with no vowel signs or finals?
public String single_cons;
// boolean, later set to true if this is a prefix, suffix, 2nd suffix, or if we need a dot as in "g.yag"
public boolean prefix, suffix, suff2, dot;
// how many tokens from the stream were used
public int tokens_used;
// list of warnings
public ArrayList<String> warns;
// constructor - initialize a few arrays
public ToWylieStack() {
this.stack = new LinkedList<String>();
this.vowels = new LinkedList<String>();
this.finals = new ArrayList<String>();
this.finals_found = new HashMap<String, String>();
this.warns = new ArrayList<String>();
}
}
// A simple class to encapsulate the return value of toWylieOneTsekbar.
// Quick and dirty and not particularly OO.
private static class ToWylieTsekbar {
// the converted wylie string
public String wylie;
// how many tokens from the stream were used
public int tokens_used;
// list of warnings
public ArrayList<String> warns;
}
}
|
lower case some safe letters
|
src/main/java/io/bdrc/xmltoldmigration/Converter.java
|
lower case some safe letters
|
|
Java
|
apache-2.0
|
d4e6a4b043040a6080e3785010349e043bc08fd9
| 0
|
bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud
|
package com.planet_ink.coffee_mud.Abilities.Properties;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.MaskingLibrary;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2004-2016 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Prop_ModExperience extends Property
{
@Override
public String ID()
{
return "Prop_ModExperience";
}
@Override
public String name()
{
return "Modifying Experience Gained";
}
@Override
protected int canAffectCode()
{
return Ability.CAN_MOBS | Ability.CAN_ITEMS | Ability.CAN_AREAS | Ability.CAN_ROOMS;
}
protected String operationFormula = "";
protected boolean selfXP = false;
protected LinkedList<CMath.CompiledOperation> operation = null;
protected MaskingLibrary.CompiledZMask mask = null;
@Override
public String accountForYourself()
{
return "Modifies experience gained: " + operationFormula;
}
public int translateAmount(int amount, String val)
{
if(amount<0)
amount=-amount;
if(val.endsWith("%"))
return (int)Math.round(CMath.mul(amount,CMath.div(CMath.s_int(val.substring(0,val.length()-1)),100)));
return CMath.s_int(val);
}
public String translateNumber(String val)
{
if(val.endsWith("%"))
return "( @x1 * (" + val.substring(0,val.length()-1) + " / 100) )";
return Integer.toString(CMath.s_int(val));
}
@Override
public void setMiscText(String newText)
{
super.setMiscText(newText);
operation = null;
mask=null;
selfXP=false;
String s=newText.trim();
int x=s.indexOf(';');
if(x>=0)
{
mask=CMLib.masking().getPreCompiledMask(s.substring(x+1).trim());
s=s.substring(0,x).trim();
}
x=s.indexOf("SELF");
if(x>=0)
{
selfXP=true;
s=s.substring(0,x)+s.substring(x+4);
}
operationFormula="Amount "+s;
if(s.startsWith("="))
operation = CMath.compileMathExpression(translateNumber(s.substring(1)).trim());
else
if(s.startsWith("+"))
operation = CMath.compileMathExpression("@x1 + "+translateNumber(s.substring(1)).trim());
else
if(s.startsWith("-"))
operation = CMath.compileMathExpression("@x1 - "+translateNumber(s.substring(1)).trim());
else
if(s.startsWith("*"))
operation = CMath.compileMathExpression("@x1 * "+translateNumber(s.substring(1)).trim());
else
if(s.startsWith("/"))
operation = CMath.compileMathExpression("@x1 / "+translateNumber(s.substring(1)).trim());
else
if(s.startsWith("(")&&(s.endsWith(")")))
{
operationFormula="Amount ="+s;
operation = CMath.compileMathExpression(s);
}
else
operation = CMath.compileMathExpression(translateNumber(s.trim()));
operationFormula=CMStrings.replaceAll(operationFormula, "@x1", "Amount");
}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(operation == null)
setMiscText(text());
if((msg.sourceMinor()==CMMsg.TYP_EXPCHANGE)
&&(operation != null)
&&((((msg.target()==affected)||(selfXP && (msg.source()==affected))) &&(affected instanceof MOB))
||((affected instanceof Item)
&&(msg.source()==((Item)affected).owner())
&&(!((Item)affected).amWearingAt(Wearable.IN_INVENTORY)))
||(affected instanceof Room)
||(affected instanceof Area)))
{
if(mask!=null)
{
if(affected instanceof Item)
{
if((msg.target()==null)||(!(msg.target() instanceof MOB))||(!CMLib.masking().maskCheck(mask,msg.target(),true)))
return super.okMessage(myHost,msg);
}
else
if(!CMLib.masking().maskCheck(mask,msg.source(),true))
return super.okMessage(myHost,msg);
}
msg.setValue((int)Math.round(CMath.parseMathExpression(operation, new double[]{msg.value()}, 0.0)));
}
return super.okMessage(myHost,msg);
}
}
|
com/planet_ink/coffee_mud/Abilities/Properties/Prop_ModExperience.java
|
package com.planet_ink.coffee_mud.Abilities.Properties;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.MaskingLibrary;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2004-2016 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Prop_ModExperience extends Property
{
@Override
public String ID()
{
return "Prop_ModExperience";
}
@Override
public String name()
{
return "Modifying Experience Gained";
}
@Override
protected int canAffectCode()
{
return Ability.CAN_MOBS | Ability.CAN_ITEMS | Ability.CAN_AREAS | Ability.CAN_ROOMS;
}
protected String operationFormula = "";
protected boolean selfXP = false;
protected LinkedList<CMath.CompiledOperation> operation = null;
protected MaskingLibrary.CompiledZMask mask = null;
@Override
public String accountForYourself()
{
return "Modifies experience gained: " + operationFormula;
}
public int translateAmount(int amount, String val)
{
if(amount<0)
amount=-amount;
if(val.endsWith("%"))
return (int)Math.round(CMath.mul(amount,CMath.div(CMath.s_int(val.substring(0,val.length()-1)),100)));
return CMath.s_int(val);
}
public String translateNumber(String val)
{
if(val.endsWith("%"))
return "( @x1 * (" + val.substring(0,val.length()-1) + " / 100) )";
return Integer.toString(CMath.s_int(val));
}
@Override
public void setMiscText(String newText)
{
super.setMiscText(newText);
operation = null;
mask=null;
selfXP=false;
String s=newText.trim();
int x=s.indexOf(';');
if(x>=0)
{
mask=CMLib.masking().getPreCompiledMask(s.substring(x+1).trim());
s=s.substring(0,x).trim();
}
x=s.indexOf("SELF");
if(x>=0)
{
selfXP=true;
s=s.substring(0,x)+s.substring(x+4);
}
operationFormula="Amount "+s;
if(s.startsWith("="))
operation = CMath.compileMathExpression(translateNumber(s.substring(1)).trim());
else
if(s.startsWith("+"))
operation = CMath.compileMathExpression("@x1 + "+translateNumber(s.substring(1)).trim());
else
if(s.startsWith("-"))
operation = CMath.compileMathExpression("@x1 - "+translateNumber(s.substring(1)).trim());
else
if(s.startsWith("*"))
operation = CMath.compileMathExpression("@x1 * "+translateNumber(s.substring(1)).trim());
else
if(s.startsWith("/"))
operation = CMath.compileMathExpression("@x1 / "+translateNumber(s.substring(1)).trim());
else
if(s.startsWith("(")&&(s.endsWith(")")))
{
operationFormula="Amount ="+s;
operation = CMath.compileMathExpression(s);
}
else
operation = CMath.compileMathExpression(translateNumber(s.trim()));
operationFormula=CMStrings.replaceAll(operationFormula, "@x1", "Amount");
}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(operation == null)
setMiscText(text());
if((msg.sourceMinor()==CMMsg.TYP_EXPCHANGE)
&&(operation != null)
&&((((msg.target()==affected)||(selfXP && (msg.source()==affected))) &&(affected instanceof MOB))
||((affected instanceof Item)
&&(msg.source()==((Item)affected).owner())
&&(!((Item)affected).amWearingAt(Wearable.IN_INVENTORY)))
||(affected instanceof Room)
||(affected instanceof Area)))
{
if(mask!=null)
{
if(affected instanceof Item)
{
if((msg.target()==null)||(!(msg.target() instanceof MOB))||(!CMLib.masking().maskCheck(mask,msg.target(),true)))
return super.okMessage(myHost,msg);
}
else
if(!CMLib.masking().maskCheck(mask,msg.source(),true))
return super.okMessage(myHost,msg);
}
msg.setValue((int)Math.round(CMath.parseMathExpression(operation, new double[]{msg.value()}, 0.0)));
}
return super.okMessage(myHost,msg);
}
}
|
git-svn-id: svn://192.168.1.10/public/CoffeeMud@14176 0d6f1817-ed0e-0410-87c9-987e46238f29
|
com/planet_ink/coffee_mud/Abilities/Properties/Prop_ModExperience.java
| ||
Java
|
apache-2.0
|
b396c16c0300857ddbf8064e787867843be1be9e
| 0
|
joshmgrant/selenium,titusfortner/selenium,valfirst/selenium,HtmlUnit/selenium,joshmgrant/selenium,Dude-X/selenium,HtmlUnit/selenium,joshmgrant/selenium,Dude-X/selenium,asolntsev/selenium,HtmlUnit/selenium,valfirst/selenium,SeleniumHQ/selenium,joshmgrant/selenium,valfirst/selenium,asolntsev/selenium,asolntsev/selenium,HtmlUnit/selenium,Ardesco/selenium,titusfortner/selenium,HtmlUnit/selenium,joshmgrant/selenium,asolntsev/selenium,titusfortner/selenium,asolntsev/selenium,Ardesco/selenium,titusfortner/selenium,Dude-X/selenium,SeleniumHQ/selenium,Dude-X/selenium,Dude-X/selenium,titusfortner/selenium,titusfortner/selenium,Ardesco/selenium,asolntsev/selenium,titusfortner/selenium,SeleniumHQ/selenium,HtmlUnit/selenium,valfirst/selenium,asolntsev/selenium,joshmgrant/selenium,titusfortner/selenium,SeleniumHQ/selenium,HtmlUnit/selenium,Dude-X/selenium,valfirst/selenium,asolntsev/selenium,valfirst/selenium,Dude-X/selenium,joshmgrant/selenium,asolntsev/selenium,SeleniumHQ/selenium,Ardesco/selenium,valfirst/selenium,titusfortner/selenium,HtmlUnit/selenium,SeleniumHQ/selenium,valfirst/selenium,SeleniumHQ/selenium,Dude-X/selenium,SeleniumHQ/selenium,HtmlUnit/selenium,SeleniumHQ/selenium,joshmgrant/selenium,HtmlUnit/selenium,Ardesco/selenium,Dude-X/selenium,titusfortner/selenium,titusfortner/selenium,Ardesco/selenium,valfirst/selenium,Ardesco/selenium,valfirst/selenium,Ardesco/selenium,SeleniumHQ/selenium,Ardesco/selenium,valfirst/selenium,joshmgrant/selenium,SeleniumHQ/selenium,joshmgrant/selenium,joshmgrant/selenium
|
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.tools.javadoc;
import org.openqa.selenium.tools.zip.StableZipEntry;
import javax.tools.DocumentationTool;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class JavadocJarMaker {
public static void main(String[] args) throws IOException {
Set<Path> sourceJars = new HashSet<>();
Path out = null;
Set<Path> classpath = new HashSet<>();
for (int i = 0; i < args.length; i++) {
String flag = args[i];
String next = args[++i];
switch (flag) {
case "--cp":
classpath.add(Paths.get(next));
break;
case "--in":
sourceJars.add(Paths.get(next));
break;
case "--out":
out = Paths.get(next);
break;
}
}
if (sourceJars.isEmpty()) {
throw new IllegalArgumentException("At least one input just must be specified via the --in flag");
}
if (out == null) {
throw new IllegalArgumentException("The output jar location must be specified via the --out flag");
}
Set<Path> tempDirs = new HashSet<>();
Path dir = Files.createTempDirectory("javadocs");
tempDirs.add(dir);
try {
DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
try (StandardJavaFileManager fileManager = tool.getStandardFileManager(null, Locale.getDefault(), StandardCharsets.UTF_8)) {
fileManager.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, List.of(dir.toFile()));
fileManager.setLocation(StandardLocation.CLASS_PATH, classpath.stream().map(Path::toFile).collect(Collectors.toSet()));
Set<JavaFileObject> sources = new HashSet<>();
Set<String> topLevelPackages = new HashSet<>();
Path unpackTo = Files.createTempDirectory("unpacked-sources");
tempDirs.add(unpackTo);
Set<String> fileNames = new HashSet<>();
readSourceFiles(unpackTo, fileManager, sourceJars, sources, topLevelPackages, fileNames);
// True if we're just exporting a set of modules
if (sources.isEmpty()) {
try (OutputStream os = Files.newOutputStream(out);
ZipOutputStream zos = new ZipOutputStream(os)) {
// It's enough to just create the thing
}
return;
}
List<String> options = new ArrayList<>();
if (!classpath.isEmpty()) {
options.add("-cp");
options.add(classpath.stream().map(String::valueOf).collect(Collectors.joining(File.pathSeparator)));
}
options.addAll(List.of("-html5", "-notimestamp", "-use", "-quiet", "-Xdoclint:-missing", "-encoding", "UTF8"));
Path outputTo = Files.createTempDirectory("output-dir");
tempDirs.add(outputTo);
options.addAll(List.of("-d", outputTo.toAbsolutePath().toString()));
sources.forEach(obj -> options.add(obj.getName()));
Writer writer = new StringWriter();
DocumentationTool.DocumentationTask task = tool.getTask(writer, fileManager, null, null, options, sources);
Boolean result = task.call();
if (result == null || !result) {
System.err.println("javadoc " + String.join(" ", options));
System.err.println(writer);
return;
}
try (OutputStream os = Files.newOutputStream(out);
ZipOutputStream zos = new ZipOutputStream(os);
Stream<Path> walk = Files.walk(outputTo)) {
walk.sorted(Comparator.naturalOrder())
.forEachOrdered(path -> {
if (path.equals(outputTo)) {
return;
}
try {
if (Files.isDirectory(path)) {
String name = outputTo.relativize(path) + "/";
ZipEntry entry = new StableZipEntry(name);
zos.putNextEntry(entry);
zos.closeEntry();
} else {
String name = outputTo.relativize(path).toString();
ZipEntry entry = new StableZipEntry(name);
zos.putNextEntry(entry);
try (InputStream is = Files.newInputStream(path)) {
is.transferTo(zos);
}
zos.closeEntry();
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
}
} finally {
tempDirs.forEach(d -> {
try (Stream<Path> walk = Files.walk(d)) {
walk.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
}
private static void readSourceFiles(
Path unpackTo,
StandardJavaFileManager fileManager,
Set<Path> sourceJars,
Set<JavaFileObject> sources,
Set<String> topLevelPackages,
Set<String> fileNames) throws IOException {
for (Path jar : sourceJars) {
if (!Files.exists(jar)) {
continue;
}
try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(jar))) {
for (ZipEntry entry = zis.getNextEntry(); entry != null; entry = zis.getNextEntry()) {
String name = entry.getName();
if (!name.endsWith(".java")) {
continue;
}
Path target = unpackTo.resolve(name).normalize();
if (!target.startsWith(unpackTo)) {
throw new IOException("Attempt to write out of working directory");
}
Files.createDirectories(target.getParent());
try (OutputStream out = Files.newOutputStream(target)) {
zis.transferTo(out);
}
fileManager.getJavaFileObjects(target).forEach(sources::add);
String[] segments = name.split("/");
if (segments.length > 0 && !"META-INF".equals(segments[0])) {
topLevelPackages.add(segments[0]);
}
fileNames.add(name);
}
}
}
}
}
|
java/client/src/org/openqa/selenium/tools/javadoc/JavadocJarMaker.java
|
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.tools.javadoc;
import org.openqa.selenium.tools.zip.StableZipEntry;
import javax.tools.DocumentationTool;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class JavadocJarMaker {
public static void main(String[] args) throws IOException {
Set<Path> sourceJars = new HashSet<>();
Path out = null;
Set<Path> classpath = new HashSet<>();
for (int i = 0; i < args.length; i++) {
String flag = args[i];
String next = args[++i];
switch (flag) {
case "--cp":
classpath.add(Paths.get(next));
break;
case "--in":
sourceJars.add(Paths.get(next));
break;
case "--out":
out = Paths.get(next);
break;
}
}
if (sourceJars.isEmpty()) {
throw new IllegalArgumentException("At least one input just must be specified via the --in flag");
}
if (out == null) {
throw new IllegalArgumentException("The output jar location must be specified via the --out flag");
}
Set<Path> tempDirs = new HashSet<>();
Path dir = Files.createTempDirectory("javadocs");
tempDirs.add(dir);
try {
DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
try (StandardJavaFileManager fileManager = tool.getStandardFileManager(null, Locale.getDefault(), StandardCharsets.UTF_8)) {
fileManager.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, List.of(dir.toFile()));
fileManager.setLocation(StandardLocation.CLASS_PATH, classpath.stream().map(Path::toFile).collect(Collectors.toSet()));
Set<JavaFileObject> sources = new HashSet<>();
Set<String> topLevelPackages = new HashSet<>();
Path unpackTo = Files.createTempDirectory("unpacked-sources");
tempDirs.add(unpackTo);
Set<String> fileNames = new HashSet<>();
readSourceFiles(unpackTo, fileManager, sourceJars, sources, topLevelPackages, fileNames);
// True if we're just exporting a set of modules
if (sources.isEmpty()) {
try (OutputStream os = Files.newOutputStream(out);
ZipOutputStream zos = new ZipOutputStream(os)) {
// It's enough to just create the thing
}
return;
}
List<String> options = new ArrayList<>();
if (!classpath.isEmpty()) {
options.add("-cp");
options.add(classpath.stream().map(String::valueOf).collect(Collectors.joining(File.pathSeparator)));
}
options.addAll(List.of("-html5", "-notimestamp", "-use", "-quiet", "-Xdoclint:-missing", "-encoding", "UTF8"));
Path outputTo = Files.createTempDirectory("output-dir");
tempDirs.add(outputTo);
options.addAll(List.of("-d", outputTo.toAbsolutePath().toString()));
sources.forEach(obj -> options.add(obj.getName()));
Writer writer = new StringWriter();
DocumentationTool.DocumentationTask task = tool.getTask(writer, fileManager, null, null, options, sources);
Boolean result = task.call();
if (result == null || !result) {
System.err.println("javadoc " + String.join(" ", options));
System.err.println(writer);
return;
}
try (OutputStream os = Files.newOutputStream(out);
ZipOutputStream zos = new ZipOutputStream(os)) {
Files.walk(outputTo)
.sorted(Comparator.naturalOrder())
.forEachOrdered(path -> {
if (path.equals(outputTo)) {
return;
}
try {
if (Files.isDirectory(path)) {
String name = outputTo.relativize(path) + "/";
ZipEntry entry = new StableZipEntry(name);
zos.putNextEntry(entry);
zos.closeEntry();
} else {
String name = outputTo.relativize(path).toString();
ZipEntry entry = new StableZipEntry(name);
zos.putNextEntry(entry);
try (InputStream is = Files.newInputStream(path)) {
is.transferTo(zos);
}
zos.closeEntry();
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
}
} finally {
tempDirs.forEach(d -> {
try {
Files.walk(d)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
}
private static void readSourceFiles(
Path unpackTo,
StandardJavaFileManager fileManager,
Set<Path> sourceJars,
Set<JavaFileObject> sources,
Set<String> topLevelPackages,
Set<String> fileNames) throws IOException {
for (Path jar : sourceJars) {
if (!Files.exists(jar)) {
continue;
}
try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(jar))) {
for (ZipEntry entry = zis.getNextEntry(); entry != null; entry = zis.getNextEntry()) {
String name = entry.getName();
if (!name.endsWith(".java")) {
continue;
}
Path target = unpackTo.resolve(name).normalize();
if (!target.startsWith(unpackTo)) {
throw new IOException("Attempt to write out of working directory");
}
Files.createDirectories(target.getParent());
try (OutputStream out = Files.newOutputStream(target)) {
zis.transferTo(out);
}
fileManager.getJavaFileObjects(target).forEach(sources::add);
String[] segments = name.split("/");
if (segments.length > 0 && !"META-INF".equals(segments[0])) {
topLevelPackages.add(segments[0]);
}
fileNames.add(name);
}
}
}
}
}
|
[java] A bit more safe way to use File.walk, the created Stream should be closed
|
java/client/src/org/openqa/selenium/tools/javadoc/JavadocJarMaker.java
|
[java] A bit more safe way to use File.walk, the created Stream should be closed
|
|
Java
|
apache-2.0
|
bad6cf992aacdca24063011417e11f9ecd0cbfb3
| 0
|
KernelHaven/KernelHaven,KernelHaven/KernelHaven
|
package net.ssehub.kernel_haven.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Set;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests the {@link ZipArchive} class.
*
* @author Adam
*/
public class ZipArchiveTest {
private static final File TESTDATA = new File("testdata/zipArchive");
/**
* In case the test file archive.zip is destroyed, replace it with archive_original.zip.
*
* @throws IOException unwanted.
*/
@AfterClass
public static void cleanUp() throws IOException {
Util.copyFile(new File(TESTDATA, "archive_original.zip"), new File(TESTDATA, "archive.zip"));
}
/**
* Tests whether a new zip archive is correctly created.
*
* @throws IOException unwanted.
*/
@Test
public void testCreation() throws IOException {
File zipFile = new File(TESTDATA, "testCreation.zip");
zipFile.deleteOnExit();
if (zipFile.exists()) {
zipFile.delete();
}
Assert.assertFalse(zipFile.exists());
ZipArchive archive = new ZipArchive(zipFile);
Assert.assertTrue(zipFile.exists());
archive.close();
Assert.assertTrue(zipFile.exists());
}
/**
* Tests whether a zip file with an invalid path is not created.
*
* @throws IOException wanted.
*/
@Test(expected = IOException.class)
public void testInvalidCreation() throws IOException {
File zipFile = TESTDATA; // this is a directory
Assert.assertTrue(zipFile.isDirectory());
new ZipArchive(zipFile).close();
}
/**
* Tests whether the containsFile() method works on an existing archive.
*
* @throws IOException unwanted.
*/
@Test
public void testContainsFile() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
Assert.assertTrue(archive.containsFile(new File("test.txt")));
Assert.assertTrue(archive.containsFile(new File("dir/test.txt")));
Assert.assertFalse(archive.containsFile(new File("doesntExist.txt")));
Assert.assertFalse(archive.containsFile(new File("doesntExist/doesnExist.txt")));
Assert.assertFalse(archive.containsFile(new File("dir/doesntExist.txt")));
archive.close();
}
/**
* Tests whether containsFile() correctly works on directories in the archive.
*
* @throws IOException unwanted.
*/
@Test
public void testContainsFileOnDirectory() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
Assert.assertFalse(archive.containsFile(new File("dir")));
Assert.assertFalse(archive.containsFile(new File("dir/")));
archive.close();
}
/**
* Tests whether the readFile() method works.
*
* @throws IOException unwanted.
*/
@Test
public void testReadFile() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
String read = archive.readFile(new File("test.txt"));
Assert.assertEquals("Hello World!\n", read);
archive.close();
}
/**
* Tests whether the readFile() method works correctly on not existing files.
*
* @throws FileNotFoundException wanted.
* @throws IOException unwanted.
*/
@Test(expected = FileNotFoundException.class)
public void testReadNotExistingFile() throws IOException, FileNotFoundException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
try {
archive.readFile(new File("doesntExist.txt"));
} finally {
archive.close();
}
}
/**
* Tests whether the getSize() method works correctly.
*
* @throws IOException unwanted.
*/
@Test
public void testGetSize() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
Assert.assertEquals(13, archive.getSize(new File("test.txt")));
archive.close();
}
/**
* Tests whether the getSize() method works correctly on not existinf files.
*
* @throws FileNotFoundException wanted.
* @throws IOException unwanted.
*/
@Test(expected = FileNotFoundException.class)
public void testGetSizeNotExisting() throws FileNotFoundException, IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
try {
archive.getSize(new File("doesntExist.txt"));
} finally {
archive.close();
}
}
/**
* Tests the write and delete methods on an existing archive.
*
* @throws IOException unwanted.
*/
@Test
public void testWriteAndDeleteFile() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
File toWrite = new File("testWrite.txt");
Assert.assertFalse(archive.containsFile(toWrite));
String content = "This is a test text\n";
archive.writeFile(toWrite, content);
Assert.assertTrue(archive.containsFile(toWrite));
Assert.assertEquals(archive.readFile(toWrite), content);
archive.deleteFile(toWrite);
Assert.assertFalse(archive.containsFile(toWrite));
archive.close();
}
/**
* Tests the delete method on a not existing file.
*
* @throws FileNotFoundException wanted.
* @throws IOException unwanted.
*/
@Test(expected = FileNotFoundException.class)
public void testDeleteNonExisting() throws FileNotFoundException, IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
Assert.assertFalse(archive.containsFile(new File("doesntExist.txt")));
try {
archive.deleteFile(new File("doesntExist.txt"));
} finally {
archive.close();
}
}
/**
* Tests whether overwriting files works correctly.
*
* @throws IOException unwanted.
*/
@Test
public void testOverwriteFile() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
File toWrite = new File("testOverwrite.txt");
Assert.assertFalse(archive.containsFile(toWrite));
String content1 = "This is a test text\n";
archive.writeFile(toWrite, content1);
Assert.assertTrue(archive.containsFile(toWrite));
Assert.assertEquals(archive.readFile(toWrite), content1);
String content2 = "This is another test text\n";
archive.writeFile(toWrite, content2);
Assert.assertTrue(archive.containsFile(toWrite));
Assert.assertEquals(archive.readFile(toWrite), content2);
archive.deleteFile(toWrite);
Assert.assertFalse(archive.containsFile(toWrite));
archive.close();
}
/**
* Tests whether the copyFileToArchive() method works correctly.
*
* @throws IOException unwanted.
*/
@Test
public void testCopyFileToArchive() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
File insideFile = new File("testCopy.txt");
File outsideFile = new File(TESTDATA, "testfile.txt");
Assert.assertTrue(outsideFile.exists());
Assert.assertFalse(archive.containsFile(insideFile));
archive.copyFileToArchive(insideFile, outsideFile);
Assert.assertTrue(outsideFile.exists());
Assert.assertTrue(archive.containsFile(insideFile));
FileInputStream in = new FileInputStream(outsideFile);
Assert.assertEquals(Util.readStream(in), archive.readFile(insideFile));
in.close();
archive.deleteFile(insideFile);
Assert.assertFalse(archive.containsFile(insideFile));
archive.close();
}
/**
* Tests whether the readFile() method works correctly.
*
* @throws IOException unwanted.
*/
@Test
public void testExtract() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
File insideFile = new File("test.txt");
File outsideFile = new File(TESTDATA, "testExtract.txt");
Assert.assertFalse(outsideFile.exists());
Assert.assertTrue(archive.containsFile(insideFile));
archive.extract(insideFile, outsideFile);
Assert.assertTrue(outsideFile.exists());
Assert.assertTrue(archive.containsFile(insideFile));
FileInputStream in = new FileInputStream(outsideFile);
Assert.assertEquals(archive.readFile(insideFile), Util.readStream(in));
in.close();
outsideFile.delete();
Assert.assertFalse(outsideFile.exists());
archive.close();
}
/**
* Tests whether the listFiles() method works.
*
* @throws IOException unwanted.
*/
@Test
public void testListFiles() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
Set<File> files = archive.listFiles();
Assert.assertEquals(2, files.size());
Assert.assertTrue(files.contains(new File("test.txt")));
Assert.assertTrue(files.contains(new File("dir/test.txt")));
archive.close();
}
}
|
test/net/ssehub/kernel_haven/util/ZipArchiveTest.java
|
package net.ssehub.kernel_haven.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests the {@link ZipArchive} class. If the test archive "archive.zip" is destroyed, replace it with
* "archive_original.zip".
*
* @author Adam
*/
public class ZipArchiveTest {
private static final File TESTDATA = new File("testdata/zipArchive");
/**
* Tests whether a new zip archive is correctly created.
*
* @throws IOException unwanted.
*/
@Test
public void testCreation() throws IOException {
File zipFile = new File(TESTDATA, "testCreation.zip");
zipFile.deleteOnExit();
if (zipFile.exists()) {
zipFile.delete();
}
Assert.assertFalse(zipFile.exists());
ZipArchive archive = new ZipArchive(zipFile);
Assert.assertTrue(zipFile.exists());
archive.close();
Assert.assertTrue(zipFile.exists());
}
/**
* Tests whether a zip file with an invalid path is not created.
*
* @throws IOException wanted.
*/
@Test(expected = IOException.class)
public void testInvalidCreation() throws IOException {
File zipFile = TESTDATA; // this is a directory
Assert.assertTrue(zipFile.isDirectory());
new ZipArchive(zipFile).close();
}
/**
* Tests whether the containsFile() method works on an existing archive.
*
* @throws IOException unwanted.
*/
@Test
public void testContainsFile() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
Assert.assertTrue(archive.containsFile(new File("test.txt")));
Assert.assertTrue(archive.containsFile(new File("dir/test.txt")));
Assert.assertFalse(archive.containsFile(new File("doesntExist.txt")));
Assert.assertFalse(archive.containsFile(new File("doesntExist/doesnExist.txt")));
Assert.assertFalse(archive.containsFile(new File("dir/doesntExist.txt")));
archive.close();
}
/**
* Tests whether containsFile() correctly works on directories in the archive.
*
* @throws IOException unwanted.
*/
@Test
public void testContainsFileOnDirectory() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
Assert.assertFalse(archive.containsFile(new File("dir")));
Assert.assertFalse(archive.containsFile(new File("dir/")));
archive.close();
}
/**
* Tests whether the readFile() method works.
*
* @throws IOException unwanted.
*/
@Test
public void testReadFile() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
String read = archive.readFile(new File("test.txt"));
Assert.assertEquals("Hello World!\n", read);
archive.close();
}
/**
* Tests whether the readFile() method works correctly on not existing files.
*
* @throws FileNotFoundException wanted.
* @throws IOException unwanted.
*/
@Test(expected = FileNotFoundException.class)
public void testReadNotExistingFile() throws IOException, FileNotFoundException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
try {
archive.readFile(new File("doesntExist.txt"));
} finally {
archive.close();
}
}
/**
* Tests whether the getSize() method works correctly.
*
* @throws IOException unwanted.
*/
@Test
public void testGetSize() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
Assert.assertEquals(13, archive.getSize(new File("test.txt")));
archive.close();
}
/**
* Tests whether the getSize() method works correctly on not existinf files.
*
* @throws FileNotFoundException wanted.
* @throws IOException unwanted.
*/
@Test(expected = FileNotFoundException.class)
public void testGetSizeNotExisting() throws FileNotFoundException, IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
try {
archive.getSize(new File("doesntExist.txt"));
} finally {
archive.close();
}
}
/**
* Tests the write and delete methods on an existing archive.
*
* @throws IOException unwanted.
*/
@Test
public void testWriteAndDeleteFile() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
File toWrite = new File("testWrite.txt");
Assert.assertFalse(archive.containsFile(toWrite));
String content = "This is a test text\n";
archive.writeFile(toWrite, content);
Assert.assertTrue(archive.containsFile(toWrite));
Assert.assertEquals(archive.readFile(toWrite), content);
archive.deleteFile(toWrite);
Assert.assertFalse(archive.containsFile(toWrite));
archive.close();
}
/**
* Tests the delete method on a not existing file.
*
* @throws FileNotFoundException wanted.
* @throws IOException unwanted.
*/
@Test(expected = FileNotFoundException.class)
public void testDeleteNonExisting() throws FileNotFoundException, IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
Assert.assertFalse(archive.containsFile(new File("doesntExist.txt")));
try {
archive.deleteFile(new File("doesntExist.txt"));
} finally {
archive.close();
}
}
/**
* Tests whether overwriting files works correctly.
*
* @throws IOException unwanted.
*/
@Test
public void testOverwriteFile() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
File toWrite = new File("testOverwrite.txt");
Assert.assertFalse(archive.containsFile(toWrite));
String content1 = "This is a test text\n";
archive.writeFile(toWrite, content1);
Assert.assertTrue(archive.containsFile(toWrite));
Assert.assertEquals(archive.readFile(toWrite), content1);
String content2 = "This is another test text\n";
archive.writeFile(toWrite, content2);
Assert.assertTrue(archive.containsFile(toWrite));
Assert.assertEquals(archive.readFile(toWrite), content2);
archive.deleteFile(toWrite);
Assert.assertFalse(archive.containsFile(toWrite));
archive.close();
}
/**
* Tests whether the copyFileToArchive() method works correctly.
*
* @throws IOException unwanted.
*/
@Test
public void testCopyFileToArchive() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
File insideFile = new File("testCopy.txt");
File outsideFile = new File(TESTDATA, "testfile.txt");
Assert.assertTrue(outsideFile.exists());
Assert.assertFalse(archive.containsFile(insideFile));
archive.copyFileToArchive(insideFile, outsideFile);
Assert.assertTrue(outsideFile.exists());
Assert.assertTrue(archive.containsFile(insideFile));
FileInputStream in = new FileInputStream(outsideFile);
Assert.assertEquals(Util.readStream(in), archive.readFile(insideFile));
in.close();
archive.deleteFile(insideFile);
Assert.assertFalse(archive.containsFile(insideFile));
archive.close();
}
/**
* Tests whether the readFile() method works correctly.
*
* @throws IOException unwanted.
*/
@Test
public void testExtract() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
File insideFile = new File("test.txt");
File outsideFile = new File(TESTDATA, "testExtract.txt");
Assert.assertFalse(outsideFile.exists());
Assert.assertTrue(archive.containsFile(insideFile));
archive.extract(insideFile, outsideFile);
Assert.assertTrue(outsideFile.exists());
Assert.assertTrue(archive.containsFile(insideFile));
FileInputStream in = new FileInputStream(outsideFile);
Assert.assertEquals(archive.readFile(insideFile), Util.readStream(in));
in.close();
outsideFile.delete();
Assert.assertFalse(outsideFile.exists());
archive.close();
}
/**
* Tests whether the listFiles() method works.
*
* @throws IOException unwanted.
*/
@Test
public void testListFiles() throws IOException {
File zipFile = new File(TESTDATA, "archive.zip");
ZipArchive archive = new ZipArchive(zipFile);
Set<File> files = archive.listFiles();
Assert.assertEquals(2, files.size());
Assert.assertTrue(files.contains(new File("test.txt")));
Assert.assertTrue(files.contains(new File("dir/test.txt")));
archive.close();
}
}
|
Clean up properly in ZipArchiveTest
|
test/net/ssehub/kernel_haven/util/ZipArchiveTest.java
|
Clean up properly in ZipArchiveTest
|
|
Java
|
apache-2.0
|
6a7aab35a7e51dbd0ce4233b319c688736ea50f0
| 0
|
JessYanCoding/MVPArms
|
/**
* Copyright 2017 JessYan
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jess.arms.integration;
import android.app.Activity;
import android.app.Application;
import android.app.Dialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.view.View;
import com.jess.arms.base.delegate.AppLifecycles;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import timber.log.Timber;
/**
* ================================================
* 用于管理所有 {@link Activity},和在前台的 {@link Activity}
* 可以通过直接持有 {@link AppManager} 对象执行对应方法
* 也可以通过 {@link #post(Message)} ,远程遥控执行对应方法,用法和 EventBus 类似
*
* @see <a href="https://github.com/JessYanCoding/MVPArms/wiki#3.11">AppManager wiki 官方文档</a>
* Created by JessYan on 14/12/2016 13:50
* <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
@Singleton
public final class AppManager {
protected final String TAG = this.getClass().getSimpleName();
public static final String APPMANAGER_MESSAGE = "appmanager_message";
//true 为不需要加入到 Activity 容器进行统一管理,默认为 false
public static final String IS_NOT_ADD_ACTIVITY_LIST = "is_not_add_activity_list";
public static final int START_ACTIVITY = 5000;
public static final int SHOW_SNACKBAR = 5001;
public static final int KILL_ALL = 5002;
public static final int APP_EXIT = 5003;
private Application mApplication;
//管理所有存活的 Activity, 容器中的顺序仅仅是 Activity 的创建顺序, 并不能保证和 Activity 任务栈顺序一致
public List<Activity> mActivityList;
//当前在前台的 Activity
private Activity mCurrentActivity;
//提供给外部扩展 AppManager 的 onReceive 方法
private HandleListener mHandleListener;
@Inject
public AppManager(Application application) {
this.mApplication = application;
EventBus.getDefault().register(this);
}
/**
* 通过 {@link EventBus#post(Object)} 事件, 远程遥控执行对应方法
* 可通过 {@link #setHandleListener(HandleListener)}, 让外部可扩展新的事件
*/
@Subscriber(tag = APPMANAGER_MESSAGE, mode = ThreadMode.MAIN)
public void onReceive(Message message) {
switch (message.what) {
case START_ACTIVITY:
if (message.obj == null)
break;
dispatchStart(message);
break;
case SHOW_SNACKBAR:
if (message.obj == null)
break;
showSnackbar((String) message.obj, message.arg1 == 0 ? false : true);
break;
case KILL_ALL:
killAll();
break;
case APP_EXIT:
appExit();
break;
default:
Timber.tag(TAG).w("The message.what not match");
break;
}
if (mHandleListener != null) {
mHandleListener.handleMessage(this, message);
}
}
private void dispatchStart(Message message) {
if (message.obj instanceof Intent)
startActivity((Intent) message.obj);
else if (message.obj instanceof Class)
startActivity((Class) message.obj);
}
public HandleListener getHandleListener() {
return mHandleListener;
}
/**
* 提供给外部扩展 {@link AppManager} 的 {@link #onReceive} 方法(远程遥控 {@link AppManager} 的功能)
* 建议在 {@link ConfigModule#injectAppLifecycle(Context, List)} 中
* 通过 {@link AppLifecycles#onCreate(Application)} 在 App 初始化时,使用此方法传入自定义的 {@link HandleListener}
*
* @param handleListener
*/
public void setHandleListener(HandleListener handleListener) {
this.mHandleListener = handleListener;
}
/**
* 通过此方法远程遥控 {@link AppManager} ,使 {@link #onReceive(Message)} 执行对应方法
*
* @param msg
*/
public static void post(Message msg) {
EventBus.getDefault().post(msg, APPMANAGER_MESSAGE);
}
/**
* 让在前台的 {@link Activity},使用 {@link Snackbar} 显示文本内容
*
* @param message
* @param isLong
*/
public void showSnackbar(String message, boolean isLong) {
if (getCurrentActivity() == null) {
Timber.tag(TAG).w("mCurrentActivity == null when showSnackbar(String,boolean)");
return;
}
View view = getCurrentActivity().getWindow().getDecorView().findViewById(android.R.id.content);
Snackbar.make(view, message, isLong ? Snackbar.LENGTH_LONG : Snackbar.LENGTH_SHORT).show();
}
/**
* 让在栈顶的 {@link Activity} ,打开指定的 {@link Activity}
*
* @param intent
*/
public void startActivity(Intent intent) {
if (getTopActivity() == null) {
Timber.tag(TAG).w("mCurrentActivity == null when startActivity(Intent)");
//如果没有前台的activity就使用new_task模式启动activity
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mApplication.startActivity(intent);
return;
}
getTopActivity().startActivity(intent);
}
/**
* 让在栈顶的 {@link Activity} ,打开指定的 {@link Activity}
*
* @param activityClass
*/
public void startActivity(Class activityClass) {
startActivity(new Intent(mApplication, activityClass));
}
/**
* 释放资源
*/
public void release() {
EventBus.getDefault().unregister(this);
mActivityList.clear();
mHandleListener = null;
mActivityList = null;
mCurrentActivity = null;
mApplication = null;
}
/**
* 将在前台的 {@link Activity} 赋值给 {@code currentActivity}, 注意此方法是在 {@link Activity#onResume} 方法执行时将栈顶的 {@link Activity} 赋值给 {@code currentActivity}
* 所以在栈顶的 {@link Activity} 执行 {@link Activity#onCreate} 方法时使用 {@link #getCurrentActivity()} 获取的就不是当前栈顶的 {@link Activity}, 可能是上一个 {@link Activity}
* 如果在 App 启动第一个 {@link Activity} 执行 {@link Activity#onCreate} 方法时使用 {@link #getCurrentActivity()} 则会出现返回为 {@code null} 的情况
* 想避免这种情况请使用 {@link #getTopActivity()}
*
* @param currentActivity
*/
public void setCurrentActivity(Activity currentActivity) {
this.mCurrentActivity = currentActivity;
}
/**
* 获取在前台的 {@link Activity} (保证获取到的 {@link Activity} 正处于可见状态, 即未调用 {@link Activity#onStop()}), 获取的 {@link Activity} 存续时间
* 是在 {@link Activity#onStop()} 之前, 所以如果当此 {@link Activity} 调用 {@link Activity#onStop()} 方法之后, 没有其他的 {@link Activity} 回到前台(用户返回桌面或者打开了其他 App 会出现此状况)
* 这时调用 {@link #getCurrentActivity()} 有可能返回 {@code null}, 所以请注意使用场景和 {@link #getTopActivity()} 不一样
* <p>
* Example usage:
* 使用场景比较适合, 只需要在可见状态的 {@link Activity} 上执行的操作
* 如当后台 {@link Service} 执行某个任务时, 需要让前台 {@link Activity} ,做出某种响应操作或其他操作,如弹出 {@link Dialog}, 这时在 {@link Service} 中就可以使用 {@link #getCurrentActivity()}
* 如果返回为 {@code null}, 说明没有前台 {@link Activity} (用户返回桌面或者打开了其他 App 会出现此状况), 则不做任何操作, 不为 {@code null}, 则弹出 {@link Dialog}
*
* @return
*/
public Activity getCurrentActivity() {
return mCurrentActivity != null ? mCurrentActivity : null;
}
/**
* 获取最近启动的一个 {@link Activity}, 此方法不保证获取到的 {@link Activity} 正处于前台可见状态
* 即使 App 进入后台或在这个 {@link Activity} 中打开一个之前已经存在的 {@link Activity}, 这时调用此方法
* 还是会返回这个最近启动的 {@link Activity}, 因此基本不会出现 {@code null} 的情况
* 比较适合大部分的使用场景, 如 startActivity
* <p>
* Tips: mActivityList 容器中的顺序仅仅是 Activity 的创建顺序, 并不能保证和 Activity 任务栈顺序一致
*
* @return
*/
public Activity getTopActivity() {
if (mActivityList == null) {
Timber.tag(TAG).w("mActivityList == null when getTopActivity()");
return null;
}
return mActivityList.size() > 0 ? mActivityList.get(mActivityList.size() - 1) : null;
}
/**
* 返回一个存储所有未销毁的 {@link Activity} 的集合
*
* @return
*/
public List<Activity> getActivityList() {
if (mActivityList == null) {
mActivityList = new LinkedList<>();
}
return mActivityList;
}
/**
* 添加 {@link Activity} 到集合
*/
public void addActivity(Activity activity) {
if (mActivityList == null) {
mActivityList = new LinkedList<>();
}
synchronized (AppManager.class) {
if (!mActivityList.contains(activity)) {
mActivityList.add(activity);
}
}
}
/**
* 删除集合里的指定的 {@link Activity} 实例
*
* @param {@link Activity}
*/
public void removeActivity(Activity activity) {
if (mActivityList == null) {
Timber.tag(TAG).w("mActivityList == null when removeActivity(Activity)");
return;
}
synchronized (AppManager.class) {
if (mActivityList.contains(activity)) {
mActivityList.remove(activity);
}
}
}
/**
* 删除集合里的指定位置的 {@link Activity}
*
* @param location
*/
public Activity removeActivity(int location) {
if (mActivityList == null) {
Timber.tag(TAG).w("mActivityList == null when removeActivity(int)");
return null;
}
synchronized (AppManager.class) {
if (location > 0 && location < mActivityList.size()) {
return mActivityList.remove(location);
}
}
return null;
}
/**
* 关闭指定的 {@link Activity} class 的所有的实例
*
* @param activityClass
*/
public void killActivity(Class<?> activityClass) {
if (mActivityList == null) {
Timber.tag(TAG).w("mActivityList == null when killActivity(Class)");
return;
}
for (Activity activity : mActivityList) {
if (activity.getClass().equals(activityClass)) {
activity.finish();
}
}
}
/**
* 指定的 {@link Activity} 实例是否存活
*
* @param {@link Activity}
* @return
*/
public boolean activityInstanceIsLive(Activity activity) {
if (mActivityList == null) {
Timber.tag(TAG).w("mActivityList == null when activityInstanceIsLive(Activity)");
return false;
}
return mActivityList.contains(activity);
}
/**
* 指定的 {@link Activity} class 是否存活(同一个 {@link Activity} class 可能有多个实例)
*
* @param activityClass
* @return
*/
public boolean activityClassIsLive(Class<?> activityClass) {
if (mActivityList == null) {
Timber.tag(TAG).w("mActivityList == null when activityClassIsLive(Class)");
return false;
}
for (Activity activity : mActivityList) {
if (activity.getClass().equals(activityClass)) {
return true;
}
}
return false;
}
/**
* 获取指定 {@link Activity} class 的实例,没有则返回 null(同一个 {@link Activity} class 有多个实例,则返回最早创建的实例)
*
* @param activityClass
* @return
*/
public Activity findActivity(Class<?> activityClass) {
if (mActivityList == null) {
Timber.tag(TAG).w("mActivityList == null when findActivity(Class)");
return null;
}
for (Activity activity : mActivityList) {
if (activity.getClass().equals(activityClass)) {
return activity;
}
}
return null;
}
/**
* 关闭所有 {@link Activity}
*/
public void killAll() {
// while (getActivityList().size() != 0) { //此方法只能兼容LinkedList
// getActivityList().remove(0).finish();
// }
Iterator<Activity> iterator = getActivityList().iterator();
while (iterator.hasNext()) {
Activity next = iterator.next();
iterator.remove();
next.finish();
}
}
/**
* 关闭所有 {@link Activity},排除指定的 {@link Activity}
*
* @param excludeActivityClasses activity class
*/
public void killAll(Class<?>... excludeActivityClasses) {
List<Class<?>> excludeList = Arrays.asList(excludeActivityClasses);
Iterator<Activity> iterator = getActivityList().iterator();
while (iterator.hasNext()) {
Activity next = iterator.next();
if (excludeList.contains(next.getClass()))
continue;
iterator.remove();
next.finish();
}
}
/**
* 关闭所有 {@link Activity},排除指定的 {@link Activity}
*
* @param excludeActivityName {@link Activity} 的完整全路径
*/
public void killAll(String... excludeActivityName) {
List<String> excludeList = Arrays.asList(excludeActivityName);
Iterator<Activity> iterator = getActivityList().iterator();
while (iterator.hasNext()) {
Activity next = iterator.next();
if (excludeList.contains(next.getClass().getName()))
continue;
iterator.remove();
next.finish();
}
}
/**
* 退出应用程序
*/
public void appExit() {
try {
killAll();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
public interface HandleListener {
void handleMessage(AppManager appManager, Message message);
}
}
|
arms/src/main/java/com/jess/arms/integration/AppManager.java
|
/**
* Copyright 2017 JessYan
*
* 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.jess.arms.integration;
import android.app.Activity;
import android.app.Application;
import android.app.Dialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.view.View;
import com.jess.arms.base.delegate.AppLifecycles;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import timber.log.Timber;
/**
* ================================================
* 用于管理所有 {@link Activity},和在前台的 {@link Activity}
* 可以通过直接持有 {@link AppManager} 对象执行对应方法
* 也可以通过 {@link #post(Message)} ,远程遥控执行对应方法,用法和 EventBus 类似
*
* @see <a href="https://github.com/JessYanCoding/MVPArms/wiki#3.11">AppManager wiki 官方文档</a>
* Created by JessYan on 14/12/2016 13:50
* <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
@Singleton
public final class AppManager {
protected final String TAG = this.getClass().getSimpleName();
public static final String APPMANAGER_MESSAGE = "appmanager_message";
public static final String IS_NOT_ADD_ACTIVITY_LIST = "is_not_add_activity_list";//true 为不需要加入到 Activity 容器进行统一管理,默认为 false
public static final int START_ACTIVITY = 5000;
public static final int SHOW_SNACKBAR = 5001;
public static final int KILL_ALL = 5002;
public static final int APP_EXIT = 5003;
private Application mApplication;
//管理所有activity
public List<Activity> mActivityList;
//当前在前台的activity
private Activity mCurrentActivity;
//提供给外部扩展 AppManager 的 onReceive 方法
private HandleListener mHandleListener;
@Inject
public AppManager(Application application) {
this.mApplication = application;
EventBus.getDefault().register(this);
}
/**
* 通过 {@link EventBus#post(Object)} 事件, 远程遥控执行对应方法
* 可通过 {@link #setHandleListener(HandleListener)}, 让外部可扩展新的事件
*/
@Subscriber(tag = APPMANAGER_MESSAGE, mode = ThreadMode.MAIN)
public void onReceive(Message message) {
switch (message.what) {
case START_ACTIVITY:
if (message.obj == null)
break;
dispatchStart(message);
break;
case SHOW_SNACKBAR:
if (message.obj == null)
break;
showSnackbar((String) message.obj, message.arg1 == 0 ? false : true);
break;
case KILL_ALL:
killAll();
break;
case APP_EXIT:
appExit();
break;
default:
Timber.tag(TAG).w("The message.what not match");
break;
}
if (mHandleListener != null) {
mHandleListener.handleMessage(this, message);
}
}
private void dispatchStart(Message message) {
if (message.obj instanceof Intent)
startActivity((Intent) message.obj);
else if (message.obj instanceof Class)
startActivity((Class) message.obj);
}
public HandleListener getHandleListener() {
return mHandleListener;
}
/**
* 提供给外部扩展 {@link AppManager} 的 {@link #onReceive} 方法(远程遥控 {@link AppManager} 的功能)
* 建议在 {@link ConfigModule#injectAppLifecycle(Context, List)} 中
* 通过 {@link AppLifecycles#onCreate(Application)} 在 App 初始化时,使用此方法传入自定义的 {@link HandleListener}
*
* @param handleListener
*/
public void setHandleListener(HandleListener handleListener) {
this.mHandleListener = handleListener;
}
/**
* 通过此方法远程遥控 {@link AppManager} ,使 {@link #onReceive(Message)} 执行对应方法
*
* @param msg
*/
public static void post(Message msg) {
EventBus.getDefault().post(msg, APPMANAGER_MESSAGE);
}
/**
* 让在前台的 {@link Activity},使用 {@link Snackbar} 显示文本内容
*
* @param message
* @param isLong
*/
public void showSnackbar(String message, boolean isLong) {
if (getCurrentActivity() == null) {
Timber.tag(TAG).w("mCurrentActivity == null when showSnackbar(String,boolean)");
return;
}
View view = getCurrentActivity().getWindow().getDecorView().findViewById(android.R.id.content);
Snackbar.make(view, message, isLong ? Snackbar.LENGTH_LONG : Snackbar.LENGTH_SHORT).show();
}
/**
* 让在栈顶的 {@link Activity} ,打开指定的 {@link Activity}
*
* @param intent
*/
public void startActivity(Intent intent) {
if (getTopActivity() == null) {
Timber.tag(TAG).w("mCurrentActivity == null when startActivity(Intent)");
//如果没有前台的activity就使用new_task模式启动activity
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mApplication.startActivity(intent);
return;
}
getTopActivity().startActivity(intent);
}
/**
* 让在栈顶的 {@link Activity} ,打开指定的 {@link Activity}
*
* @param activityClass
*/
public void startActivity(Class activityClass) {
startActivity(new Intent(mApplication, activityClass));
}
/**
* 释放资源
*/
public void release() {
EventBus.getDefault().unregister(this);
mActivityList.clear();
mHandleListener = null;
mActivityList = null;
mCurrentActivity = null;
mApplication = null;
}
/**
* 将在前台的 {@link Activity} 赋值给 {@code currentActivity}, 注意此方法是在 {@link Activity#onResume} 方法执行时将栈顶的 {@link Activity} 赋值给 {@code currentActivity}
* 所以在栈顶的 {@link Activity} 执行 {@link Activity#onCreate} 方法时使用 {@link #getCurrentActivity()} 获取的就不是当前栈顶的 {@link Activity}, 可能是上一个 {@link Activity}
* 如果在 App 的第一个 {@link Activity} 执行 {@link Activity#onCreate} 方法时使用 {@link #getCurrentActivity()} 则会出现返回为 {@code null} 的情况
* 想避免这种情况请使用 {@link #getTopActivity()}
*
* @param currentActivity
*/
public void setCurrentActivity(Activity currentActivity) {
this.mCurrentActivity = currentActivity;
}
/**
* 获取在前台的 {@link Activity} (保证获取到的 {@link Activity} 正处于可见状态, 即未调用 {@link Activity#onStop()}), 获取的 {@link Activity} 存续时间
* 是在 {@link Activity#onStop()} 之前, 所以如果当此 {@link Activity} 调用 {@link Activity#onStop()} 方法之后, 没有其他的 {@link Activity} 回到前台(用户返回桌面或者打开了其他 App 会出现此状况)
* 这时调用 {@link #getCurrentActivity()} 有可能返回 {@code null}, 所以请注意使用场景和 {@link #getTopActivity()} 不一样
* <p>
* Example usage:
* 使用场景比较适合, 只需要在可见状态的 {@link Activity} 上执行的操作
* 如当后台 {@link Service} 执行某个任务时, 需要让前台 {@link Activity} ,做出某种响应操作或其他操作,如弹出 {@link Dialog}, 这时在 {@link Service} 中就可以使用 {@link #getCurrentActivity()}
* 如果返回为 {@code null}, 说明没有前台 {@link Activity} (用户返回桌面或者打开了其他 App 会出现此状况), 则不做任何操作, 不为 {@code null}, 则弹出 {@link Dialog}
*
* @return
*/
public Activity getCurrentActivity() {
return mCurrentActivity != null ? mCurrentActivity : null;
}
/**
* 获取位于栈顶的 {@link Activity}, 此方法不保证获取到的 {@link Activity} 正处于可见状态, 即使 App 进入后台也会返回当前栈顶的 {@link Activity}
* 因此基本不会出现 {@code null} 的情况, 比较适合大部分的使用场景, 如 startActivity, Glide 加载图片
*
* @return
*/
public Activity getTopActivity() {
if (mActivityList == null) {
Timber.tag(TAG).w("mActivityList == null when getTopActivity()");
return null;
}
return mActivityList.size() > 0 ? mActivityList.get(mActivityList.size() - 1) : null;
}
/**
* 返回一个存储所有未销毁的 {@link Activity} 的集合
*
* @return
*/
public List<Activity> getActivityList() {
if (mActivityList == null) {
mActivityList = new LinkedList<>();
}
return mActivityList;
}
/**
* 添加 {@link Activity} 到集合
*/
public void addActivity(Activity activity) {
if (mActivityList == null) {
mActivityList = new LinkedList<>();
}
synchronized (AppManager.class) {
if (!mActivityList.contains(activity)) {
mActivityList.add(activity);
}
}
}
/**
* 删除集合里的指定的 {@link Activity} 实例
*
* @param {@link Activity}
*/
public void removeActivity(Activity activity) {
if (mActivityList == null) {
Timber.tag(TAG).w("mActivityList == null when removeActivity(Activity)");
return;
}
synchronized (AppManager.class) {
if (mActivityList.contains(activity)) {
mActivityList.remove(activity);
}
}
}
/**
* 删除集合里的指定位置的 {@link Activity}
*
* @param location
*/
public Activity removeActivity(int location) {
if (mActivityList == null) {
Timber.tag(TAG).w("mActivityList == null when removeActivity(int)");
return null;
}
synchronized (AppManager.class) {
if (location > 0 && location < mActivityList.size()) {
return mActivityList.remove(location);
}
}
return null;
}
/**
* 关闭指定的 {@link Activity} class 的所有的实例
*
* @param activityClass
*/
public void killActivity(Class<?> activityClass) {
if (mActivityList == null) {
Timber.tag(TAG).w("mActivityList == null when killActivity(Class)");
return;
}
for (Activity activity : mActivityList) {
if (activity.getClass().equals(activityClass)) {
activity.finish();
}
}
}
/**
* 指定的 {@link Activity} 实例是否存活
*
* @param {@link Activity}
* @return
*/
public boolean activityInstanceIsLive(Activity activity) {
if (mActivityList == null) {
Timber.tag(TAG).w("mActivityList == null when activityInstanceIsLive(Activity)");
return false;
}
return mActivityList.contains(activity);
}
/**
* 指定的 {@link Activity} class 是否存活(同一个 {@link Activity} class 可能有多个实例)
*
* @param activityClass
* @return
*/
public boolean activityClassIsLive(Class<?> activityClass) {
if (mActivityList == null) {
Timber.tag(TAG).w("mActivityList == null when activityClassIsLive(Class)");
return false;
}
for (Activity activity : mActivityList) {
if (activity.getClass().equals(activityClass)) {
return true;
}
}
return false;
}
/**
* 获取指定 {@link Activity} class 的实例,没有则返回 null(同一个 {@link Activity} class 有多个实例,则返回最早的实例)
*
* @param activityClass
* @return
*/
public Activity findActivity(Class<?> activityClass) {
if (mActivityList == null) {
Timber.tag(TAG).w("mActivityList == null when findActivity(Class)");
return null;
}
for (Activity activity : mActivityList) {
if (activity.getClass().equals(activityClass)) {
return activity;
}
}
return null;
}
/**
* 关闭所有 {@link Activity}
*/
public void killAll() {
// while (getActivityList().size() != 0) { //此方法只能兼容LinkedList
// getActivityList().remove(0).finish();
// }
Iterator<Activity> iterator = getActivityList().iterator();
while (iterator.hasNext()) {
Activity next = iterator.next();
iterator.remove();
next.finish();
}
}
/**
* 关闭所有 {@link Activity},排除指定的 {@link Activity}
*
* @param excludeActivityClasses activity class
*/
public void killAll(Class<?>... excludeActivityClasses) {
List<Class<?>> excludeList = Arrays.asList(excludeActivityClasses);
Iterator<Activity> iterator = getActivityList().iterator();
while (iterator.hasNext()) {
Activity next = iterator.next();
if (excludeList.contains(next.getClass()))
continue;
iterator.remove();
next.finish();
}
}
/**
* 关闭所有 {@link Activity},排除指定的 {@link Activity}
*
* @param excludeActivityName {@link Activity} 的完整全路径
*/
public void killAll(String... excludeActivityName) {
List<String> excludeList = Arrays.asList(excludeActivityName);
Iterator<Activity> iterator = getActivityList().iterator();
while (iterator.hasNext()) {
Activity next = iterator.next();
if (excludeList.contains(next.getClass().getName()))
continue;
iterator.remove();
next.finish();
}
}
/**
* 退出应用程序
*/
public void appExit() {
try {
killAll();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
public interface HandleListener {
void handleMessage(AppManager appManager, Message message);
}
}
|
Improve AppManager comments
|
arms/src/main/java/com/jess/arms/integration/AppManager.java
|
Improve AppManager comments
|
|
Java
|
apache-2.0
|
00644b961270fbb53551d8e8cbf4c0831093ed74
| 0
|
ov3rflow/eFaps-Kernel,eFaps/eFaps-Kernel
|
/*
* Copyright 2003-2007 The eFaps Team
*
* 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.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.ui.wicket.components.table;
import java.util.Iterator;
import org.apache.wicket.Page;
import org.apache.wicket.behavior.HeaderContributor;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.efaps.admin.dbproperty.DBProperties;
import org.efaps.ui.wicket.components.table.row.RowPanel;
import org.efaps.ui.wicket.models.TableModel;
import org.efaps.ui.wicket.models.TableModel.RowModel;
import org.efaps.ui.wicket.pages.contentcontainer.ContentContainerPage;
public class TablePanel extends Panel {
private static final long serialVersionUID = 1L;
public TablePanel(final String _id, final TableModel _model, final Page _page) {
super(_id, _model);
if (!_model.isInitialised()) {
_model.execute();
}
add(HeaderContributor.forCss(getClass(), "TablePanel.css"));
RepeatingView rowsRepeater = new RepeatingView("rowRepeater");
add(rowsRepeater);
if (_model.getValues().isEmpty()) {
final Label nodata =
new Label(rowsRepeater.newChildId(), DBProperties
.getProperty("WebTable.NoData"));
nodata.add(new SimpleAttributeModifier("class", "eFapsTableNoData"));
rowsRepeater.add(nodata);
} else {
boolean odd = true;
for (final Iterator<RowModel> rowIter = _model.getValues().iterator(); rowIter
.hasNext(); odd = !odd) {
RowPanel row =
new RowPanel(rowsRepeater.newChildId(), rowIter.next(), _model,
ContentContainerPage.IFRAME_PAGEMAP_NAME.equals(_page
.getPageMapName()));
row.setOutputMarkupId(true);
if (odd) {
row.add(new SimpleAttributeModifier("class", "eFapsTableRowOdd"));
} else {
row.add(new SimpleAttributeModifier("class", "eFapsTableRowEven"));
}
rowsRepeater.add(row);
}
}
}
}
|
webapp/src/main/java/org/efaps/ui/wicket/components/table/TablePanel.java
|
/*
* Copyright 2003-2007 The eFaps Team
*
* 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.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.ui.wicket.components.table;
import java.util.Iterator;
import org.apache.wicket.Page;
import org.apache.wicket.behavior.HeaderContributor;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.efaps.admin.dbproperty.DBProperties;
import org.efaps.ui.wicket.components.table.row.RowPanel;
import org.efaps.ui.wicket.models.TableModel;
import org.efaps.ui.wicket.models.TableModel.RowModel;
import org.efaps.ui.wicket.pages.contentcontainer.ContentContainerPage;
public class TablePanel extends Panel {
private static final long serialVersionUID = 1L;
public TablePanel(final String _id, final TableModel _model,
final Page _page) {
super(_id, _model);
if (!_model.isInitialised()) {
_model.execute();
}
add(HeaderContributor.forCss(getClass(), "TablePanel.css"));
RepeatingView rowsRepeater = new RepeatingView("rowRepeater");
add(rowsRepeater);
if (_model.getValues().isEmpty()) {
final Label nodata =
new Label("test", DBProperties.getProperty("WebTable.NoData"));
nodata.add(new SimpleAttributeModifier("class", "eFapsTableNoData"));
rowsRepeater.add(nodata);
} else {
boolean odd = true;
for (final Iterator<RowModel> rowIter = _model.getValues().iterator(); rowIter
.hasNext(); odd = !odd) {
RowPanel row =
new RowPanel(rowsRepeater.newChildId(), rowIter.next(), _model,
ContentContainerPage.IFRAME_PAGEMAP_NAME.equals(_page
.getPageMapName()));
row.setOutputMarkupId(true);
if (odd) {
row.add(new SimpleAttributeModifier("class", "eFapsTableRowOdd"));
} else {
row.add(new SimpleAttributeModifier("class", "eFapsTableRowEven"));
}
rowsRepeater.add(row);
}
}
}
}
|
- correction of wicket:id due to warning that might leed to future problems
git-svn-id: 4b3b87045ec33e1a2f7ddff44705baa56df11711@1593 fee104cc-1dfa-8c0f-632d-d3b7e6b59fb0
|
webapp/src/main/java/org/efaps/ui/wicket/components/table/TablePanel.java
|
- correction of wicket:id due to warning that might leed to future problems
|
|
Java
|
apache-2.0
|
a8c561cdce244ea8728918f39afaaef18ae43036
| 0
|
asciidoctor/asciidoctor-intellij-plugin,asciidoctor/asciidoctor-intellij-plugin,asciidoctor/asciidoctor-intellij-plugin,asciidoctor/asciidoctor-intellij-plugin,asciidoctor/asciidoctor-intellij-plugin
|
package org.asciidoc.intellij.editor.javafx;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.actions.OpenFileAction;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.ide.projectView.impl.ProjectViewPane;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.CaretState;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.fileChooser.FileChooserFactory;
import com.intellij.openapi.fileChooser.FileSaverDescriptor;
import com.intellij.openapi.fileChooser.FileSaverDialog;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileWrapper;
import com.intellij.ui.JBColor;
import com.intellij.util.PsiNavigateUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.sun.javafx.application.PlatformImpl;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker.State;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.text.FontSmoothingType;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import netscape.javascript.JSObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.asciidoc.intellij.editor.AsciiDocHtmlPanel;
import org.asciidoc.intellij.editor.AsciiDocHtmlPanelProvider;
import org.asciidoc.intellij.editor.AsciiDocPreviewEditor;
import org.asciidoc.intellij.psi.AsciiDocBlockId;
import org.asciidoc.intellij.psi.AsciiDocUtil;
import org.asciidoc.intellij.settings.AsciiDocApplicationSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.w3c.dom.html.HTMLImageElement;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaFxHtmlPanel extends AsciiDocHtmlPanel {
private Logger log = Logger.getInstance(JavaFxHtmlPanel.class);
private static final NotNullLazyValue<String> MY_SCRIPTING_LINES = new NotNullLazyValue<String>() {
@NotNull
@Override
protected String compute() {
final Class<JavaFxHtmlPanel> clazz = JavaFxHtmlPanel.class;
//noinspection StringBufferReplaceableByString
return new StringBuilder()
.append("<script src=\"").append(PreviewStaticServer.getScriptUrl("scrollToElement.js")).append("\"></script>\n")
.append("<script src=\"").append(PreviewStaticServer.getScriptUrl("processLinks.js")).append("\"></script>\n")
.append("<script src=\"").append(PreviewStaticServer.getScriptUrl("pickSourceLine.js")).append("\"></script>\n")
.append("<script type=\"text/x-mathjax-config\">\n" +
"MathJax.Hub.Config({\n" +
" messageStyle: \"none\",\n" +
" EqnChunkDelay: 1," +
" tex2jax: {\n" +
" inlineMath: [[\"\\\\(\", \"\\\\)\"]],\n" +
" displayMath: [[\"\\\\[\", \"\\\\]\"]],\n" +
" ignoreClass: \"nostem|nolatexmath\"\n" +
" },\n" +
" asciimath2jax: {\n" +
" delimiters: [[\"\\\\$\", \"\\\\$\"]],\n" +
" ignoreClass: \"nostem|noasciimath\"\n" +
" },\n" +
" TeX: { equationNumbers: { autoNumber: \"none\" } }\n" +
"});\n" +
"MathJax.Hub.Register.MessageHook(\"Math Processing Error\",function (message) {\n" +
" window.JavaPanelBridge && window.JavaPanelBridge.log(JSON.stringify(message)); \n" +
"});" +
"MathJax.Hub.Register.MessageHook(\"TeX Jax - parse error\",function (message) {\n" +
" var errortext = document.getElementById('mathjaxerrortext'); " +
" var errorformula = document.getElementById('mathjaxerrorformula'); " +
" if (errorformula && errortext) { " +
" errortext.textContent = 'Math Formula problem: ' + message[1]; " +
" errorformula.textContent = '\\n' + message[2]; " +
" } " +
" window.JavaPanelBridge && window.JavaPanelBridge.log(JSON.stringify(message)); \n" +
"});" +
"</script>\n")
.append("<script src=\"").append(PreviewStaticServer.getScriptUrl("MathJax/MathJax.js")).append("&config=TeX-MML-AM_HTMLorMML\"></script>\n")
.toString();
}
};
@NotNull
private final JPanel myPanelWrapper;
@NotNull
private final List<Runnable> myInitActions = new ArrayList<>();
@Nullable
private volatile JFXPanel myPanel;
@Nullable
private WebView myWebView;
@Nullable
private String myInlineCss;
@Nullable
private String myInlineCssDarcula;
@Nullable
private String myFontAwesomeCssLink;
@Nullable
private String myDejavuCssLink;
@NotNull
private final ScrollPreservingListener myScrollPreservingListener = new ScrollPreservingListener();
@NotNull
private final BridgeSettingListener myBridgeSettingListener = new BridgeSettingListener();
@NotNull
private String base;
private int lineCount;
private int offset;
private final Path imagesPath;
private VirtualFile parentDirectory;
private VirtualFile saveImageLastDir = null;
private volatile CountDownLatch rendered;
JavaFxHtmlPanel(Document document, Path imagesPath) {
//System.setProperty("prism.lcdtext", "false");
//System.setProperty("prism.text", "t2k");
this.imagesPath = imagesPath;
myPanelWrapper = new JPanel(new BorderLayout());
myPanelWrapper.setBackground(JBColor.background());
lineCount = document.getLineCount();
VirtualFile file = FileDocumentManager.getInstance().getFile(document);
if (file != null) {
parentDirectory = file.getParent();
}
if (parentDirectory != null) {
// parent will be null if we use Language Injection and Fragment Editor
base = parentDirectory.getUrl().replaceAll("^file://", "")
.replaceAll(":", "%3A");
} else {
base = "";
}
try {
Properties p = new Properties();
p.load(JavaFxHtmlPanel.class.getResourceAsStream("/META-INF/asciidoctorj-version.properties"));
String asciidoctorVersion = p.getProperty("version.asciidoctor");
myInlineCss = IOUtils.toString(JavaFxHtmlPanel.class.getResourceAsStream("/gems/asciidoctor-"
+ asciidoctorVersion
+ "/data/stylesheets/asciidoctor-default.css"));
// asian characters won't display with text-rendering:optimizeLegibility
// https://github.com/asciidoctor/asciidoctor-intellij-plugin/issues/203
myInlineCss = myInlineCss.replaceAll("text-rendering:", "disabled-text-rendering");
// JavaFX doesn't load 'DejaVu Sans Mono' font when 'Droid Sans Mono' is listed first
// https://github.com/asciidoctor/asciidoctor-intellij-plugin/issues/193
myInlineCss = myInlineCss.replaceAll("(\"Noto Serif\"|\"Open Sans\"|\"Droid Sans Mono\"),", "");
myInlineCssDarcula = myInlineCss + IOUtils.toString(JavaFxHtmlPanel.class.getResourceAsStream("darcula.css"));
myInlineCssDarcula += IOUtils.toString(JavaFxHtmlPanel.class.getResourceAsStream("coderay-darcula.css"));
myInlineCss += IOUtils.toString(JavaFxHtmlPanel.class.getResourceAsStream("/gems/asciidoctor-"
+ asciidoctorVersion
+ "/data/stylesheets/coderay-asciidoctor.css"));
myFontAwesomeCssLink = "<link rel=\"stylesheet\" href=\"" + PreviewStaticServer.getStyleUrl("font-awesome/css/font-awesome.min.css") + "\">";
myDejavuCssLink = "<link rel=\"stylesheet\" href=\"" + PreviewStaticServer.getStyleUrl("dejavu/dejavu.css") + "\">";
} catch (IOException e) {
String message = "Unable to combine CSS resources: " + e.getMessage();
log.error(message, e);
Notification notification = AsciiDocPreviewEditor.NOTIFICATION_GROUP
.createNotification("Error rendering asciidoctor", message, NotificationType.ERROR, null);
// increase event log counter
notification.setImportant(true);
Notifications.Bus.notify(notification);
}
ApplicationManager.getApplication().invokeLater(() -> runFX(new Runnable() {
@Override
public void run() {
if (new JavaFxHtmlPanelProvider().isAvailable() == AsciiDocHtmlPanelProvider.AvailabilityInfo.UNAVAILABLE) {
String message = "JavaFX unavailable, probably stuck";
log.warn(message);
return;
}
try {
PlatformImpl.startup(() -> {
myWebView = new WebView();
updateFontSmoothingType(myWebView, false);
registerContextMenu(JavaFxHtmlPanel.this.myWebView);
myWebView.setContextMenuEnabled(false);
myWebView.setZoom(JBUI.scale(1.f));
myWebView.getEngine().loadContent(prepareHtml("<html><head></head><body>Initializing...</body>"));
myWebView.addEventFilter(ScrollEvent.SCROLL, scrollEvent -> {
// touch pads send lots of events with deltaY == 0, not handling them here
if (scrollEvent.isControlDown() && Double.compare(scrollEvent.getDeltaY(), 0.0) != 0) {
double zoom = myWebView.getZoom();
double factor = (scrollEvent.getDeltaY() > 0.0 ? 0.1 : -0.1)
// normalize scrolling
* (Math.abs(scrollEvent.getDeltaY()) / scrollEvent.getMultiplierY())
// adding one to make it a factor that we can multiply the zoom by
+ 1;
zoom = zoom * factor;
// define minimum/maximum zoom
if (zoom < JBUI.scale(0.1f)) {
zoom = 0.1;
} else if (zoom > JBUI.scale(10.f)) {
zoom = 10;
}
myWebView.setZoom(zoom);
scrollEvent.consume();
}
});
myWebView.addEventFilter(MouseEvent.MOUSE_CLICKED, mouseEvent -> {
if (mouseEvent.isControlDown() && mouseEvent.getButton() == MouseButton.MIDDLE) {
myWebView.setZoom(JBUI.scale(1f));
mouseEvent.consume();
}
});
final WebEngine engine = myWebView.getEngine();
engine.getLoadWorker().stateProperty().addListener(myBridgeSettingListener);
engine.getLoadWorker().stateProperty().addListener(myScrollPreservingListener);
final Scene scene = new Scene(myWebView);
ApplicationManager.getApplication().invokeLater(() -> runFX(() -> {
try {
synchronized (myInitActions) {
myPanel = new JFXPanelWrapper();
Platform.runLater(() -> myPanel.setScene(scene));
for (Runnable action : myInitActions) {
Platform.runLater(action);
}
myInitActions.clear();
}
myPanelWrapper.add(myPanel, BorderLayout.CENTER);
myPanelWrapper.repaint();
} catch (Throwable e) {
log.warn("can't initialize JFXPanelWrapper", e);
}
}));
});
} catch (Throwable ex) {
String message = "Error initializing JavaFX: " + ex.getMessage();
log.error(message, ex);
Notification notification = AsciiDocPreviewEditor.NOTIFICATION_GROUP.createNotification("Error rendering asciidoctor", message,
NotificationType.ERROR, null);
// increase event log counter
notification.setImportant(true);
Notifications.Bus.notify(notification);
}
}
}));
}
private void registerContextMenu(WebView webView) {
webView.setOnMousePressed(e -> {
if (e.getButton() == MouseButton.SECONDARY) {
JSObject object = getJavaScriptObjectAtLocation(webView, e);
if (object instanceof HTMLImageElement) {
String src = ((HTMLImageElement) object).getAttribute("src");
ApplicationManager.getApplication().invokeLater(() -> saveImage(src));
}
}
});
}
private JSObject getJavaScriptObjectAtLocation(WebView webView, MouseEvent e) {
String script = String.format("document.elementFromPoint(%s,%s);", e.getX(), e.getY());
return (JSObject) webView.getEngine().executeScript(script);
}
private void saveImage(@NotNull String path) {
String parent = imagesPath.getFileName().toString();
String subPath = path.substring(path.indexOf(parent) + parent.length() + 1);
Path imagePath = imagesPath.resolve(subPath);
if (imagePath.toFile().exists()) {
File file = imagePath.toFile();
String fileName = imagePath.getFileName().toString();
ArrayList<String> extensions = new ArrayList<>();
int lastDotIndex = fileName.lastIndexOf('.');
if (lastDotIndex > 0 && !fileName.endsWith(".")) {
extensions.add(fileName.substring(lastDotIndex + 1));
}
// set static file name if image name has been generated dynamically
final String fileNameNoExt;
if (fileName.matches("diag-[0-9a-f]{32}\\.[a-z]+")) {
fileNameNoExt = "image";
} else {
fileNameNoExt = lastDotIndex > 0 ? fileName.substring(0, lastDotIndex) : fileName;
}
// check if also a SVG exists for the provided PNG
if (extensions.contains("png") &&
new File(file.getParent(), fileNameNoExt + ".svg").exists()) {
extensions.add("svg");
}
final FileSaverDescriptor descriptor = new FileSaverDescriptor("Export Image to", "Choose the destination file",
extensions.toArray(new String[]{}));
FileSaverDialog saveFileDialog = FileChooserFactory.getInstance().createSaveFileDialog(descriptor, (Project) null);
VirtualFile baseDir = saveImageLastDir;
if (baseDir == null) {
baseDir = parentDirectory;
}
VirtualFile finalBaseDir = baseDir;
SwingUtilities.invokeLater(() -> {
VirtualFileWrapper destination = saveFileDialog.save(finalBaseDir, fileNameNoExt);
if (destination != null) {
try {
saveImageLastDir = LocalFileSystem.getInstance().findFileByIoFile(destination.getFile().getParentFile());
Path src = imagePath;
// if the destination ends with .svg, but the source doesn't, patch the source file name as the user chose a different file type
if (destination.getFile().getAbsolutePath().endsWith(".svg") && !src.endsWith(".svg")) {
src = new File(src.toFile().getAbsolutePath().replaceAll("\\.png$", ".svg")).toPath();
}
Files.copy(src, destination.getFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
String message = "Can't save file: " + ex.getMessage();
Notification notification = AsciiDocPreviewEditor.NOTIFICATION_GROUP
.createNotification("Error in plugin", message, NotificationType.ERROR, null);
// increase event log counter
notification.setImportant(true);
Notifications.Bus.notify(notification);
}
}
});
}
}
private static void runFX(@NotNull Runnable r) {
IdeEventQueue.unsafeNonblockingExecute(r);
}
private void runInPlatformWhenAvailable(@NotNull final Runnable runnable) {
synchronized (myInitActions) {
if (myPanel == null) {
myInitActions.add(runnable);
} else {
Platform.runLater(runnable);
}
}
}
private boolean isDarcula() {
final AsciiDocApplicationSettings settings = AsciiDocApplicationSettings.getInstance();
switch (settings.getAsciiDocPreviewSettings().getPreviewTheme()) {
case INTELLIJ:
return UIUtil.isUnderDarcula();
case ASCIIDOC:
return false;
case DARCULA:
return true;
default:
return false;
}
}
private static void updateFontSmoothingType(@NotNull WebView view, boolean isGrayscale) {
final FontSmoothingType typeToSet;
if (isGrayscale) {
typeToSet = FontSmoothingType.GRAY;
} else {
typeToSet = FontSmoothingType.LCD;
}
view.fontSmoothingTypeProperty().setValue(typeToSet);
}
@NotNull
@Override
public JComponent getComponent() {
return myPanelWrapper;
}
@Override
public void setHtml(@NotNull String htmlParam) {
rendered = new CountDownLatch(1);
runInPlatformWhenAvailable(() -> {
String html = htmlParam;
if (isDarcula()) {
// clear out coderay inline CSS colors as they are barely readable in darcula theme
html = html.replaceAll("<span style=\"color:#[a-zA-Z0-9]*;?", "<span style=\"");
html = html.replaceAll("<span style=\"background-color:#[a-zA-Z0-9]*;?", "<span style=\"");
}
boolean result = false;
final AsciiDocApplicationSettings settings = AsciiDocApplicationSettings.getInstance();
if (settings.getAsciiDocPreviewSettings().isInplacePreviewRefresh() && html.contains("id=\"content\"")) {
final String htmlToReplace = StringEscapeUtils.escapeEcmaScript(prepareHtml(html));
// try to replace the HTML contents using JavaScript to avoid flickering MathML
try {
result = (Boolean) JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().executeScript(
"function finish() {" +
"if ('__IntelliJTools' in window) {" +
"__IntelliJTools.processLinks && __IntelliJTools.processLinks();" +
"__IntelliJTools.pickSourceLine && __IntelliJTools.pickSourceLine(" + lineCount + ", " + offset + ");" +
"}" +
"window.JavaPanelBridge && window.JavaPanelBridge.rendered();" +
"}" +
"function updateContent() { var elem = document.getElementById('content'); if (elem && elem.parentNode) { " +
"var div = document.createElement('div');" +
"div.innerHTML = '" + htmlToReplace + "'; " +
"var errortext = document.getElementById('mathjaxerrortext'); " +
"var errorformula = document.getElementById('mathjaxerrorformula'); " +
"if (errorformula && errortext) { " +
" errortext.textContent = ''; " +
" errorformula.textContent = ''; " +
"} " +
"div.style.cssText = 'display: none'; " +
// need to add the element to the DOM as MathJAX will use document.getElementById in some places
"elem.appendChild(div); " +
// use MathJax to set the formulas in advance if formulas are present - this takes ~100ms
// re-evaluate the content element as it might have been replaced by a concurrent rendering
"if ('MathJax' in window && MathJax.Hub.getAllJax().length > 0) { MathJax.Hub.Typeset(div.firstChild, function() { var elem2 = document.getElementById('content'); elem2.parentNode.replaceChild(div.firstChild, elem2); finish(); }); } " +
// if no math was present before, replace contents, and do the MathJax typesetting afterwards in case Math has been added
"else { elem.parentNode.replaceChild(div.firstChild, elem); MathJax.Hub.Typeset(div.firstChild); finish(); } " +
"return true; } else { return false; }}; updateContent();"
);
} catch (RuntimeException e) {
// might happen when rendered output is not valid HTML due to passtrough content
log.warn("unable to use JavaScript for update", e);
}
}
// if not successful using JavaScript (like on first rendering attempt), set full content
if (!result) {
html = "<html><head></head><body><div style='position:fixed;top:0;left:0;background-color:#eeeeee;color:red;z-index:99;'><div id='mathjaxerrortext'></div><pre style='color:red' id='mathjaxerrorformula'></pre></div>" + html + "</body>";
final String htmlToRender = prepareHtml(html);
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().loadContent(htmlToRender);
rendered.countDown();
}
});
try {
// slow down the rendering of the next version of the preview until the rendering if the current version is complete
// this prevents us building up a queue that would lead to a lagging preview
rendered.await(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.warn("rendering didn't complete in time, might be slow or broken");
}
}
private String findTempImageFile(String filename) {
Path file = imagesPath.resolve(filename);
if (Files.exists(file)) {
return file.toFile().toString();
}
return null;
}
private String prepareHtml(@NotNull String html) {
/* for each image we'll calculate a MD5 sum of its content. Once the content changes, MD5 and therefore the URL
* will change. The changed URL is necessary for the JavaFX web view to display the new content, as each URL
* will be loaded only once by the JavaFX web view. */
Pattern pattern = Pattern.compile("<img src=\"([^:\"]*)\"");
final Matcher matcher = pattern.matcher(html);
while (matcher.find()) {
final MatchResult matchResult = matcher.toMatchResult();
String file = matchResult.group(1);
String tmpFile = findTempImageFile(file);
String md5;
String replacement;
if (tmpFile != null) {
md5 = calculateMd5(tmpFile, null);
tmpFile = tmpFile.replaceAll("\\\\", "/");
tmpFile = tmpFile.replaceAll(":", "%3A");
if (JavaFxHtmlPanelProvider.isInitialized()) {
replacement = "<img src=\"localfile://" + md5 + "/" + tmpFile + "\"";
} else {
replacement = "<img src=\"file://" + tmpFile.replaceAll("%3A", ":") + "\"";
}
} else {
md5 = calculateMd5(file, base);
if (JavaFxHtmlPanelProvider.isInitialized()) {
replacement = "<img src=\"localfile://" + md5 + "/" + base + "/" + file + "\"";
} else {
replacement = "<img src=\"file://" + base.replaceAll("%3A", ":") + "/" + file + "\"";
}
}
html = html.substring(0, matchResult.start()) +
replacement + html.substring(matchResult.end());
matcher.reset(html);
}
// filter out Twitter's JavaScript, as it is problematic for JDK8 JavaFX
// see: https://github.com/asciidoctor/asciidoctor-intellij-plugin/issues/235
html = html.replaceAll("(?i)<script [a-z ]*src=\"https://platform\\.twitter\\.com/widgets\\.js\" [^>]*></script>", "");
/* Add CSS line and JavaScript for auto-scolling and clickable links */
return html
.replace("<head>", "<head>" + getCssLines(isDarcula() ? myInlineCssDarcula : myInlineCss) + myFontAwesomeCssLink + myDejavuCssLink)
.replace("</body>", getScriptingLines() + "</body>");
}
private String calculateMd5(String file, String base) {
String md5;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
try (FileInputStream fis = new FileInputStream((base != null ? base.replaceAll("%3A", ":") + "/" : "") + file)) {
int nread;
byte[] dataBytes = new byte[1024];
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
}
}
byte[] mdbytes = md.digest();
StringBuilder sb = new StringBuilder();
for (byte mdbyte : mdbytes) {
sb.append(Integer.toString((mdbyte & 0xff) + 0x100, 16).substring(1));
}
md5 = sb.toString();
} catch (NoSuchAlgorithmException | IOException e) {
md5 = "none";
}
return md5;
}
@Override
public void render() {
runInPlatformWhenAvailable(() -> {
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().reload();
ApplicationManager.getApplication().invokeLater(myPanelWrapper::repaint);
});
}
@Override
public void scrollToLine(final int line, final int lineCount) {
this.lineCount = lineCount;
runInPlatformWhenAvailable(() -> {
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().executeScript(
"if ('__IntelliJTools' in window) " +
"__IntelliJTools.scrollToLine(" + line + ", " + lineCount + ");"
);
final Object result = JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().executeScript(
"document.documentElement.scrollTop || document.body.scrollTop");
if (result instanceof Number) {
myScrollPreservingListener.myScrollY = ((Number) result).intValue();
}
});
}
@Override
public void dispose() {
runInPlatformWhenAvailable(() -> {
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().load("about:blank");
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().getLoadWorker().stateProperty().removeListener(myScrollPreservingListener);
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().getLoadWorker().stateProperty().removeListener(myBridgeSettingListener);
});
}
@NotNull
private WebView getWebViewGuaranteed() {
if (myWebView == null) {
throw new IllegalStateException("WebView should be initialized by now. Check the caller thread");
}
return myWebView;
}
@NotNull
private static String getScriptingLines() {
return MY_SCRIPTING_LINES.getValue();
}
@SuppressWarnings("unused")
public class JavaPanelBridge {
public void openLink(@NotNull String link) {
final URI uri;
try {
uri = new URI(link);
} catch (URISyntaxException ex) {
throw new RuntimeException("unable to parse URL " + link);
}
String scheme = uri.getScheme();
if ("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme) || "mailto".equalsIgnoreCase(scheme)) {
BrowserUtil.browse(uri);
} else if ("file".equalsIgnoreCase(scheme) || scheme == null) {
openInEditor(uri);
} else {
log.warn("won't open URI as it might be unsafe: " + uri);
}
}
public void rendered() {
rendered.countDown();
}
private boolean openInEditor(@NotNull URI uri) {
return ReadAction.compute(() -> {
String anchor = uri.getFragment();
String path = uri.getPath();
final VirtualFile targetFile;
VirtualFile tmpTargetFile = parentDirectory.findFileByRelativePath(path);
if (tmpTargetFile == null) {
// extension might be skipped if it is an .adoc file
tmpTargetFile = parentDirectory.findFileByRelativePath(path + ".adoc");
}
if (tmpTargetFile == null && path.endsWith(".html")) {
// might link to a .html in the rendered output, but might actually be a .adoc file
tmpTargetFile = parentDirectory.findFileByRelativePath(path.replaceAll("\\.html$", ".adoc"));
}
if (tmpTargetFile == null) {
log.warn("unable to find file for " + uri);
return false;
}
targetFile = tmpTargetFile;
Project project = ProjectUtil.guessProjectForContentFile(targetFile);
if (project == null) {
log.warn("unable to find project for " + uri);
return false;
}
if (targetFile.isDirectory()) {
ProjectView projectView = ProjectView.getInstance(project);
projectView.changeView(ProjectViewPane.ID);
projectView.select(null, targetFile, true);
} else {
boolean anchorFound = false;
if (anchor != null) {
List<AsciiDocBlockId> ids = AsciiDocUtil.findIds(project, targetFile, anchor);
if (!ids.isEmpty()) {
anchorFound = true;
ApplicationManager.getApplication().invokeLater(() -> PsiNavigateUtil.navigate(ids.get(0)));
}
}
if (!anchorFound) {
ApplicationManager.getApplication().invokeLater(() -> OpenFileAction.openFile(targetFile, project));
}
}
return true;
});
}
public void scrollEditorToLine(int sourceLine) {
if (sourceLine <= 0) {
Notification notification = AsciiDocPreviewEditor.NOTIFICATION_GROUP.createNotification("Setting cursor position", "line number " + sourceLine + " requested for cursor position, ignoring",
NotificationType.INFORMATION, null);
notification.setImportant(false);
return;
}
ApplicationManager.getApplication().invokeLater(
() -> {
getEditor().getCaretModel().setCaretsAndSelections(
Collections.singletonList(new CaretState(new LogicalPosition(sourceLine - 1, 0), null, null))
);
getEditor().getScrollingModel().scrollToCaret(ScrollType.CENTER_UP);
}
);
}
public void log(@Nullable String text) {
Logger.getInstance(JavaPanelBridge.class).warn(text);
}
}
/* keep bridge in class instance to avoid cleanup of bridge due to weak references in
JavaScript mappings starting from JDK 8 111
see: https://bugs.openjdk.java.net/browse/JDK-8170515
*/
private JavaPanelBridge bridge = new JavaPanelBridge();
private class BridgeSettingListener implements ChangeListener<State> {
@Override
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
if (newValue == State.SUCCEEDED) {
JSObject win
= (JSObject) getWebViewGuaranteed().getEngine().executeScript("window");
win.setMember("JavaPanelBridge", bridge);
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().executeScript(
"if ('__IntelliJTools' in window) {" +
"__IntelliJTools.processLinks && __IntelliJTools.processLinks();" +
"__IntelliJTools.pickSourceLine && __IntelliJTools.pickSourceLine(" + lineCount + ", " + offset + ");" +
"}"
);
}
}
}
private class ScrollPreservingListener implements ChangeListener<State> {
private volatile int myScrollY = 0;
@Override
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
if (newValue == State.RUNNING) {
final Object result =
getWebViewGuaranteed().getEngine().executeScript("document.documentElement.scrollTop || document.body.scrollTop");
if (result instanceof Number) {
myScrollY = ((Number) result).intValue();
}
} else if (newValue == State.SUCCEEDED) {
getWebViewGuaranteed().getEngine()
.executeScript("document.documentElement.scrollTop = document.body.scrollTop = " + myScrollY);
}
}
}
}
|
src/main/java/org/asciidoc/intellij/editor/javafx/JavaFxHtmlPanel.java
|
package org.asciidoc.intellij.editor.javafx;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.actions.OpenFileAction;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.ide.projectView.impl.ProjectViewPane;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.CaretState;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.fileChooser.FileChooserFactory;
import com.intellij.openapi.fileChooser.FileSaverDescriptor;
import com.intellij.openapi.fileChooser.FileSaverDialog;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileWrapper;
import com.intellij.ui.JBColor;
import com.intellij.util.PsiNavigateUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.sun.javafx.application.PlatformImpl;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker.State;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.text.FontSmoothingType;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import netscape.javascript.JSObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.asciidoc.intellij.editor.AsciiDocHtmlPanel;
import org.asciidoc.intellij.editor.AsciiDocHtmlPanelProvider;
import org.asciidoc.intellij.editor.AsciiDocPreviewEditor;
import org.asciidoc.intellij.psi.AsciiDocBlockId;
import org.asciidoc.intellij.psi.AsciiDocUtil;
import org.asciidoc.intellij.settings.AsciiDocApplicationSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.w3c.dom.html.HTMLImageElement;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaFxHtmlPanel extends AsciiDocHtmlPanel {
private Logger log = Logger.getInstance(JavaFxHtmlPanel.class);
private static final NotNullLazyValue<String> MY_SCRIPTING_LINES = new NotNullLazyValue<String>() {
@NotNull
@Override
protected String compute() {
final Class<JavaFxHtmlPanel> clazz = JavaFxHtmlPanel.class;
//noinspection StringBufferReplaceableByString
return new StringBuilder()
.append("<script src=\"").append(PreviewStaticServer.getScriptUrl("scrollToElement.js")).append("\"></script>\n")
.append("<script src=\"").append(PreviewStaticServer.getScriptUrl("processLinks.js")).append("\"></script>\n")
.append("<script src=\"").append(PreviewStaticServer.getScriptUrl("pickSourceLine.js")).append("\"></script>\n")
.append("<script type=\"text/x-mathjax-config\">\n" +
"MathJax.Hub.Config({\n" +
" messageStyle: \"none\",\n" +
" EqnChunkDelay: 1," +
" tex2jax: {\n" +
" inlineMath: [[\"\\\\(\", \"\\\\)\"]],\n" +
" displayMath: [[\"\\\\[\", \"\\\\]\"]],\n" +
" ignoreClass: \"nostem|nolatexmath\"\n" +
" },\n" +
" asciimath2jax: {\n" +
" delimiters: [[\"\\\\$\", \"\\\\$\"]],\n" +
" ignoreClass: \"nostem|noasciimath\"\n" +
" },\n" +
" TeX: { equationNumbers: { autoNumber: \"none\" } }\n" +
"});\n" +
"MathJax.Hub.Register.MessageHook(\"Math Processing Error\",function (message) {\n" +
" window.JavaPanelBridge && window.JavaPanelBridge.log(JSON.stringify(message)); \n" +
"});" +
"MathJax.Hub.Register.MessageHook(\"TeX Jax - parse error\",function (message) {\n" +
" var errortext = document.getElementById('mathjaxerrortext'); " +
" var errorformula = document.getElementById('mathjaxerrorformula'); " +
" if (errorformula && errortext) { " +
" errortext.textContent = 'Math Formula problem: ' + message[1]; " +
" errorformula.textContent = '\\n' + message[2]; " +
" } " +
" window.JavaPanelBridge && window.JavaPanelBridge.log(JSON.stringify(message)); \n" +
"});" +
"</script>\n")
.append("<script src=\"").append(PreviewStaticServer.getScriptUrl("MathJax/MathJax.js")).append("&config=TeX-MML-AM_HTMLorMML\"></script>\n")
.toString();
}
};
@NotNull
private final JPanel myPanelWrapper;
@NotNull
private final List<Runnable> myInitActions = new ArrayList<>();
@Nullable
private volatile JFXPanel myPanel;
@Nullable
private WebView myWebView;
@Nullable
private String myInlineCss;
@Nullable
private String myInlineCssDarcula;
@Nullable
private String myFontAwesomeCssLink;
@Nullable
private String myDejavuCssLink;
@NotNull
private final ScrollPreservingListener myScrollPreservingListener = new ScrollPreservingListener();
@NotNull
private final BridgeSettingListener myBridgeSettingListener = new BridgeSettingListener();
@NotNull
private String base;
private int lineCount;
private int offset;
private final Path imagesPath;
private VirtualFile parentDirectory;
private VirtualFile saveImageLastDir = null;
private volatile CountDownLatch rendered;
JavaFxHtmlPanel(Document document, Path imagesPath) {
//System.setProperty("prism.lcdtext", "false");
//System.setProperty("prism.text", "t2k");
this.imagesPath = imagesPath;
myPanelWrapper = new JPanel(new BorderLayout());
myPanelWrapper.setBackground(JBColor.background());
lineCount = document.getLineCount();
VirtualFile file = FileDocumentManager.getInstance().getFile(document);
if (file != null) {
parentDirectory = file.getParent();
}
if (parentDirectory != null) {
// parent will be null if we use Language Injection and Fragment Editor
base = parentDirectory.getUrl().replaceAll("^file://", "")
.replaceAll(":", "%3A");
} else {
base = "";
}
try {
Properties p = new Properties();
p.load(JavaFxHtmlPanel.class.getResourceAsStream("/META-INF/asciidoctorj-version.properties"));
String asciidoctorVersion = p.getProperty("version.asciidoctor");
myInlineCss = IOUtils.toString(JavaFxHtmlPanel.class.getResourceAsStream("/gems/asciidoctor-"
+ asciidoctorVersion
+ "/data/stylesheets/asciidoctor-default.css"));
// asian characters won't display with text-rendering:optimizeLegibility
// https://github.com/asciidoctor/asciidoctor-intellij-plugin/issues/203
myInlineCss = myInlineCss.replaceAll("text-rendering:", "disabled-text-rendering");
// JavaFX doesn't load 'DejaVu Sans Mono' font when 'Droid Sans Mono' is listed first
// https://github.com/asciidoctor/asciidoctor-intellij-plugin/issues/193
myInlineCss = myInlineCss.replaceAll("(\"Noto Serif\"|\"Open Sans\"|\"Droid Sans Mono\"),", "");
myInlineCssDarcula = myInlineCss + IOUtils.toString(JavaFxHtmlPanel.class.getResourceAsStream("darcula.css"));
myInlineCssDarcula += IOUtils.toString(JavaFxHtmlPanel.class.getResourceAsStream("coderay-darcula.css"));
myInlineCss += IOUtils.toString(JavaFxHtmlPanel.class.getResourceAsStream("/gems/asciidoctor-"
+ asciidoctorVersion
+ "/data/stylesheets/coderay-asciidoctor.css"));
myFontAwesomeCssLink = "<link rel=\"stylesheet\" href=\"" + PreviewStaticServer.getStyleUrl("font-awesome/css/font-awesome.min.css") + "\">";
myDejavuCssLink = "<link rel=\"stylesheet\" href=\"" + PreviewStaticServer.getStyleUrl("dejavu/dejavu.css") + "\">";
} catch (IOException e) {
String message = "Unable to combine CSS resources: " + e.getMessage();
log.error(message, e);
Notification notification = AsciiDocPreviewEditor.NOTIFICATION_GROUP
.createNotification("Error rendering asciidoctor", message, NotificationType.ERROR, null);
// increase event log counter
notification.setImportant(true);
Notifications.Bus.notify(notification);
}
ApplicationManager.getApplication().invokeLater(() -> runFX(new Runnable() {
@Override
public void run() {
if (new JavaFxHtmlPanelProvider().isAvailable() == AsciiDocHtmlPanelProvider.AvailabilityInfo.UNAVAILABLE) {
String message = "JavaFX unavailable, probably stuck";
log.warn(message);
return;
}
try {
PlatformImpl.startup(() -> {
myWebView = new WebView();
updateFontSmoothingType(myWebView, false);
registerContextMenu(JavaFxHtmlPanel.this.myWebView);
myWebView.setContextMenuEnabled(false);
myWebView.setZoom(JBUI.scale(1.f));
myWebView.getEngine().loadContent(prepareHtml("<html><head></head><body>Initializing...</body>"));
myWebView.addEventFilter(ScrollEvent.SCROLL, scrollEvent -> {
// touch pads send lots of events with deltaY == 0, not handling them here
if (scrollEvent.isControlDown() && Double.compare(scrollEvent.getDeltaY(), 0.0) != 0) {
double zoom = myWebView.getZoom();
double factor = (scrollEvent.getDeltaY() > 0.0 ? 0.1 : -0.1)
// normalize scrolling
* (Math.abs(scrollEvent.getDeltaY()) / scrollEvent.getMultiplierY())
// adding one to make it a factor that we can multiply the zoom by
+ 1;
zoom = zoom * factor;
// define minimum/maximum zoom
if (zoom < JBUI.scale(0.1f)) {
zoom = 0.1;
} else if (zoom > JBUI.scale(10.f)) {
zoom = 10;
}
myWebView.setZoom(zoom);
scrollEvent.consume();
}
});
myWebView.addEventFilter(MouseEvent.MOUSE_CLICKED, mouseEvent -> {
if (mouseEvent.isControlDown() && mouseEvent.getButton() == MouseButton.MIDDLE) {
myWebView.setZoom(JBUI.scale(1f));
mouseEvent.consume();
}
});
final WebEngine engine = myWebView.getEngine();
engine.getLoadWorker().stateProperty().addListener(myBridgeSettingListener);
engine.getLoadWorker().stateProperty().addListener(myScrollPreservingListener);
final Scene scene = new Scene(myWebView);
ApplicationManager.getApplication().invokeLater(() -> runFX(() -> {
try {
synchronized (myInitActions) {
myPanel = new JFXPanelWrapper();
Platform.runLater(() -> myPanel.setScene(scene));
for (Runnable action : myInitActions) {
Platform.runLater(action);
}
myInitActions.clear();
}
myPanelWrapper.add(myPanel, BorderLayout.CENTER);
myPanelWrapper.repaint();
} catch (Throwable e) {
log.warn("can't initialize JFXPanelWrapper", e);
}
}));
});
} catch (Throwable ex) {
String message = "Error initializing JavaFX: " + ex.getMessage();
log.error(message, ex);
Notification notification = AsciiDocPreviewEditor.NOTIFICATION_GROUP.createNotification("Error rendering asciidoctor", message,
NotificationType.ERROR, null);
// increase event log counter
notification.setImportant(true);
Notifications.Bus.notify(notification);
}
}
}));
}
private void registerContextMenu(WebView webView) {
webView.setOnMousePressed(e -> {
if (e.getButton() == MouseButton.SECONDARY) {
JSObject object = getJavaScriptObjectAtLocation(webView, e);
if (object instanceof HTMLImageElement) {
String src = ((HTMLImageElement) object).getAttribute("src");
ApplicationManager.getApplication().invokeLater(() -> saveImage(src));
}
}
});
}
private JSObject getJavaScriptObjectAtLocation(WebView webView, MouseEvent e) {
String script = String.format("document.elementFromPoint(%s,%s);", e.getX(), e.getY());
return (JSObject) webView.getEngine().executeScript(script);
}
private void saveImage(@NotNull String path) {
String parent = imagesPath.getFileName().toString();
String subPath = path.substring(path.indexOf(parent) + parent.length() + 1);
Path imagePath = imagesPath.resolve(subPath);
if (imagePath.toFile().exists()) {
File file = imagePath.toFile();
String fileName = imagePath.getFileName().toString();
ArrayList<String> extensions = new ArrayList<>();
int lastDotIndex = fileName.lastIndexOf('.');
if (lastDotIndex > 0 && !fileName.endsWith(".")) {
extensions.add(fileName.substring(lastDotIndex + 1));
}
// set static file name if image name has been generated dynamically
final String fileNameNoExt;
if (fileName.matches("diag-[0-9a-f]{32}\\.[a-z]+")) {
fileNameNoExt = "image";
} else {
fileNameNoExt = lastDotIndex > 0 ? fileName.substring(0, lastDotIndex) : fileName;
}
// check if also a SVG exists for the provided PNG
if (extensions.contains("png") &&
new File(file.getParent(), fileNameNoExt + ".svg").exists()) {
extensions.add("svg");
}
final FileSaverDescriptor descriptor = new FileSaverDescriptor("Export Image to", "Choose the destination file",
extensions.toArray(new String[]{}));
FileSaverDialog saveFileDialog = FileChooserFactory.getInstance().createSaveFileDialog(descriptor, (Project) null);
VirtualFile baseDir = saveImageLastDir;
if (baseDir == null) {
baseDir = parentDirectory;
}
VirtualFile finalBaseDir = baseDir;
SwingUtilities.invokeLater(() -> {
VirtualFileWrapper destination = saveFileDialog.save(finalBaseDir, fileNameNoExt);
if (destination != null) {
try {
saveImageLastDir = LocalFileSystem.getInstance().findFileByIoFile(destination.getFile().getParentFile());
Path src = imagePath;
// if the destination ends with .svg, but the source doesn't, patch the source file name as the user chose a different file type
if (destination.getFile().getAbsolutePath().endsWith(".svg") && !src.endsWith(".svg")) {
src = new File(src.toFile().getAbsolutePath().replaceAll("\\.png$", ".svg")).toPath();
}
Files.copy(src, destination.getFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
String message = "Can't save file: " + ex.getMessage();
Notification notification = AsciiDocPreviewEditor.NOTIFICATION_GROUP
.createNotification("Error in plugin", message, NotificationType.ERROR, null);
// increase event log counter
notification.setImportant(true);
Notifications.Bus.notify(notification);
}
}
});
}
}
private static void runFX(@NotNull Runnable r) {
IdeEventQueue.unsafeNonblockingExecute(r);
}
private void runInPlatformWhenAvailable(@NotNull final Runnable runnable) {
synchronized (myInitActions) {
if (myPanel == null) {
myInitActions.add(runnable);
} else {
Platform.runLater(runnable);
}
}
}
private boolean isDarcula() {
final AsciiDocApplicationSettings settings = AsciiDocApplicationSettings.getInstance();
switch (settings.getAsciiDocPreviewSettings().getPreviewTheme()) {
case INTELLIJ:
return UIUtil.isUnderDarcula();
case ASCIIDOC:
return false;
case DARCULA:
return true;
default:
return false;
}
}
private static void updateFontSmoothingType(@NotNull WebView view, boolean isGrayscale) {
final FontSmoothingType typeToSet;
if (isGrayscale) {
typeToSet = FontSmoothingType.GRAY;
} else {
typeToSet = FontSmoothingType.LCD;
}
view.fontSmoothingTypeProperty().setValue(typeToSet);
}
@NotNull
@Override
public JComponent getComponent() {
return myPanelWrapper;
}
@Override
public void setHtml(@NotNull String htmlParam) {
rendered = new CountDownLatch(1);
runInPlatformWhenAvailable(() -> {
String html = htmlParam;
if (isDarcula()) {
// clear out coderay inline CSS colors as they are barely readable in darcula theme
html = html.replaceAll("<span style=\"color:#[a-zA-Z0-9]*;?", "<span style=\"");
html = html.replaceAll("<span style=\"background-color:#[a-zA-Z0-9]*;?", "<span style=\"");
}
boolean result = false;
final AsciiDocApplicationSettings settings = AsciiDocApplicationSettings.getInstance();
if (settings.getAsciiDocPreviewSettings().isInplacePreviewRefresh() && html.contains("id=\"content\"")) {
final String htmlToReplace = StringEscapeUtils.escapeEcmaScript(prepareHtml(html));
// try to replace the HTML contents using JavaScript to avoid flickering MathML
try {
result = (Boolean) JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().executeScript(
"function finish() {" +
"if ('__IntelliJTools' in window) {" +
"__IntelliJTools.processLinks && __IntelliJTools.processLinks();" +
"__IntelliJTools.pickSourceLine && __IntelliJTools.pickSourceLine(" + lineCount + ", " + offset + ");" +
"}" +
"window.JavaPanelBridge && window.JavaPanelBridge.rendered();" +
"}" +
"function updateContent() { var elem = document.getElementById('content'); if (elem && elem.parentNode) { " +
"var div = document.createElement('div');" +
"div.innerHTML = '" + htmlToReplace + "'; " +
" var errortext = document.getElementById('mathjaxerrortext'); " +
" var errorformula = document.getElementById('mathjaxerrorformula'); " +
" if (errorformula && errortext) { " +
" errortext.textContent = '' " +
" errorformula.textContent = '' " +
" } " +
"div.style.cssText = 'display: none'; " +
// need to add the element to the DOM as MathJAX will use document.getElementById in some places
"elem.appendChild(div); " +
// use MathJax to set the formulas in advance if formulas are present - this takes ~100ms
// re-evaluate the content element as it might have been replaced by a concurrent rendering
"if ('MathJax' in window && MathJax.Hub.getAllJax().length > 0) { MathJax.Hub.Typeset(div.firstChild, function() { var elem2 = document.getElementById('content'); elem2.parentNode.replaceChild(div.firstChild, elem2); finish(); }); } " +
// if no math was present before, replace contents, and do the MathJax typesetting afterwards in case Math has been added
"else { elem.parentNode.replaceChild(div.firstChild, elem); MathJax.Hub.Typeset(div.firstChild); finish(); } " +
"return true; } else { return false; }}; updateContent();"
);
} catch (RuntimeException e) {
// might happen when rendered output is not valid HTML due to passtrough content
log.warn("unable to use JavaScript for update", e);
}
}
// if not successful using JavaScript (like on first rendering attempt), set full content
if (!result) {
html = "<html><head></head><body><div style='position:fixed;top:0;left:0;background-color:#eeeeee;color:red;z-index:99;'><div id='mathjaxerrortext'></div><pre style='color:red' id='mathjaxerrorformula'></pre></div>" + html + "</body>";
final String htmlToRender = prepareHtml(html);
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().loadContent(htmlToRender);
rendered.countDown();
}
});
try {
// slow down the rendering of the next version of the preview until the rendering if the current version is complete
// this prevents us building up a queue that would lead to a lagging preview
rendered.await(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.warn("rendering didn't complete in time, might be slow or broken");
}
}
private String findTempImageFile(String filename) {
Path file = imagesPath.resolve(filename);
if (Files.exists(file)) {
return file.toFile().toString();
}
return null;
}
private String prepareHtml(@NotNull String html) {
/* for each image we'll calculate a MD5 sum of its content. Once the content changes, MD5 and therefore the URL
* will change. The changed URL is necessary for the JavaFX web view to display the new content, as each URL
* will be loaded only once by the JavaFX web view. */
Pattern pattern = Pattern.compile("<img src=\"([^:\"]*)\"");
final Matcher matcher = pattern.matcher(html);
while (matcher.find()) {
final MatchResult matchResult = matcher.toMatchResult();
String file = matchResult.group(1);
String tmpFile = findTempImageFile(file);
String md5;
String replacement;
if (tmpFile != null) {
md5 = calculateMd5(tmpFile, null);
tmpFile = tmpFile.replaceAll("\\\\", "/");
tmpFile = tmpFile.replaceAll(":", "%3A");
if (JavaFxHtmlPanelProvider.isInitialized()) {
replacement = "<img src=\"localfile://" + md5 + "/" + tmpFile + "\"";
} else {
replacement = "<img src=\"file://" + tmpFile.replaceAll("%3A", ":") + "\"";
}
} else {
md5 = calculateMd5(file, base);
if (JavaFxHtmlPanelProvider.isInitialized()) {
replacement = "<img src=\"localfile://" + md5 + "/" + base + "/" + file + "\"";
} else {
replacement = "<img src=\"file://" + base.replaceAll("%3A", ":") + "/" + file + "\"";
}
}
html = html.substring(0, matchResult.start()) +
replacement + html.substring(matchResult.end());
matcher.reset(html);
}
// filter out Twitter's JavaScript, as it is problematic for JDK8 JavaFX
// see: https://github.com/asciidoctor/asciidoctor-intellij-plugin/issues/235
html = html.replaceAll("(?i)<script [a-z ]*src=\"https://platform\\.twitter\\.com/widgets\\.js\" [^>]*></script>", "");
/* Add CSS line and JavaScript for auto-scolling and clickable links */
return html
.replace("<head>", "<head>" + getCssLines(isDarcula() ? myInlineCssDarcula : myInlineCss) + myFontAwesomeCssLink + myDejavuCssLink)
.replace("</body>", getScriptingLines() + "</body>");
}
private String calculateMd5(String file, String base) {
String md5;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
try (FileInputStream fis = new FileInputStream((base != null ? base.replaceAll("%3A", ":") + "/" : "") + file)) {
int nread;
byte[] dataBytes = new byte[1024];
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
}
}
byte[] mdbytes = md.digest();
StringBuilder sb = new StringBuilder();
for (byte mdbyte : mdbytes) {
sb.append(Integer.toString((mdbyte & 0xff) + 0x100, 16).substring(1));
}
md5 = sb.toString();
} catch (NoSuchAlgorithmException | IOException e) {
md5 = "none";
}
return md5;
}
@Override
public void render() {
runInPlatformWhenAvailable(() -> {
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().reload();
ApplicationManager.getApplication().invokeLater(myPanelWrapper::repaint);
});
}
@Override
public void scrollToLine(final int line, final int lineCount) {
this.lineCount = lineCount;
runInPlatformWhenAvailable(() -> {
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().executeScript(
"if ('__IntelliJTools' in window) " +
"__IntelliJTools.scrollToLine(" + line + ", " + lineCount + ");"
);
final Object result = JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().executeScript(
"document.documentElement.scrollTop || document.body.scrollTop");
if (result instanceof Number) {
myScrollPreservingListener.myScrollY = ((Number) result).intValue();
}
});
}
@Override
public void dispose() {
runInPlatformWhenAvailable(() -> {
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().load("about:blank");
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().getLoadWorker().stateProperty().removeListener(myScrollPreservingListener);
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().getLoadWorker().stateProperty().removeListener(myBridgeSettingListener);
});
}
@NotNull
private WebView getWebViewGuaranteed() {
if (myWebView == null) {
throw new IllegalStateException("WebView should be initialized by now. Check the caller thread");
}
return myWebView;
}
@NotNull
private static String getScriptingLines() {
return MY_SCRIPTING_LINES.getValue();
}
@SuppressWarnings("unused")
public class JavaPanelBridge {
public void openLink(@NotNull String link) {
final URI uri;
try {
uri = new URI(link);
} catch (URISyntaxException ex) {
throw new RuntimeException("unable to parse URL " + link);
}
String scheme = uri.getScheme();
if ("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme) || "mailto".equalsIgnoreCase(scheme)) {
BrowserUtil.browse(uri);
} else if ("file".equalsIgnoreCase(scheme) || scheme == null) {
openInEditor(uri);
} else {
log.warn("won't open URI as it might be unsafe: " + uri);
}
}
public void rendered() {
rendered.countDown();
}
private boolean openInEditor(@NotNull URI uri) {
return ReadAction.compute(() -> {
String anchor = uri.getFragment();
String path = uri.getPath();
final VirtualFile targetFile;
VirtualFile tmpTargetFile = parentDirectory.findFileByRelativePath(path);
if (tmpTargetFile == null) {
// extension might be skipped if it is an .adoc file
tmpTargetFile = parentDirectory.findFileByRelativePath(path + ".adoc");
}
if (tmpTargetFile == null && path.endsWith(".html")) {
// might link to a .html in the rendered output, but might actually be a .adoc file
tmpTargetFile = parentDirectory.findFileByRelativePath(path.replaceAll("\\.html$", ".adoc"));
}
if (tmpTargetFile == null) {
log.warn("unable to find file for " + uri);
return false;
}
targetFile = tmpTargetFile;
Project project = ProjectUtil.guessProjectForContentFile(targetFile);
if (project == null) {
log.warn("unable to find project for " + uri);
return false;
}
if (targetFile.isDirectory()) {
ProjectView projectView = ProjectView.getInstance(project);
projectView.changeView(ProjectViewPane.ID);
projectView.select(null, targetFile, true);
} else {
boolean anchorFound = false;
if (anchor != null) {
List<AsciiDocBlockId> ids = AsciiDocUtil.findIds(project, targetFile, anchor);
if (!ids.isEmpty()) {
anchorFound = true;
ApplicationManager.getApplication().invokeLater(() -> PsiNavigateUtil.navigate(ids.get(0)));
}
}
if (!anchorFound) {
ApplicationManager.getApplication().invokeLater(() -> OpenFileAction.openFile(targetFile, project));
}
}
return true;
});
}
public void scrollEditorToLine(int sourceLine) {
if (sourceLine <= 0) {
Notification notification = AsciiDocPreviewEditor.NOTIFICATION_GROUP.createNotification("Setting cursor position", "line number " + sourceLine + " requested for cursor position, ignoring",
NotificationType.INFORMATION, null);
notification.setImportant(false);
return;
}
ApplicationManager.getApplication().invokeLater(
() -> {
getEditor().getCaretModel().setCaretsAndSelections(
Collections.singletonList(new CaretState(new LogicalPosition(sourceLine - 1, 0), null, null))
);
getEditor().getScrollingModel().scrollToCaret(ScrollType.CENTER_UP);
}
);
}
public void log(@Nullable String text) {
Logger.getInstance(JavaPanelBridge.class).warn(text);
}
}
/* keep bridge in class instance to avoid cleanup of bridge due to weak references in
JavaScript mappings starting from JDK 8 111
see: https://bugs.openjdk.java.net/browse/JDK-8170515
*/
private JavaPanelBridge bridge = new JavaPanelBridge();
private class BridgeSettingListener implements ChangeListener<State> {
@Override
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
if (newValue == State.SUCCEEDED) {
JSObject win
= (JSObject) getWebViewGuaranteed().getEngine().executeScript("window");
win.setMember("JavaPanelBridge", bridge);
JavaFxHtmlPanel.this.getWebViewGuaranteed().getEngine().executeScript(
"if ('__IntelliJTools' in window) {" +
"__IntelliJTools.processLinks && __IntelliJTools.processLinks();" +
"__IntelliJTools.pickSourceLine && __IntelliJTools.pickSourceLine(" + lineCount + ", " + offset + ");" +
"}"
);
}
}
}
private class ScrollPreservingListener implements ChangeListener<State> {
private volatile int myScrollY = 0;
@Override
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
if (newValue == State.RUNNING) {
final Object result =
getWebViewGuaranteed().getEngine().executeScript("document.documentElement.scrollTop || document.body.scrollTop");
if (result instanceof Number) {
myScrollY = ((Number) result).intValue();
}
} else if (newValue == State.SUCCEEDED) {
getWebViewGuaranteed().getEngine()
.executeScript("document.documentElement.scrollTop = document.body.scrollTop = " + myScrollY);
}
}
}
}
|
fixing javascript error that produced flicker (#326)
|
src/main/java/org/asciidoc/intellij/editor/javafx/JavaFxHtmlPanel.java
|
fixing javascript error that produced flicker (#326)
|
|
Java
|
apache-2.0
|
e90522e1b37525658756802f4589bacab2b25b29
| 0
|
lenworthrose/music-app,treejames/music-app
|
package com.lenworthrose.music.fragment;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PaintDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewPropertyAnimator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.lenworthrose.music.R;
import com.lenworthrose.music.activity.PlayingNowActivity;
import com.lenworthrose.music.playback.PlaybackService;
import com.lenworthrose.music.util.Constants;
import com.lenworthrose.music.util.Constants.PlaybackState;
import com.lenworthrose.music.util.Utils;
/**
* This Fragment displays information about the currently playing track (Artist, Album, Title, Cover
* Art, etc). It also provides playback controls (Play/Pause, Next, Previous, Stop).
*/
public class PlayingItemFragment extends Fragment implements ServiceConnection {
private SeekBar positionBar;
private TextView artist, album, title, playlistPosition, playlistTracks, positionDisplay, durationDisplay;
private ImageView coverArt, playPause;
private View artistAlbumContainer, topDetailContainer, bottomDetailContainer;
private boolean isPositionBarTouched, autoHideOverlays;
private boolean areOverlaysVisible = true;
private Animation pauseBlinkAnimation = new AlphaAnimation(0f, 1f);
private PlaybackService playbackService;
private MenuItem repeatItem;
private boolean isRepeatEnabled;
private Handler positionHandler, overlayHandler;
private int position;
private boolean isActivityTransitionDone;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case Constants.PLAYING_NOW_CHANGED:
playingItemChanged(intent);
break;
case Constants.PLAYBACK_STATE_CHANGED:
playbackStateChanged(intent);
break;
case Constants.PLAYING_NOW_PLAYLIST_CHANGED:
playlistUpdated();
break;
}
}
};
private SeekBar.OnSeekBarChangeListener seekListener = new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
isPositionBarTouched = false;
positionDisplay.setText(Utils.longToTimeDisplay(seekBar.getProgress()));
playbackService.seek(seekBar.getProgress());
scheduleHideOverlays();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
isPositionBarTouched = true;
if (autoHideOverlays) {
setOverlaysVisible(true);
cancelHideOverlays();
}
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) positionDisplay.setText(Utils.longToTimeDisplay(progress));
}
};
private View.OnClickListener playbackButtonClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.pn_previous:
playbackService.previous();
break;
case R.id.pn_play_pause:
playbackService.playPause();
break;
case R.id.pn_stop:
playbackService.stop();
break;
case R.id.pn_next:
playbackService.next();
break;
}
}
};
private View.OnClickListener coverArtClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
cancelHideOverlays();
setOverlaysVisible(!areOverlaysVisible);
if (areOverlaysVisible) scheduleHideOverlays();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
autoHideOverlays = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(Constants.SETTING_AUTO_HIDE_PLAYING_NOW_OVERLAYS, false);
positionHandler = new Handler(Looper.getMainLooper());
overlayHandler = new Handler(Looper.getMainLooper());
setHasOptionsMenu(true);
pauseBlinkAnimation.setDuration(375);
pauseBlinkAnimation.setStartOffset(250);
pauseBlinkAnimation.setRepeatCount(Animation.INFINITE);
pauseBlinkAnimation.setRepeatMode(Animation.REVERSE);
setHasOptionsMenu(true); //Required for the system to call onCreateOptionsMenu() to get the Repeat MenuItem
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_playing_item, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
topDetailContainer = view.findViewById(R.id.pn_top_detail_container);
artistAlbumContainer = topDetailContainer.findViewById(R.id.pn_artist_album_container);
artist = (TextView)artistAlbumContainer.findViewById(R.id.pn_artist);
album = (TextView)artistAlbumContainer.findViewById(R.id.pn_album);
title = (TextView)topDetailContainer.findViewById(R.id.pn_name);
bottomDetailContainer = view.findViewById(R.id.pn_bottom_detail_container);
playlistPosition = (TextView)bottomDetailContainer.findViewById(R.id.pn_playlist_position);
playlistTracks = (TextView)bottomDetailContainer.findViewById(R.id.pn_playlist_tracks);
positionDisplay = (TextView)bottomDetailContainer.findViewById(R.id.pn_position_display);
durationDisplay = (TextView)bottomDetailContainer.findViewById(R.id.pn_duration);
positionBar = (SeekBar)bottomDetailContainer.findViewById(R.id.pn_position_seekbar);
positionBar.setOnSeekBarChangeListener(seekListener);
positionBar.setEnabled(false);
coverArt = (ImageView)view.findViewById(R.id.pn_coverArt);
coverArt.setOnClickListener(coverArtClickListener);
View playbackControlContainer = view.findViewById(R.id.pn_playback_control_container);
playPause = (ImageView)playbackControlContainer.findViewById(R.id.pn_play_pause);
playPause.setOnClickListener(playbackButtonClickListener);
playbackControlContainer.findViewById(R.id.pn_previous).setOnClickListener(playbackButtonClickListener);
playbackControlContainer.findViewById(R.id.pn_next).setOnClickListener(playbackButtonClickListener);
playbackControlContainer.findViewById(R.id.pn_stop).setOnClickListener(playbackButtonClickListener);
ShapeDrawable.ShaderFactory topShaderFactory = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
return new LinearGradient(0, height, 0, 0,
new int[] { 0x00090909, 0x29090909, 0x49090909, 0x69090909, 0x7C090909, 0x8A090909, 0x9D090909, 0xB2090909 },
new float[] { 0f, .023f, .039f, .056f, .080f, .110f, .165f, 1f },
Shader.TileMode.CLAMP);
}
};
PaintDrawable topBackground = new PaintDrawable();
topBackground.setShape(new RectShape());
topBackground.setShaderFactory(topShaderFactory);
topDetailContainer.setBackground(topBackground);
ShapeDrawable.ShaderFactory bottomShaderFactory = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
return new LinearGradient(0, 0, 0, height,
new int[] { 0x00090909, 0x4D090909, 0x69090909, 0x72090909, 0x76090909, 0x79090909, 0x87090909, 0x93090909, 0xA6090909, 0xB2090909 },
new float[] { 0f, .040f, .064f, .083f, .090f, .095f, .12f, .15f, .2f, 1f },
Shader.TileMode.CLAMP);
}
};
PaintDrawable bottomBackground = new PaintDrawable();
bottomBackground.setShape(new RectShape());
bottomBackground.setShaderFactory(bottomShaderFactory);
bottomDetailContainer.setBackground(bottomBackground);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
repeatItem = menu.findItem(R.id.action_repeat);
repeatItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(getActivity(), PlaybackService.class);
intent.setAction(Constants.CMD_TOGGLE_REPEAT_MODE);
getActivity().startService(intent);
isRepeatEnabled = !isRepeatEnabled;
onRepeatToggled();
return true;
}
});
onRepeatToggled();
}
@Override
public void onResume() {
super.onResume();
getActivity().bindService(new Intent(getActivity(), PlaybackService.class), this, Context.BIND_AUTO_CREATE);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(broadcastReceiver, Utils.createPlaybackIntentFilter());
}
@Override
public void onPause() {
cancelHideOverlays();
positionHandler.removeCallbacksAndMessages(null);
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcastReceiver);
getActivity().unbindService(this);
super.onPause();
}
private void playingItemChanged(Intent intent) {
positionHandler.removeCallbacksAndMessages(null);
if (isDetached() || playbackService == null) return;
if (autoHideOverlays && isActivityTransitionDone) setOverlaysVisible(true);
artist.setText(intent.getStringExtra(Constants.EXTRA_ARTIST));
album.setText(intent.getStringExtra(Constants.EXTRA_ALBUM));
title.setText(intent.getStringExtra(Constants.EXTRA_TITLE));
if (!playbackService.isPlaylistEmpty()) {
playlistPosition.setText(String.valueOf(intent.getIntExtra(Constants.EXTRA_PLAYLIST_POSITION, 0)));
playlistTracks.setText(String.valueOf(intent.getIntExtra(Constants.EXTRA_PLAYLIST_TOTAL_TRACKS, 0)));
positionDisplay.setText(R.string.blank_time);
coverArt.animate().alpha(0.08f).setDuration(75);
Glide.with(this).load(intent.getStringExtra(Constants.EXTRA_ALBUM_ART_URL)).asBitmap().into(new CoverArtTarget());
} else {
resetToLogo();
positionBar.setEnabled(false);
positionBar.setProgress(0);
playlistPosition.setText("0");
playlistTracks.setText("0");
}
artistAlbumContainer.setVisibility(artist.getText().toString().isEmpty() && album.getText().toString().isEmpty() ? View.GONE : View.VISIBLE);
}
private void playbackStateChanged(Intent intent) {
positionHandler.removeCallbacksAndMessages(null);
if (isDetached() || playbackService == null) return;
PlaybackState state = (PlaybackState)intent.getSerializableExtra(Constants.EXTRA_STATE);
playPause.setImageResource(R.drawable.play);
int duration = intent.getIntExtra(Constants.EXTRA_DURATION, -1);
switch (state) {
case BUFFERING:
positionDisplay.clearAnimation();
positionBar.setEnabled(false);
playPause.setAlpha(.3f);
playPause.setImageResource(R.drawable.play);
playPause.setEnabled(false);
break;
case PLAYING:
positionDisplay.clearAnimation();
durationDisplay.setText(Utils.longToTimeDisplay(duration));
positionBar.setMax(duration);
playPause.setAlpha(1f);
playPause.setImageResource(R.drawable.pause);
playPause.setEnabled(true);
scheduleHideOverlays();
updatePosition(intent.getIntExtra(Constants.EXTRA_POSITION, 0));
positionHandler.postDelayed(new UpdatePositionRunnable(), 1000);
break;
case PAUSED:
positionDisplay.startAnimation(pauseBlinkAnimation);
durationDisplay.setText(Utils.longToTimeDisplay(duration));
positionBar.setMax(duration);
updatePosition(intent.getIntExtra(Constants.EXTRA_POSITION, 0));
break;
case STOPPED:
positionDisplay.setText(R.string.blank_time);
durationDisplay.setText(R.string.blank_time);
positionBar.setProgress(0);
positionBar.setEnabled(false);
playPause.setEnabled(true);
playPause.setAlpha(1f);
positionDisplay.clearAnimation();
break;
}
if (state != PlaybackState.PLAYING) {
cancelHideOverlays();
if (isActivityTransitionDone) setOverlaysVisible(true);
}
}
private void playlistUpdated() {
if (isDetached() || playbackService == null) return;
if (!playbackService.isPlaylistEmpty()) {
playlistPosition.setText(String.valueOf(playbackService.getPlaylistPositionForDisplay()));
playlistTracks.setText(String.valueOf(playbackService.getPlaylistSize()));
} else {
playlistPosition.setText("0");
playlistTracks.setText("0");
}
}
private void resetToLogo() {
if (!isActivityTransitionDone) {
startEnterTransition();
isActivityTransitionDone = true;
}
coverArt.setAlpha(.1f);
coverArt.setImageResource(R.drawable.logo);
if (getActivity() instanceof PlayingNowActivity)
((PlayingNowActivity)getActivity()).setBackgroundImage(null);
}
private void updatePosition(int position) {
this.position = position;
if (!isPositionBarTouched) {
positionBar.setProgress(position);
positionBar.setEnabled(true);
positionDisplay.setText(Utils.longToTimeDisplay(position));
}
}
private void startEnterTransition() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) getActivity().startPostponedEnterTransition();
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
playbackService = ((PlaybackService.LocalBinder)service).getService();
playingItemChanged(playbackService.getPlayingItemIntent());
playbackStateChanged(playbackService.getPlaybackStateIntent());
this.isRepeatEnabled = playbackService.isRepeatEnabled();
onRepeatToggled();
}
private void onRepeatToggled() {
if (repeatItem == null) return;
repeatItem.getIcon().setAlpha(isRepeatEnabled ? 255 : 50);
}
@Override
public void onServiceDisconnected(ComponentName name) {
playbackService = null;
}
private void scheduleHideOverlays() {
if (!autoHideOverlays || playbackService.getState() != PlaybackState.PLAYING) return;
overlayHandler.removeCallbacksAndMessages(null);
overlayHandler.postDelayed(new Runnable() {
@Override
public void run() {
setOverlaysVisible(false);
}
}, 5000);
}
private void cancelHideOverlays() {
overlayHandler.removeCallbacksAndMessages(null);
}
private void setOverlaysVisible(boolean visible) {
float alpha = visible ? 1f : 0f;
int duration = visible ? 400 : 750;
ViewPropertyAnimator topAnimator = topDetailContainer.animate().alpha(alpha).setDuration(duration);
ViewPropertyAnimator bottomAnimator = bottomDetailContainer.animate().alpha(alpha).setDuration(duration);
if (visible) {
topAnimator.withStartAction(new SetVisibilityRunnable(topDetailContainer, true));
bottomAnimator.withStartAction(new SetVisibilityRunnable(bottomDetailContainer, true));
} else {
topAnimator.withEndAction(new SetVisibilityRunnable(topDetailContainer, false));
bottomAnimator.withEndAction(new SetVisibilityRunnable(bottomDetailContainer, false));
}
topAnimator.start();
bottomAnimator.start();
areOverlaysVisible = visible;
}
private static class SetVisibilityRunnable implements Runnable {
private View view;
private boolean visible;
public SetVisibilityRunnable(View view, boolean visible) {
this.view = view;
this.visible = visible;
}
@Override
public void run() {
if (visible) view.setAlpha(0f);
view.setVisibility(visible ? View.VISIBLE : View.GONE);
}
}
private class UpdatePositionRunnable implements Runnable {
@Override
public void run() {
if (playbackService.getState() == PlaybackState.PLAYING) {
updatePosition(position + 1000);
positionHandler.postDelayed(new UpdatePositionRunnable(), 1000);
}
}
}
private class CoverArtTarget extends SimpleTarget<Bitmap> {
@Override
public void onResourceReady(Bitmap art, GlideAnimation<? super Bitmap> glideAnimation) {
Utils.createDropShadowBitmap(art, new Utils.BitmapCallback() {
@Override
public void onBitmapReady(Bitmap bitmap) {
coverArt.setImageBitmap(bitmap);
ViewPropertyAnimator animator = coverArt.animate().alpha(1f).setDuration(175);
if (!isActivityTransitionDone) {
startEnterTransition();
animator.withEndAction(new Runnable() {
@Override
public void run() {
overlayHandler.postDelayed(new Runnable() {
@Override
public void run() {
isActivityTransitionDone = true;
setOverlaysVisible(true);
}
}, 150);
}
});
}
}
});
if (getActivity() instanceof PlayingNowActivity)
Utils.createBlurredBitmap(art, new Utils.BitmapCallback() {
@Override
public void onBitmapReady(Bitmap bitmap) {
((PlayingNowActivity)getActivity()).setBackgroundImage(bitmap);
}
});
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
resetToLogo();
}
}
}
|
app/src/main/java/com/lenworthrose/music/fragment/PlayingItemFragment.java
|
package com.lenworthrose.music.fragment;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PaintDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewPropertyAnimator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.lenworthrose.music.R;
import com.lenworthrose.music.activity.PlayingNowActivity;
import com.lenworthrose.music.playback.PlaybackService;
import com.lenworthrose.music.util.Constants;
import com.lenworthrose.music.util.Constants.PlaybackState;
import com.lenworthrose.music.util.Utils;
/**
* This Fragment displays information about the currently playing track (Artist, Album, Title, Cover
* Art, etc). It also provides playback controls (Play/Pause, Next, Previous, Stop).
*/
public class PlayingItemFragment extends Fragment implements ServiceConnection {
private SeekBar positionBar;
private TextView artist, album, title, playlistPosition, playlistTracks, positionDisplay, durationDisplay;
private ImageView coverArt, playPause;
private View artistAlbumContainer, topDetailContainer, bottomDetailContainer;
private boolean isPositionBarTouched, autoHideOverlays;
private boolean areOverlaysVisible = true;
private Animation pauseBlinkAnimation = new AlphaAnimation(0f, 1f);
private PlaybackService playbackService;
private MenuItem repeatItem;
private boolean isRepeatEnabled;
private Handler positionHandler, overlayHandler;
private int position;
private boolean isActivityTransitionDone;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case Constants.PLAYING_NOW_CHANGED:
playingItemChanged(intent);
break;
case Constants.PLAYBACK_STATE_CHANGED:
playbackStateChanged(intent);
break;
case Constants.PLAYING_NOW_PLAYLIST_CHANGED:
playlistUpdated();
break;
}
}
};
private SeekBar.OnSeekBarChangeListener seekListener = new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
isPositionBarTouched = false;
positionDisplay.setText(Utils.longToTimeDisplay(seekBar.getProgress()));
playbackService.seek(seekBar.getProgress());
scheduleHideOverlays();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
isPositionBarTouched = true;
if (autoHideOverlays) {
setOverlaysVisible(true);
cancelHideOverlays();
}
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) positionDisplay.setText(Utils.longToTimeDisplay(progress));
}
};
private View.OnClickListener playbackButtonClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.pn_previous:
playbackService.previous();
break;
case R.id.pn_play_pause:
playbackService.playPause();
break;
case R.id.pn_stop:
playbackService.stop();
break;
case R.id.pn_next:
playbackService.next();
break;
}
}
};
private View.OnClickListener coverArtClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
cancelHideOverlays();
setOverlaysVisible(!areOverlaysVisible);
if (areOverlaysVisible) scheduleHideOverlays();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
autoHideOverlays = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(Constants.SETTING_AUTO_HIDE_PLAYING_NOW_OVERLAYS, false);
positionHandler = new Handler(Looper.getMainLooper());
overlayHandler = new Handler(Looper.getMainLooper());
setHasOptionsMenu(true);
pauseBlinkAnimation.setDuration(375);
pauseBlinkAnimation.setStartOffset(250);
pauseBlinkAnimation.setRepeatCount(Animation.INFINITE);
pauseBlinkAnimation.setRepeatMode(Animation.REVERSE);
setHasOptionsMenu(true); //Required for the system to call onCreateOptionsMenu() to get the Repeat MenuItem
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_playing_item, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
topDetailContainer = view.findViewById(R.id.pn_top_detail_container);
artistAlbumContainer = topDetailContainer.findViewById(R.id.pn_artist_album_container);
artist = (TextView)artistAlbumContainer.findViewById(R.id.pn_artist);
album = (TextView)artistAlbumContainer.findViewById(R.id.pn_album);
title = (TextView)topDetailContainer.findViewById(R.id.pn_name);
bottomDetailContainer = view.findViewById(R.id.pn_bottom_detail_container);
playlistPosition = (TextView)bottomDetailContainer.findViewById(R.id.pn_playlist_position);
playlistTracks = (TextView)bottomDetailContainer.findViewById(R.id.pn_playlist_tracks);
positionDisplay = (TextView)bottomDetailContainer.findViewById(R.id.pn_position_display);
durationDisplay = (TextView)bottomDetailContainer.findViewById(R.id.pn_duration);
positionBar = (SeekBar)bottomDetailContainer.findViewById(R.id.pn_position_seekbar);
positionBar.setOnSeekBarChangeListener(seekListener);
positionBar.setEnabled(false);
coverArt = (ImageView)view.findViewById(R.id.pn_coverArt);
coverArt.setOnClickListener(coverArtClickListener);
View playbackControlContainer = view.findViewById(R.id.pn_playback_control_container);
playPause = (ImageView)playbackControlContainer.findViewById(R.id.pn_play_pause);
playPause.setOnClickListener(playbackButtonClickListener);
playbackControlContainer.findViewById(R.id.pn_previous).setOnClickListener(playbackButtonClickListener);
playbackControlContainer.findViewById(R.id.pn_next).setOnClickListener(playbackButtonClickListener);
playbackControlContainer.findViewById(R.id.pn_stop).setOnClickListener(playbackButtonClickListener);
ShapeDrawable.ShaderFactory topShaderFactory = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
return new LinearGradient(0, height, 0, 0,
new int[] { 0x00090909, 0x29090909, 0x49090909, 0x69090909, 0x7C090909, 0x8A090909, 0x9D090909, 0xB2090909 },
new float[] { 0f, .023f, .039f, .056f, .080f, .110f, .165f, 1f },
Shader.TileMode.CLAMP);
}
};
PaintDrawable topBackground = new PaintDrawable();
topBackground.setShape(new RectShape());
topBackground.setShaderFactory(topShaderFactory);
topDetailContainer.setBackground(topBackground);
ShapeDrawable.ShaderFactory bottomShaderFactory = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
return new LinearGradient(0, 0, 0, height,
new int[] { 0x00090909, 0x4D090909, 0x69090909, 0x72090909, 0x76090909, 0x79090909, 0x87090909, 0x93090909, 0xA6090909, 0xB2090909 },
new float[] { 0f, .040f, .064f, .083f, .090f, .095f, .12f, .15f, .2f, 1f },
Shader.TileMode.CLAMP);
}
};
PaintDrawable bottomBackground = new PaintDrawable();
bottomBackground.setShape(new RectShape());
bottomBackground.setShaderFactory(bottomShaderFactory);
bottomDetailContainer.setBackground(bottomBackground);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
repeatItem = menu.findItem(R.id.action_repeat);
repeatItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(getActivity(), PlaybackService.class);
intent.setAction(Constants.CMD_TOGGLE_REPEAT_MODE);
getActivity().startService(intent);
isRepeatEnabled = !isRepeatEnabled;
onRepeatToggled();
return true;
}
});
onRepeatToggled();
}
@Override
public void onResume() {
super.onResume();
getActivity().bindService(new Intent(getActivity(), PlaybackService.class), this, Context.BIND_AUTO_CREATE);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(broadcastReceiver, Utils.createPlaybackIntentFilter());
}
@Override
public void onPause() {
cancelHideOverlays();
positionHandler.removeCallbacksAndMessages(null);
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcastReceiver);
getActivity().unbindService(this);
super.onPause();
}
private void playingItemChanged(Intent intent) {
positionHandler.removeCallbacksAndMessages(null);
if (isDetached() || playbackService == null) return;
if (autoHideOverlays && isActivityTransitionDone) setOverlaysVisible(true);
artist.setText(intent.getStringExtra(Constants.EXTRA_ARTIST));
album.setText(intent.getStringExtra(Constants.EXTRA_ALBUM));
title.setText(intent.getStringExtra(Constants.EXTRA_TITLE));
if (!playbackService.isPlaylistEmpty()) {
playlistPosition.setText(String.valueOf(intent.getIntExtra(Constants.EXTRA_PLAYLIST_POSITION, 0)));
playlistTracks.setText(String.valueOf(intent.getIntExtra(Constants.EXTRA_PLAYLIST_TOTAL_TRACKS, 0)));
positionDisplay.setText(R.string.blank_time);
coverArt.animate().alpha(0.08f).setDuration(75);
Glide.with(this).load(intent.getStringExtra(Constants.EXTRA_ALBUM_ART_URL)).asBitmap().into(new SimpleTarget<Bitmap>() {
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
resetToLogo();
}
@Override
public void onResourceReady(Bitmap art, GlideAnimation<? super Bitmap> glideAnimation) {
if (art != null) {
Utils.createDropShadowBitmap(art, new Utils.BitmapCallback() {
@Override
public void onBitmapReady(Bitmap bitmap) {
coverArt.setImageBitmap(bitmap);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) getActivity().startPostponedEnterTransition();
coverArt.animate().alpha(1f).setDuration(175).withEndAction(new Runnable() {
@Override
public void run() {
if (!isActivityTransitionDone) {
overlayHandler.postDelayed(new Runnable() {
@Override
public void run() {
isActivityTransitionDone = true;
setOverlaysVisible(true);
}
}, 150);
}
}
});
}
});
if (getActivity() instanceof PlayingNowActivity)
Utils.createBlurredBitmap(art, new Utils.BitmapCallback() {
@Override
public void onBitmapReady(Bitmap bitmap) {
((PlayingNowActivity)getActivity()).setBackgroundImage(bitmap);
}
});
}
}
});
} else {
resetToLogo();
positionBar.setEnabled(false);
positionBar.setProgress(0);
playlistPosition.setText("0");
playlistTracks.setText("0");
}
artistAlbumContainer.setVisibility(artist.getText().toString().isEmpty() && album.getText().toString().isEmpty() ? View.GONE : View.VISIBLE);
}
private void playbackStateChanged(Intent intent) {
positionHandler.removeCallbacksAndMessages(null);
if (isDetached() || playbackService == null) return;
PlaybackState state = (PlaybackState)intent.getSerializableExtra(Constants.EXTRA_STATE);
playPause.setImageResource(R.drawable.play);
int duration = intent.getIntExtra(Constants.EXTRA_DURATION, -1);
switch (state) {
case BUFFERING:
positionDisplay.clearAnimation();
positionBar.setEnabled(false);
playPause.setAlpha(.3f);
playPause.setImageResource(R.drawable.play);
playPause.setEnabled(false);
break;
case PLAYING:
positionDisplay.clearAnimation();
durationDisplay.setText(Utils.longToTimeDisplay(duration));
positionBar.setMax(duration);
playPause.setAlpha(1f);
playPause.setImageResource(R.drawable.pause);
playPause.setEnabled(true);
scheduleHideOverlays();
updatePosition(intent.getIntExtra(Constants.EXTRA_POSITION, 0));
positionHandler.postDelayed(new UpdatePositionRunnable(), 1000);
break;
case PAUSED:
positionDisplay.startAnimation(pauseBlinkAnimation);
durationDisplay.setText(Utils.longToTimeDisplay(duration));
positionBar.setMax(duration);
updatePosition(intent.getIntExtra(Constants.EXTRA_POSITION, 0));
break;
case STOPPED:
positionDisplay.setText(R.string.blank_time);
durationDisplay.setText(R.string.blank_time);
positionBar.setProgress(0);
positionBar.setEnabled(false);
playPause.setEnabled(true);
playPause.setAlpha(1f);
positionDisplay.clearAnimation();
break;
}
if (state != PlaybackState.PLAYING) {
cancelHideOverlays();
if (isActivityTransitionDone) setOverlaysVisible(true);
}
}
private void playlistUpdated() {
if (isDetached() || playbackService == null) return;
if (!playbackService.isPlaylistEmpty()) {
playlistPosition.setText(String.valueOf(playbackService.getPlaylistPositionForDisplay()));
playlistTracks.setText(String.valueOf(playbackService.getPlaylistSize()));
} else {
playlistPosition.setText("0");
playlistTracks.setText("0");
}
}
private void resetToLogo() {
coverArt.setAlpha(.1f);
coverArt.setImageResource(R.drawable.logo);
if (getActivity() instanceof PlayingNowActivity)
((PlayingNowActivity)getActivity()).setBackgroundImage(null);
}
private void updatePosition(int position) {
this.position = position;
if (!isPositionBarTouched) {
positionBar.setProgress(position);
positionBar.setEnabled(true);
positionDisplay.setText(Utils.longToTimeDisplay(position));
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
playbackService = ((PlaybackService.LocalBinder)service).getService();
playingItemChanged(playbackService.getPlayingItemIntent());
playbackStateChanged(playbackService.getPlaybackStateIntent());
this.isRepeatEnabled = playbackService.isRepeatEnabled();
onRepeatToggled();
}
private void onRepeatToggled() {
if (repeatItem == null) return;
repeatItem.getIcon().setAlpha(isRepeatEnabled ? 255 : 50);
}
@Override
public void onServiceDisconnected(ComponentName name) {
playbackService = null;
}
private void scheduleHideOverlays() {
if (!autoHideOverlays || playbackService.getState() != PlaybackState.PLAYING) return;
overlayHandler.removeCallbacksAndMessages(null);
overlayHandler.postDelayed(new Runnable() {
@Override
public void run() {
setOverlaysVisible(false);
}
}, 5000);
}
private void cancelHideOverlays() {
overlayHandler.removeCallbacksAndMessages(null);
}
private void setOverlaysVisible(boolean visible) {
float alpha = visible ? 1f : 0f;
int duration = visible ? 400 : 750;
ViewPropertyAnimator topAnimator = topDetailContainer.animate().alpha(alpha).setDuration(duration);
ViewPropertyAnimator bottomAnimator = bottomDetailContainer.animate().alpha(alpha).setDuration(duration);
if (visible) {
topAnimator.withStartAction(new SetVisibilityRunnable(topDetailContainer, true));
bottomAnimator.withStartAction(new SetVisibilityRunnable(bottomDetailContainer, true));
} else {
topAnimator.withEndAction(new SetVisibilityRunnable(topDetailContainer, false));
bottomAnimator.withEndAction(new SetVisibilityRunnable(bottomDetailContainer, false));
}
topAnimator.start();
bottomAnimator.start();
areOverlaysVisible = visible;
}
private static class SetVisibilityRunnable implements Runnable {
private View view;
private boolean visible;
public SetVisibilityRunnable(View view, boolean visible) {
this.view = view;
this.visible = visible;
}
@Override
public void run() {
if (visible) view.setAlpha(0f);
view.setVisibility(visible ? View.VISIBLE : View.GONE);
}
}
private class UpdatePositionRunnable implements Runnable {
@Override
public void run() {
if (playbackService.getState() == PlaybackState.PLAYING) {
updatePosition(position + 1000);
positionHandler.postDelayed(new UpdatePositionRunnable(), 1000);
}
}
}
}
|
Fix: unable to open Playing Now if no cover art
If the playing track had no cover art, or there was no playing track, the
Playing Now page sometimes wouldn't open, and if it did it wouldn't show
the overlays.
Refactored the image fetch logic into an inner class, for cleanliness.
|
app/src/main/java/com/lenworthrose/music/fragment/PlayingItemFragment.java
|
Fix: unable to open Playing Now if no cover art
|
|
Java
|
apache-2.0
|
c48b6973eca59174f3e1f90cd15637029c27dcf5
| 0
|
Centril/sleepfighter,Centril/sleepfighter
|
package se.chalmers.dat255.sleepfighter.activity;
import org.joda.time.DateTime;
import se.chalmers.dat255.sleepfighter.R;
import se.chalmers.dat255.sleepfighter.SFApplication;
import se.chalmers.dat255.sleepfighter.audio.AudioDriver;
import se.chalmers.dat255.sleepfighter.model.Alarm;
import se.chalmers.dat255.sleepfighter.model.AlarmTimestamp;
import se.chalmers.dat255.sleepfighter.preference.GlobalPreferencesReader;
import se.chalmers.dat255.sleepfighter.service.AlarmPlannerService;
import se.chalmers.dat255.sleepfighter.service.AlarmPlannerService.Command;
import se.chalmers.dat255.sleepfighter.utils.android.AlarmWakeLocker;
import se.chalmers.dat255.sleepfighter.utils.android.IntentUtils;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
/**
* The activity for when an alarm rings/occurs.
*
* @author Centril<twingoow@gmail.com> / Mazdak Farrokhzad.
* @version 1.0
* @since Sep 20, 2013
*/
public class AlarmActivity extends Activity {
public static final String EXTRA_ALARM_ID = "alarm_id";
private static final int WINDOW_FLAGS_SCREEN_ON =
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
private static final int WINDOW_FLAGS_LOCKSCREEN = WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
public static final int CHALLENGE_REQUEST_CODE = 1;
// TODO move to settings!
private boolean turnScreenOn = true;
private boolean bypassLockscreen = true;
private Alarm alarm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Turn and/or Keep screen on.
this.setScreenFlags();
this.setContentView(R.layout.activity_alarm_prechallenge);
SFApplication app = SFApplication.get();
// Fetch alarm Id.
int alarmId = new IntentUtils( this.getIntent() ).getAlarmId();
this.alarm = app.getPersister().fetchAlarmById( alarmId );
// Do stuff.
this.work();
}
protected void onPause() {
super.onPause();
// Release the wake-lock acquired in AlarmReceiver!
AlarmWakeLocker.release();
}
private void performRescheduling() {
SFApplication app = SFApplication.get();
// Disable alarm if not repeating.
if ( !this.alarm.isRepeating() ) {
if ( this.alarm.getMessageBus() == null ) {
this.alarm.setMessageBus( app.getBus() );
}
this.alarm.setActivated( false );
} else {
// Reschedule earliest alarm (if any).
AlarmTimestamp at = app.getAlarms().getEarliestAlarm( new DateTime().getMillis() );
if ( at != AlarmTimestamp.INVALID ) {
AlarmPlannerService.call( app, Command.CREATE, at.getAlarm().getId() );
}
}
}
/**
* Sets screen related flags, reads from preferences.
*/
private void setScreenFlags() {
int flags = this.computeScreenFlags();
if ( flags == 0 ) {
return;
}
this.getWindow().addFlags( flags );
}
private void readPreferences() {
GlobalPreferencesReader prefs = SFApplication.get().getPrefs();
this.turnScreenOn = prefs.turnScreenOn();
this.bypassLockscreen = prefs.bypassLockscreen();
}
/**
* Computes screen flags based on preferences.
*
* @return screen flags.
*/
private int computeScreenFlags() {
readPreferences();
int flags = 0;
if ( this.turnScreenOn ) {
flags |= WINDOW_FLAGS_SCREEN_ON;
}
if ( this.bypassLockscreen ) {
flags |= WINDOW_FLAGS_LOCKSCREEN;
}
return flags;
}
private void work() {
Log.d( "AlarmActivity", "alarm #id: " + Integer.toString( this.alarm.getId() ) );
this.startAudio( this.alarm );
Log.d( "AlarmActivity", "work#1" );
// TODO: do something useful.
Toast.makeText(this, "Alarm ringing, get up! Alarm #" + this.alarm.getId(), Toast.LENGTH_LONG).show();
}
public void button(View view) {
// Intent intent = new Intent(this, ChallengeActivity.class);
//Intent intent = new Intent(this, MemoryActivity.class);
Intent intent = new Intent(this, SimpleMathActivity.class);
startActivityForResult(intent, CHALLENGE_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check if result is from a challenge
if(requestCode == CHALLENGE_REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Challenge completed", Toast.LENGTH_LONG)
.show();
stopAlarm();
finish();
} else {
Toast.makeText(this, "Returned from uncompleted challenge",
Toast.LENGTH_LONG).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
// TODO move out of class
public void stopAlarm() {
// TODO more here
// TODO move ?
this.stopAudio();
this.performRescheduling();
}
private void startAudio( Alarm alarm ) {
SFApplication app = SFApplication.get();
AudioDriver driver = app.getAudioDriverFactory().produce( app, alarm.getAudioSource() );
app.setAudioDriver( driver );
driver.play( alarm.getAudioConfig() );
}
private void stopAudio() {
SFApplication.get().setAudioDriver( null );
}
}
|
application/src/se/chalmers/dat255/sleepfighter/activity/AlarmActivity.java
|
package se.chalmers.dat255.sleepfighter.activity;
import org.joda.time.DateTime;
import se.chalmers.dat255.sleepfighter.R;
import se.chalmers.dat255.sleepfighter.SFApplication;
import se.chalmers.dat255.sleepfighter.audio.AudioDriver;
import se.chalmers.dat255.sleepfighter.model.Alarm;
import se.chalmers.dat255.sleepfighter.model.AlarmTimestamp;
import se.chalmers.dat255.sleepfighter.preference.GlobalPreferencesReader;
import se.chalmers.dat255.sleepfighter.service.AlarmPlannerService;
import se.chalmers.dat255.sleepfighter.service.AlarmPlannerService.Command;
import se.chalmers.dat255.sleepfighter.utils.android.AlarmWakeLocker;
import se.chalmers.dat255.sleepfighter.utils.android.IntentUtils;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
/**
* The activity for when an alarm rings/occurs.
*
* @author Centril<twingoow@gmail.com> / Mazdak Farrokhzad.
* @version 1.0
* @since Sep 20, 2013
*/
public class AlarmActivity extends Activity {
public static final String EXTRA_ALARM_ID = "alarm_id";
private static final int WINDOW_FLAGS_SCREEN_ON =
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
private static final int WINDOW_FLAGS_LOCKSCREEN = WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
public static final int CHALLENGE_REQUEST_CODE = 1;
// TODO move to settings!
private boolean turnScreenOn = true;
private boolean bypassLockscreen = true;
private Alarm alarm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Turn and/or Keep screen on.
this.setScreenFlags();
this.setContentView(R.layout.activity_alarm_prechallenge);
SFApplication app = SFApplication.get();
// Fetch alarm Id.
int alarmId = new IntentUtils( this.getIntent() ).getAlarmId();
this.alarm = app.getPersister().fetchAlarmById( alarmId );
// Do stuff.
this.work();
}
protected void onPause() {
super.onPause();
// Release the wake-lock acquired in AlarmReceiver!
AlarmWakeLocker.release();
}
private void performRescheduling() {
SFApplication app = SFApplication.get();
// Disable alarm if not repeating.
if ( !this.alarm.isRepeating() ) {
if ( this.alarm.getMessageBus() == null ) {
this.alarm.setMessageBus( app.getBus() );
}
this.alarm.setActivated( false );
} else {
// Reschedule earliest alarm (if any).
AlarmTimestamp at = app.getAlarms().getEarliestAlarm( new DateTime().getMillis() );
if ( at != AlarmTimestamp.INVALID ) {
AlarmPlannerService.call( app, Command.CREATE, at.getAlarm().getId() );
}
}
}
/**
* Sets screen related flags, reads from preferences.
*/
private void setScreenFlags() {
int flags = this.computeScreenFlags();
if ( flags == 0 ) {
return;
}
this.getWindow().addFlags( flags );
}
private void readPreferences() {
GlobalPreferencesReader prefs = SFApplication.get().getPrefs();
this.turnScreenOn = prefs.turnScreenOn();
this.bypassLockscreen = prefs.bypassLockscreen();
}
/**
* Computes screen flags based on preferences.
*
* @return screen flags.
*/
private int computeScreenFlags() {
readPreferences();
int flags = 0;
if ( this.turnScreenOn ) {
flags |= WINDOW_FLAGS_SCREEN_ON;
}
if ( this.bypassLockscreen ) {
flags |= WINDOW_FLAGS_LOCKSCREEN;
}
return flags;
}
private void work() {
Log.d( "AlarmActivity", "alarm #id: " + Integer.toString( this.alarm.getId() ) );
this.startAudio( this.alarm );
Log.d( "AlarmActivity", "work#1" );
// TODO: do something useful.
Toast.makeText(this, "Alarm ringing, get up! Alarm #" + this.alarm.getId(), Toast.LENGTH_LONG).show();
}
public void button(View view) {
// Intent intent = new Intent(this, ChallengeActivity.class);
//Intent intent = new Intent(this, MemoryActivity.class);
Intent intent = new Intent(this, SimpleMathActivity.class);
startActivityForResult(intent, CHALLENGE_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check if result is from a challenge
if(requestCode == CHALLENGE_REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Challenge completed", Toast.LENGTH_LONG)
.show();
stopAlarm();
} else {
Toast.makeText(this, "Returned from uncompleted challenge",
Toast.LENGTH_LONG).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
// TODO move out of class
public void stopAlarm() {
// TODO more here
// TODO move ?
this.stopAudio();
this.performRescheduling();
}
private void startAudio( Alarm alarm ) {
SFApplication app = SFApplication.get();
AudioDriver driver = app.getAudioDriverFactory().produce( app, alarm.getAudioSource() );
app.setAudioDriver( driver );
driver.play( alarm.getAudioConfig() );
}
private void stopAudio() {
SFApplication.get().setAudioDriver( null );
}
}
|
When complete a challenge - back to main activity
|
application/src/se/chalmers/dat255/sleepfighter/activity/AlarmActivity.java
|
When complete a challenge - back to main activity
|
|
Java
|
apache-2.0
|
b1cc5d950ee2750f5c11b554f40cd440a6f44c64
| 0
|
apache/continuum,apache/continuum,apache/continuum
|
package org.apache.continuum.taskqueue.manager;
/*
* 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.
*/
import java.util.List;
import org.apache.continuum.taskqueue.PrepareBuildProjectsTask;
import org.codehaus.plexus.taskqueue.TaskQueue;;
/**
* @author <a href="mailto:ctan@apache.org">Maria Catherine Tan</a>
*/
public interface TaskQueueManager
{
String ROLE = TaskQueueManager.class.getName();
TaskQueue getDistributedBuildQueue();
List<PrepareBuildProjectsTask> getDistributedBuildProjectsInQueue()
throws TaskQueueManagerException;
TaskQueue getPurgeQueue();
boolean isInDistributedBuildQueue( int projectGroupId, String scmRootAddress )
throws TaskQueueManagerException;
boolean isInPurgeQueue( int purgeConfigurationId )
throws TaskQueueManagerException;
/**
* Check if the repository is already in the purging queue
*
* @param repositoryId the id of the repository purge configuration
* @return true if the repository is in the purging queue, otherwise false
* @throws TaskQueueManagerException
*/
boolean isRepositoryInPurgeQueue( int repositoryId )
throws TaskQueueManagerException;
/**
* Check if the repository is being used by a project that is currently building
*
* @param repositoryId the id of the local repository
* @return true if the repository is in use, otherwise false
* @throws TaskQueueManagerException
*/
boolean isRepositoryInUse( int repositoryId )
throws TaskQueueManagerException;
/**
* Check whether a project is in the release stage based on the given releaseId.
*
* @param releaseId
* @return
* @throws TaskQueueManagerException
*/
boolean isProjectInReleaseStage( String releaseId )
throws TaskQueueManagerException;
boolean releaseInProgress()
throws TaskQueueManagerException;
void removeFromDistributedBuildQueue( int projectGroupId, String scmRootAddress )
throws TaskQueueManagerException;
/**
* Remove local repository from the purge queue
*
* @param purgeConfigId the id of the purge configuration
* @return true if the purge configuration was successfully removed from the purge queue, otherwise false
* @throws TaskQueueManagerException
*/
boolean removeFromPurgeQueue( int purgeConfigId )
throws TaskQueueManagerException;
/**
* Remove local repositories from the purge queue
*
* @param purgeConfigIds the ids of the purge configuration
* @return true if the purge configurations were successfully removed from the purge queue, otherwise false
* @throws TaskQueueManagerException
*/
boolean removeFromPurgeQueue( int[] purgeConfigIds )
throws TaskQueueManagerException;
/**
* Remove local repository from the purge queue
*
* @param repositoryId the id of the local repository
* @throws TaskQueueManagerException
*/
void removeRepositoryFromPurgeQueue( int repositoryId )
throws TaskQueueManagerException;
void removeTasksFromDistributedBuildQueueWithHashCodes( int[] hashCodes )
throws TaskQueueManagerException;
}
|
continuum-api/src/main/java/org/apache/continuum/taskqueue/manager/TaskQueueManager.java
|
package org.apache.continuum.taskqueue.manager;
/*
* 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.
*/
import java.util.List;
import org.apache.continuum.taskqueue.PrepareBuildProjectsTask;
import org.codehaus.plexus.taskqueue.TaskQueue;;
/**
* @author <a href="mailto:ctan@apache.org">Maria Catherine Tan</a>
*/
public interface TaskQueueManager
{
String ROLE = TaskQueueManager.class.getName();
TaskQueue getDistributedBuildQueue();
List<PrepareBuildProjectsTask> getDistributedBuildProjectsInQueue()
throws TaskQueueManagerException;
TaskQueue getPurgeQueue();
boolean isInDistributedBuildQueue( int projectGroupId, String scmRootAddress )
throws TaskQueueManagerException;
boolean isInPurgeQueue( int purgeConfigurationId )
throws TaskQueueManagerException;
/**
* Check if the repository is already in the purging queue
*
* @param repositoryId the id of the repository purge configuration
* @return true if the repository is in the purging queue, otherwise false
* @throws TaskQueueManagerException
*/
boolean isRepositoryInPurgeQueue( int repositoryId )
throws TaskQueueManagerException;
/**
* Check if the repository is being used by a project that is currently building
*
* @param repositoryId the id of the local repository
* @return true if the repository is in use, otherwise false
* @throws TaskQueueManagerException
*/
boolean isRepositoryInUse( int repositoryId )
throws TaskQueueManagerException;
/**
* Check whether a project is in the release stage based on the given releaseId.
*
* @param releaseId
* @return
* @throws TaskQueueManagerException
*/
boolean isProjectInReleaseStage( String releaseId )
throws TaskQueueManagerException;
boolean releaseInProgress()
throws TaskQueueManagerException;
boolean removeFromDistributedBuildQueue( int projectGroupId, String scmRootAddress )
throws TaskQueueManagerException;
/**
* Remove local repository from the purge queue
*
* @param purgeConfigId the id of the purge configuration
* @return true if the purge configuration was successfully removed from the purge queue, otherwise false
* @throws TaskQueueManagerException
*/
boolean removeFromPurgeQueue( int purgeConfigId )
throws TaskQueueManagerException;
/**
* Remove local repositories from the purge queue
*
* @param purgeConfigIds the ids of the purge configuration
* @return true if the purge configurations were successfully removed from the purge queue, otherwise false
* @throws TaskQueueManagerException
*/
boolean removeFromPurgeQueue( int[] purgeConfigIds )
throws TaskQueueManagerException;
/**
* Remove local repository from the purge queue
*
* @param repositoryId the id of the local repository
* @throws TaskQueueManagerException
*/
void removeRepositoryFromPurgeQueue( int repositoryId )
throws TaskQueueManagerException;
void removeTasksFromDistributedBuildQueueWithHashCodes( int[] hashCodes )
throws TaskQueueManagerException;
}
|
Fix compilation error
git-svn-id: 14f2065c7afdeb19086ae32a80b5e7aec819bae3@745098 13f79535-47bb-0310-9956-ffa450edef68
|
continuum-api/src/main/java/org/apache/continuum/taskqueue/manager/TaskQueueManager.java
|
Fix compilation error
|
|
Java
|
apache-2.0
|
c1f758f82907d1a0fc445e6b9a093400edcfb370
| 0
|
Water-Cat1/FelisBotus,Water-Cat1/FelisBotus
|
/*
*
* Reference = http://www.jibble.org/javadocs/pircbot/index.html
*Used foundation of CyBot made by JennyLeeP to get me started. Many thanks to her help and support!
*
*
*
*/
package com.wc1.felisBotus;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.PircBot;
import org.jibble.pircbot.User;
import com.wc1.felisBotus.irc.IRCChannel;
import com.wc1.felisBotus.irc.IRCServer;
/**
* Bot for the program. Each instance can only connect to one server, so several instances will need to be created to connect to several servers.
* Stores the username for the owner of this bot, server this bot will connect to, password to identify this bot (if it is being saved), login address and bot name.
* Bot will always listen to its owner or Ops in the channel. (yet to be implemented)
* @author Water_Cat1
* @author JennyLeeP
*/
public class FelisBotus extends PircBot {
private boolean voiceUsers = true;
private String owner;
private IRCServer server; // this thing will contain all info on the server,
// channels and ops in said channels.
private String loginPass;
private boolean shuttingdown = false;
/**Version of the bot*/
public static final String version = "C3 Java IRC Bot - V0.5.W";
/**String that this bot will recognize as a command to it*/
public static final String commandStart = "\\";
/**
* Constructor for when bot without server information (can be added later through other methods) Used mainly for first time creation
* @param botName Name for this bot
* @param owner Username for the owner of this bot. Bot will always recognize commands from this user
* @param login Login address for the bot
* @param loginPass Password to identify this bot (can be null)
*/
public FelisBotus(String botName, String owner, String login,
String loginPass) {
this.setName(botName);
this.owner = owner;
this.setLogin(login);
this.loginPass = loginPass;
this.setVersion(version);
}
/**
* Constructer to create this bot, including server information. Used mainly for loading from the XML file.
* @param botName Name for this bot
* @param owner Username for the owner of this bot. Bot will always recognize commands from this user
* @param login Login address for the bot
* @param loginPass Password to identify this bot (can be null)
* @param currServer Server information for this bot
*/
public FelisBotus(String botName, String owner, String login,
String loginPass, IRCServer currServer) {
this.setName(botName);
this.owner = owner;
this.setLogin(login);
this.loginPass = loginPass;
this.server = currServer;
this.setVersion(version);
}
/**
* Call to connect bots to default server assigned to them. Assumes call is from console and will ask console for missing information.
*/
public void connectConsole(){
this.setAutoNickChange(true);
if (server == null){
String newServer = System.console().readLine("Please enter a server address.\n");
server = new IRCServer(newServer);
}
try {
this.connect(server.getServerAddress());//TODO add support for saving port numbers and server passwords
while (!isConnected()){//wait till successfully connected
Thread.sleep(5000);
}
//verify login
String pass;
if (loginPass != null){
pass = loginPass;
}
else{
Thread.sleep(5000);
pass = new String(System.console().readPassword("\nPlease enter a password to verify the bot on %s\n", this.server.getServerAddress()));
}
if(!this.getName().equals(this.getNick())){//bot has a secondary name. GHOST primary nickname and then take it!
sendMessage("NickServ", "GHOST " + this.getName() + " " + pass.toString());
Thread.sleep(1000);
changeNick(this.getName());
}
identify(pass);
Thread.sleep(1000);
if (server.getChannels().size() == 0){ //if no default channels then connect to a new ones
String newChannel = System.console().readLine("Please enter a channel name to connect to.\n");
while (!newChannel.startsWith("#")){
newChannel = System.console().readLine("Channel name requires a '#' symbol at the start.\n");
}
server.addChannel(new IRCChannel(newChannel));
this.joinChannel(newChannel);
}else{//Connect to all default channels
for (IRCChannel channel:server.getChannels()){
this.joinChannel(channel.getName()); //TODO support for channels with keys
}
}
Main.save();
} catch (IOException e){//TODO how to manage exceptions? return to console/
//
} catch (IrcException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Method to make bot connect to supplied server.
* @param newServer New server to connect to
*/
public void connectCommand(IRCServer newServer){
//TODO make this and make exception to be thrown if already connected to a server.
//do i make this recieve a server or use the one saved by the bot? It does need a server otherwise it won't be controllable.
}
/**
* Returns the server associated with this instance of the bot
* @return server for this bot
*/
public IRCServer getIRCServer() {
return server;
}
/**
* Get the login password stored by this bot
* @return
*/
public String getLoginPass() {
return loginPass;
}
/**
* Get the username for the owner of this pot
* @return
*/
public String getOwner() {
return owner;
}
public boolean isVoiceUsers() {
return voiceUsers;
}
@Override
public void log(String line) {
System.out.println(line + "\n");
}
public void onDisconnect() {
if (shuttingdown){
Main.removeBot(this);
}
else{
int retryCount = 0;
while (!isConnected()) {
try {
reconnect();
//ghost old bot?
} catch (Exception e) {
retryCount++;
if (retryCount > 5){
shuttingdown = true;
Main.removeBot(this);
}
}
}
}
}
public void shutDown(){
shuttingdown = true;
if(isConnected()){
for (IRCChannel channel:server.getChannels()){
partChannel(channel.getName(), "Shutting Down");
}
disconnect();
}
dispose();
}
@Override
protected void onJoin(String channel, String sender, String login,
String hostname) {
if (sender != this.getNick()) {
IRCChannel currChannel = server.getChannel(channel);
if (currChannel.getBotIsOp() && currChannel.checkOP(sender)){
op(channel, sender);
}
if (sender.equals(owner)){
sendNotice(sender, "Greetings commander! The qube monkeys are ready for testing!");
}
else{
sendNotice(sender, "Hello " + sender
+ " Welcome to the Qubed C3 IRC Channel!");
}
}
if (isVoiceUsers()) {
this.voice(channel, sender);
}
}
// public void onKick(String channel, String kickerNick, String login,
// String hostname, String recipientNick, String reason) {
// if (recipientNick.equalsIgnoreCase(getNick())) {
// joinChannel(channel);
// sendMessage(channel, "Guess who is baaaaack!");
// }
// }
@Override
protected void onMessage(String channel, String sender, String login,
String hostname, String message) {
if (message.startsWith(commandStart)){
boolean isOp = server.getChannel(channel).checkOP(sender);
String lowercaseCommand = message.toLowerCase(Locale.ROOT).split(" ")[0];
String[] splitMessage = {""};
switch(lowercaseCommand.substring(commandStart.length())){ //substring removes the command section of the string
case("addcommand"):
splitMessage = message.split(" ",3);
if (isOp && splitMessage.length >= 3){
String result = Main.putCommand(splitMessage[1].toLowerCase(Locale.ROOT), splitMessage[2]);
if (result !=null){
sendNotice(sender, "Command successfully overwritten :]. Previous response was '" +result+"'");
}
else{
sendNotice(sender, "Command successfully added :]");
}
try {
Main.save();
} catch (IOException e) {
sendNotice(sender, "Failed to save command. Command will be lost on bot restart :[");
System.out.printf("\nFailed to save bot!\n");
e.printStackTrace();
}
}
else if (splitMessage.length < 3){
sendNotice(sender, "Syntax Error. Correct usage is " + commandStart +"addcommand <newCommand> <Response>");
}
else{
sendNotice(sender, "You must be an OP to use this command");
}
break;
case("removecommand"):
if (isOp){
splitMessage = message.split(" ",3);
if (splitMessage.length == 2){
String result = Main.removeCommand(splitMessage[1]);
if (result==null){
sendNotice(sender, splitMessage[1] + " was never a saved command");
}
else{
sendNotice(sender, "Command successfully removed! :]");
try {
Main.save();
} catch (IOException e) {
sendNotice(sender, "Failed to save command. Command will come back on bot restart :[");
System.out.printf("\nFailed to save bot!\n");
e.printStackTrace();
}
}
}
else{
sendNotice(sender, "Syntax Error. Correct usage is " + commandStart +"removecommand <oldCommand>");
}
}
else{
sendNotice(sender, "You must be an OP to use this command");
}
break;
case("leavechannel"):
if (isOp){
splitMessage = message.split(" ");
if ((!splitMessage[1].startsWith("#")) || splitMessage.length > 2){
sendNotice(sender, "Syntax Error. Correct usage is " + commandStart +"leavechannel [channel]. "
+ "Channel must be prefxed by a #. If no channel is supplied then bot will leave this channel");
}
else if (splitMessage.length == 1 || splitMessage[1].equals(channel)){
partChannel(channel, "I don't hate you");
server.removeChannel(channel);
if (server.getChannels().size() == 0){ //not connected to any channels, disconnect from the server
shuttingdown = true;
disconnect();
}
}
else{
if (server.getChannels().contains(splitMessage[1])){
partChannel(splitMessage[1], "I must go, my people need me");
server.removeChannel(splitMessage[1]);
}
else{
sendNotice(sender, "I am not connected to this channel");
}
}
}
else{
sendNotice(sender, "You must be an OP to use this command");
}
break;
case("leaveserver"):
if (isOp){
splitMessage = message.split(" ");
if (splitMessage.length > 2){
sendNotice(sender, "Syntax Error. Correct usage is " + commandStart +"leaveserver [server]. "
+ "If no server is supplied then bot will leave this server");
}
else if (splitMessage.length == 1 || splitMessage[1].equals(server.getServerAddress())){
Main.removeBot(this);
}
else{
FelisBotus botToDisconnect = Main.getBotConnectedTo(splitMessage[1]);
if (botToDisconnect == null){
sendNotice(sender, "I am not connected to that server");
}
else{
Main.removeBot(botToDisconnect);
sendNotice(sender, "Successfully disconnected from " + splitMessage[1]);
}
}
}else{
sendNotice(sender, "You must be an OP to use this command");
}
break;
case("joinchannel"):
break;
case("joinserver"):
break;
case("shutdown"):
if (isOp){
splitMessage = message.split(" ");
if (splitMessage.length == 2 && splitMessage[1].equalsIgnoreCase("force")){
try {
Main.shutItDown(true);
} catch (IOException e) {
//Will never throw exception here
}
}
else if (splitMessage.length == 1){
try {
Main.shutItDown(false);
} catch (IOException e) {
sendNotice(sender, "Error while attempting to save before shutdown :[ \n"
+ "If you wish to ignore this use " + commandStart + "shutdown force.");
System.out.printf("Error encounted while attempting to save while shuting down\n");
e.printStackTrace();
}
}
else{
sendNotice(sender, "Syntax Error. Correct usage is " + commandStart +"shutdown [force]. "
+ "If the word 'force' is supplied then bot will shutdown even if an error occurs.");
}
}else{
sendNotice(sender, "You must be an OP to use this command");
}
break;
default:
String response = Main.getResponse(lowercaseCommand.substring(commandStart.length()));
if (response != null){
sendMessage(channel, response);
}
else{
sendNotice(sender, "Invalid command, please ensure it is spelled correctly");
}
}
}
}
/* (non-Javadoc)
* @see org.jibble.pircbot.PircBot#onNotice(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
@Override
protected void onNotice(String sourceNick, String sourceLogin,
String sourceHostname, String target, String notice) {
// TODO Auto-generated method stub
super.onNotice(sourceNick, sourceLogin, sourceHostname, target, notice);
}
@Override
protected void onOp(String channel, String sourceNick, String sourceLogin,
String sourceHostname, String recipient) {
IRCChannel currChannel = server.getChannel(channel);
Set<String> opList = currChannel.getOpList();
if (recipient.equals(this.getNick())){
server.getChannel(channel).setBotIsOp(true);
List<String> addedToList = new ArrayList<String>();
User[] users = getUsers(channel);
for (int i = 0; i < users.length; i++) {
User user = users[i];
String nick = user.getNick();
if (opList.contains(nick)){
if(!user.isOp()){//user is on OP list but is not op'd, so op them
op(channel, nick);
}
}
}
try {
if(Main.save())sendMessage(channel, "OpBot initialized.");
} catch (IOException e) {
sendMessage(channel, "Error occured while saving bot config. :[");
e.printStackTrace();
}
}
else{
if(!opList.contains(recipient)){
currChannel.addOp(recipient);
try {
if(Main.save())sendMessage(channel, recipient + " has been added to this bots known Ops");
} catch (IOException e) {
sendMessage(channel, "Error occured while saving bot config. :[");
e.printStackTrace();
}
}
}
}
@Override
protected void onDeop(String channel, String sourceNick,
String sourceLogin, String sourceHostname, String recipient) {
if (recipient.equals(this.getNick())){
server.getChannel(channel).setBotIsOp(false);
}
else{
IRCChannel currChannel = server.getChannel(channel);
Set<String> opList = currChannel.getOpList();
if(opList.contains(recipient)){
currChannel.removeOp(recipient);
try {
if(Main.save())sendMessage(channel, recipient + " has been removed from this bots known Ops");
} catch (IOException e) {
sendMessage(channel, "Error occured while saving bot config. :[");
e.printStackTrace();
}
}
}
}
public void onUserList(String channel, User[] users) {
IRCChannel currChannel = server.getChannel(channel);
Set<String> opList = currChannel.getOpList();
server.getChannel(channel).setBotIsOp(true);
List<String> addedToList = new ArrayList<String>();
for (int i = 0; i < users.length; i++) {
User user = users[i];
String nick = user.getNick();
if (!opList.contains(nick)){
if(user.isOp() && nick != this.getNick()){//user is op'd but is not on bots op list, so add them to the list
currChannel.addOp(nick);
addedToList.add(nick);
}
}
}
StringBuilder output = new StringBuilder("Bot initialized.");
if (addedToList.size() > 0){
output.append(" Added " + String.join(", ", addedToList.toArray(new String[addedToList.size()])) + " to this bots known Ops");
}
try {
if(Main.save())sendMessage(channel, output.toString());
} catch (IOException e) {
sendMessage(channel, "Error occured while saving bot config. :[");
e.printStackTrace();
}
}
public void setVoiceUsers(boolean voiceUsers) {
this.voiceUsers = voiceUsers;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((owner == null) ? 0 : owner.hashCode());
result = prime * result + ((server == null) ? 0 : server.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (!(obj instanceof FelisBotus))
return false;
FelisBotus other = (FelisBotus) obj;
if (owner == null) {
if (other.owner != null)
return false;
} else if (!owner.equals(other.owner))
return false;
if (server == null) {
if (other.server != null)
return false;
} else if (!server.equals(other.server))
return false;
return true;
}
}
|
FelisBotus/src/com/wc1/felisBotus/FelisBotus.java
|
/*
*
* Reference = http://www.jibble.org/javadocs/pircbot/index.html
*Used foundation of CyBot made by JennyLeeP to get me started. Many thanks to her help and support!
*
*
*
*/
package com.wc1.felisBotus;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.PircBot;
import org.jibble.pircbot.User;
import com.wc1.felisBotus.irc.IRCChannel;
import com.wc1.felisBotus.irc.IRCServer;
/**
* Bot for the program. Each instance can only connect to one server, so several instances will need to be created to connect to several servers.
* Stores the username for the owner of this bot, server this bot will connect to, password to identify this bot (if it is being saved), login address and bot name.
* Bot will always listen to its owner or Ops in the channel. (yet to be implemented)
* @author Water_Cat1
* @author JennyLeeP
*/
public class FelisBotus extends PircBot {
private boolean voiceUsers = true;
private String owner;
private IRCServer server; // this thing will contain all info on the server,
// channels and ops in said channels.
private String loginPass;
private boolean shuttingdown = false;
/**Version of the bot*/
public static final String version = "C3 Java IRC Bot - V0.5.W";
/**String that this bot will recognize as a command to it*/
public static final String commandStart = "\\";
/**
* Constructor for when bot without server information (can be added later through other methods) Used mainly for first time creation
* @param botName Name for this bot
* @param owner Username for the owner of this bot. Bot will always recognize commands from this user
* @param login Login address for the bot
* @param loginPass Password to identify this bot (can be null)
*/
public FelisBotus(String botName, String owner, String login,
String loginPass) {
this.setName(botName);
this.owner = owner;
this.setLogin(login);
this.loginPass = loginPass;
this.setVersion(version);
}
/**
* Constructer to create this bot, including server information. Used mainly for loading from the XML file.
* @param botName Name for this bot
* @param owner Username for the owner of this bot. Bot will always recognize commands from this user
* @param login Login address for the bot
* @param loginPass Password to identify this bot (can be null)
* @param currServer Server information for this bot
*/
public FelisBotus(String botName, String owner, String login,
String loginPass, IRCServer currServer) {
this.setName(botName);
this.owner = owner;
this.setLogin(login);
this.loginPass = loginPass;
this.server = currServer;
this.setVersion(version);
}
/**
* Call to connect bots to default server assigned to them. Assumes call is from console and will ask console for missing information.
*/
public void connectConsole(){
this.setAutoNickChange(true);
if (server == null){
String newServer = System.console().readLine("Please enter a server address.\n");
server = new IRCServer(newServer);
}
try {
this.connect(server.getServerAddress());//TODO add support for saving port numbers and server passwords
while (!isConnected()){//wait till successfully connected
Thread.sleep(5000);
}
//verify login
String pass;
if (loginPass != null){
pass = loginPass;
}
else{
Thread.sleep(5000);
pass = new String(System.console().readPassword("\nPlease enter a password to verify the bot on %s\n", this.server.getServerAddress()));
}
if(!this.getName().equals(this.getNick())){//bot has a secondary name. GHOST primary nickname and then take it!
sendMessage("NickServ", "GHOST " + this.getName() + " " + pass.toString());
Thread.sleep(1000);
changeNick(this.getName());
}
identify(pass);
Thread.sleep(1000);
if (server.getChannels().size() == 0){ //if no default channels then connect to a new ones
String newChannel = System.console().readLine("Please enter a channel name to connect to.\n");
while (!newChannel.startsWith("#")){
newChannel = System.console().readLine("Channel name requires a '#' symbol at the start.\n");
}
server.addChannel(new IRCChannel(newChannel));
this.joinChannel(newChannel);
}else{//Connect to all default channels
for (IRCChannel channel:server.getChannels()){
this.joinChannel(channel.getName()); //TODO support for channels with keys
}
}
Main.save();
} catch (IOException e){//TODO how to manage exceptions? return to console/
//
} catch (IrcException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Method to make bot connect to supplied server.
* @param newServer New server to connect to
*/
public void connectCommand(IRCServer newServer){
//TODO make this and make exception to be thrown if already connected to a server.
//do i make this recieve a server or use the one saved by the bot? It does need a server otherwise it won't be controllable.
}
/**
* Returns the server associated with this instance of the bot
* @return server for this bot
*/
public IRCServer getIRCServer() {
return server;
}
/**
* Get the login password stored by this bot
* @return
*/
public String getLoginPass() {
return loginPass;
}
/**
* Get the username for the owner of this pot
* @return
*/
public String getOwner() {
return owner;
}
public boolean isVoiceUsers() {
return voiceUsers;
}
@Override
public void log(String line) {
System.out.println(line + "\n");
}
public void onDisconnect() {
if (shuttingdown){
Main.removeBot(this);
}
else{
int retryCount = 0;
while (!isConnected()) {
try {
reconnect();
//ghost old bot?
} catch (Exception e) {
retryCount++;
if (retryCount > 5){
shuttingdown = true;
Main.removeBot(this);
}
}
}
}
}
public void shutDown(){
shuttingdown = true;
if(isConnected()){
for (IRCChannel channel:server.getChannels()){
partChannel(channel.getName(), "Shutting Down");
}
disconnect();
}
dispose();
}
@Override
protected void onJoin(String channel, String sender, String login,
String hostname) {
if (sender != this.getNick()) {
IRCChannel currChannel = server.getChannel(channel);
if (currChannel.getBotIsOp() && currChannel.checkOP(sender)){
op(channel, sender);
}
if (sender.equals(owner)){
sendNotice(sender, "Greetings commander! The qube monkeys are ready for testing!");
}
else{
sendNotice(sender, "Hello " + sender
+ " Welcome to the Qubed C3 IRC Channel- (I am a Bot)");
}
}
if (isVoiceUsers()) {
this.voice(channel, sender);
}
}
// public void onKick(String channel, String kickerNick, String login,
// String hostname, String recipientNick, String reason) {
// if (recipientNick.equalsIgnoreCase(getNick())) {
// joinChannel(channel);
// sendMessage(channel, "Guess who is baaaaack!");
// }
// }
@Override
protected void onMessage(String channel, String sender, String login,
String hostname, String message) {
if (message.startsWith(commandStart)){
boolean isOp = server.getChannel(channel).checkOP(sender);
String lowercaseCommand = message.toLowerCase(Locale.ROOT).split(" ")[0];
String[] splitMessage = {""};
switch(lowercaseCommand.substring(commandStart.length())){ //substring removes the command section of the string
case("addcommand"):
splitMessage = message.split(" ",3);
if (isOp && splitMessage.length >= 3){
String result = Main.putCommand(splitMessage[1].toLowerCase(Locale.ROOT), splitMessage[2]);
if (result !=null){
sendNotice(sender, "Command successfully overwritten :]. Previous response was '" +result+"'");
}
else{
sendNotice(sender, "Command successfully added :]");
}
try {
Main.save();
} catch (IOException e) {
sendNotice(sender, "Failed to save command. Command will be lost on bot restart :[");
System.out.printf("\nFailed to save bot!\n");
e.printStackTrace();
}
}
else if (splitMessage.length < 3){
sendNotice(sender, "Syntax Error. Correct usage is " + commandStart +"addcommand <newCommand> <Response>");
}
else{
sendNotice(sender, "You must be an OP to use this command");
}
break;
case("removecommand"):
if (isOp){
splitMessage = message.split(" ",3);
if (splitMessage.length == 2){
String result = Main.removeCommand(splitMessage[1]);
if (result==null){
sendNotice(sender, splitMessage[1] + " was never a saved command");
}
else{
sendNotice(sender, "Command successfully removed! :]");
try {
Main.save();
} catch (IOException e) {
sendNotice(sender, "Failed to save command. Command will come back on bot restart :[");
System.out.printf("\nFailed to save bot!\n");
e.printStackTrace();
}
}
}
else{
sendNotice(sender, "Syntax Error. Correct usage is " + commandStart +"removecommand <oldCommand>");
}
}
else{
sendNotice(sender, "You must be an OP to use this command");
}
break;
case("leavechannel"):
if (isOp){
splitMessage = message.split(" ");
if ((!splitMessage[1].startsWith("#")) || splitMessage.length > 2){
sendNotice(sender, "Syntax Error. Correct usage is " + commandStart +"leavechannel [channel]. "
+ "Channel must be prefxed by a #. If no channel is supplied then bot will leave this channel");
}
else if (splitMessage.length == 1 || splitMessage[1].equals(channel)){
partChannel(channel, "I don't hate you");
server.removeChannel(channel);
if (server.getChannels().size() == 0){ //not connected to any channels, disconnect from the server
shuttingdown = true;
disconnect();
}
}
else{
if (server.getChannels().contains(splitMessage[1])){
partChannel(splitMessage[1], "I must go, my people need me");
server.removeChannel(splitMessage[1]);
}
else{
sendNotice(sender, "I am not connected to this channel");
}
}
}
else{
sendNotice(sender, "You must be an OP to use this command");
}
break;
case("leaveserver"):
if (isOp){
splitMessage = message.split(" ");
if (splitMessage.length > 2){
sendNotice(sender, "Syntax Error. Correct usage is " + commandStart +"leaveserver [server]. "
+ "If no server is supplied then bot will leave this server");
}
else if (splitMessage.length == 1 || splitMessage[1].equals(server.getServerAddress())){
Main.removeBot(this);
}
else{
FelisBotus botToDisconnect = Main.getBotConnectedTo(splitMessage[1]);
if (botToDisconnect == null){
sendNotice(sender, "I am not connected to that server");
}
else{
Main.removeBot(botToDisconnect);
sendNotice(sender, "Successfully disconnected from " + splitMessage[1]);
}
}
}else{
sendNotice(sender, "You must be an OP to use this command");
}
break;
case("joinchannel"):
break;
case("joinserver"):
break;
case("shutdown"):
if (isOp){
splitMessage = message.split(" ");
if (splitMessage.length == 2 && splitMessage[1].equalsIgnoreCase("force")){
try {
Main.shutItDown(true);
} catch (IOException e) {
//Will never throw exception here
}
}
else if (splitMessage.length == 1){
try {
Main.shutItDown(false);
} catch (IOException e) {
sendNotice(sender, "Error while attempting to save before shutdown :[ \n"
+ "If you wish to ignore this use " + commandStart + "shutdown force.");
System.out.printf("Error encounted while attempting to save while shuting down\n");
e.printStackTrace();
}
}
else{
sendNotice(sender, "Syntax Error. Correct usage is " + commandStart +"shutdown [force]. "
+ "If the word 'force' is supplied then bot will shutdown even if an error occurs.");
}
}else{
sendNotice(sender, "You must be an OP to use this command");
}
break;
default:
String response = Main.getResponse(lowercaseCommand.substring(commandStart.length()));
if (response != null){
sendMessage(channel, response);
}
else{
sendNotice(sender, "Invalid command, please ensure it is spelled correctly");
}
}
}
}
/* (non-Javadoc)
* @see org.jibble.pircbot.PircBot#onNotice(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
@Override
protected void onNotice(String sourceNick, String sourceLogin,
String sourceHostname, String target, String notice) {
// TODO Auto-generated method stub
super.onNotice(sourceNick, sourceLogin, sourceHostname, target, notice);
}
@Override
protected void onOp(String channel, String sourceNick, String sourceLogin,
String sourceHostname, String recipient) {
IRCChannel currChannel = server.getChannel(channel);
Set<String> opList = currChannel.getOpList();
if (recipient.equals(this.getNick())){
server.getChannel(channel).setBotIsOp(true);
List<String> addedToList = new ArrayList<String>();
User[] users = getUsers(channel);
for (int i = 0; i < users.length; i++) {
User user = users[i];
String nick = user.getNick();
if (opList.contains(nick)){
if(!user.isOp()){//user is on OP list but is not op'd, so op them
op(channel, nick);
}
}
else{
if(user.isOp() && nick != this.getNick()){//user is op'd but is not on bots op list, so add them to the list
currChannel.addOp(nick);
addedToList.add(nick);
}
}
}
StringBuilder output = new StringBuilder("OpBot initialized.");
if (addedToList.size() > 0){
output.append(" Added " + String.join(", ", addedToList.toArray(new String[addedToList.size()])) + " to saved list of Ops");
}
try {
if(Main.save())sendMessage(channel, output.toString());
} catch (IOException e) {
sendMessage(channel, "Error occured while saving bot config. :[");
e.printStackTrace();
}
}
else{
if(!opList.contains(recipient)){
currChannel.addOp(recipient);
try {
if(Main.save())sendMessage(channel, recipient + " has been added to the saved Op list");
} catch (IOException e) {
sendMessage(channel, "Error occured while saving bot config. :[");
e.printStackTrace();
}
}
}
}
@Override
protected void onDeop(String channel, String sourceNick,
String sourceLogin, String sourceHostname, String recipient) {
if (recipient.equals(this.getNick())){
server.getChannel(channel).setBotIsOp(false);
}
else{
IRCChannel currChannel = server.getChannel(channel);
Set<String> opList = currChannel.getOpList();
if(opList.contains(recipient)){
currChannel.removeOp(recipient);
try {
if(Main.save())sendMessage(channel, recipient + " has been removed from the saved Op list");
} catch (IOException e) {
sendMessage(channel, "Error occured while saving bot config. :[");
e.printStackTrace();
}
}
}
}
public void onUserList(String channel, User[] users) {
IRCChannel currChannel = server.getChannel(channel);
Set<String> opList = currChannel.getOpList();
server.getChannel(channel).setBotIsOp(true);
List<String> addedToList = new ArrayList<String>();
for (int i = 0; i < users.length; i++) {
User user = users[i];
String nick = user.getNick();
if (!opList.contains(nick)){
if(user.isOp() && nick != this.getNick()){//user is op'd but is not on bots op list, so add them to the list
currChannel.addOp(nick);
addedToList.add(nick);
}
}
}
StringBuilder output = new StringBuilder("Bot initialized.");
if (addedToList.size() > 0){
output.append(" Added " + String.join(", ", addedToList.toArray(new String[addedToList.size()])) + " to this bots known Ops");
}
try {
if(Main.save())sendMessage(channel, output.toString());
} catch (IOException e) {
sendMessage(channel, "Error occured while saving bot config. :[");
e.printStackTrace();
}
}
public void setVoiceUsers(boolean voiceUsers) {
this.voiceUsers = voiceUsers;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((owner == null) ? 0 : owner.hashCode());
result = prime * result + ((server == null) ? 0 : server.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (!(obj instanceof FelisBotus))
return false;
FelisBotus other = (FelisBotus) obj;
if (owner == null) {
if (other.owner != null)
return false;
} else if (!owner.equals(other.owner))
return false;
if (server == null) {
if (other.server != null)
return false;
} else if (!server.equals(other.server))
return false;
return true;
}
}
|
moved bot reading list of ops to on userlist, while still doing the
opping of others when this bot becomes op. (some of this was in the last
commit too)
|
FelisBotus/src/com/wc1/felisBotus/FelisBotus.java
|
moved bot reading list of ops to on userlist, while still doing the opping of others when this bot becomes op. (some of this was in the last commit too)
|
|
Java
|
apache-2.0
|
8339715a3b3cbe3b46041182b9433238bda6889c
| 0
|
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
|
// 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.jetbrains.python.console;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.jetbrains.python.run.PythonRunConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public abstract class PythonConsoleRunnerFactory {
@NotNull
public static PythonConsoleRunnerFactory getInstance() {
return ServiceManager.getService(PythonConsoleRunnerFactory.class);
}
@NotNull
public abstract PydevConsoleRunner createConsoleRunner(@NotNull final Project project,
@Nullable Module contextModule);
@NotNull
public abstract PydevConsoleRunner createConsoleRunnerWithFile(@NotNull final Project project,
@Nullable Module contextModule, @Nullable String runFileText, @NotNull
PythonRunConfiguration config);
}
|
python/src/com/jetbrains/python/console/PythonConsoleRunnerFactory.java
|
// 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.jetbrains.python.console;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.jetbrains.python.run.PythonRunConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public abstract class PythonConsoleRunnerFactory {
@NotNull
public static PythonConsoleRunnerFactory getInstance() {
return ApplicationManager.getApplication().getComponent(PythonConsoleRunnerFactory.class);
}
@NotNull
public abstract PydevConsoleRunner createConsoleRunner(@NotNull final Project project,
@Nullable Module contextModule);
@NotNull
public abstract PydevConsoleRunner createConsoleRunnerWithFile(@NotNull final Project project,
@Nullable Module contextModule, @Nullable String runFileText, @NotNull
PythonRunConfiguration config);
}
|
Make DjangoAwarePythonConsoleRunnerFactory an application service (PY-41923)
GitOrigin-RevId: af84cc2362992afd34129cc56443cd5ff8c3eed1
|
python/src/com/jetbrains/python/console/PythonConsoleRunnerFactory.java
|
Make DjangoAwarePythonConsoleRunnerFactory an application service (PY-41923)
|
|
Java
|
apache-2.0
|
c18328be38209a1ee1ba0523176b635a1f5339bd
| 0
|
DBCG/cql_measure_processor,DBCG/cqf-ruler,DBCG/cqf-ruler,DBCG/cqf-ruler,DBCG/cql_measure_processor
|
package org.opencds.cqf.r4.providers;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.hl7.fhir.r4.model.Bundle;
import org.hl7.fhir.r4.model.Coding;
import org.hl7.fhir.r4.model.Composition;
import org.hl7.fhir.r4.model.Extension;
import org.hl7.fhir.r4.model.IdType;
import org.hl7.fhir.r4.model.ListResource;
import org.hl7.fhir.r4.model.Measure;
import org.hl7.fhir.r4.model.MeasureReport;
import org.hl7.fhir.r4.model.Meta;
import org.hl7.fhir.r4.model.Narrative;
import org.hl7.fhir.r4.model.Organization;
import org.hl7.fhir.r4.model.Parameters;
import org.hl7.fhir.r4.model.Reference;
import org.hl7.fhir.r4.model.RelatedArtifact;
import org.hl7.fhir.r4.model.Resource;
import org.hl7.fhir.r4.model.StringType;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.utilities.xhtml.XhtmlNode;
import org.opencds.cqf.common.evaluation.EvaluationProviderFactory;
import org.opencds.cqf.common.providers.LibraryResolutionProvider;
import org.opencds.cqf.cql.execution.LibraryLoader;
import org.opencds.cqf.library.r4.NarrativeProvider;
import org.opencds.cqf.measure.r4.CqfMeasure;
import org.opencds.cqf.r4.evaluation.MeasureEvaluation;
import org.opencds.cqf.r4.evaluation.MeasureEvaluationSeed;
import org.opencds.cqf.r4.helpers.LibraryHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.jpa.dao.DaoRegistry;
import ca.uhn.fhir.jpa.dao.IFhirResourceDao;
import ca.uhn.fhir.jpa.rp.r4.MeasureResourceProvider;
import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
import ca.uhn.fhir.model.api.IQueryParameterType;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.Operation;
import ca.uhn.fhir.rest.annotation.OperationParam;
import ca.uhn.fhir.rest.annotation.OptionalParam;
import ca.uhn.fhir.rest.annotation.RequiredParam;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.param.StringParam;
import ca.uhn.fhir.rest.param.TokenParam;
import ca.uhn.fhir.rest.param.TokenParamModifier;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
public class MeasureOperationsProvider {
private NarrativeProvider narrativeProvider;
private HQMFProvider hqmfProvider;
private DataRequirementsProvider dataRequirementsProvider;
private LibraryResolutionProvider<org.hl7.fhir.r4.model.Library> libraryResolutionProvider;
private MeasureResourceProvider measureResourceProvider;
private DaoRegistry registry;
private EvaluationProviderFactory factory;
private static final Logger logger = LoggerFactory.getLogger(MeasureOperationsProvider.class);
public MeasureOperationsProvider(DaoRegistry registry, EvaluationProviderFactory factory, NarrativeProvider narrativeProvider, HQMFProvider hqmfProvider, LibraryResolutionProvider<org.hl7.fhir.r4.model.Library> libraryResolutionProvider,
MeasureResourceProvider measureResourceProvider) {
this.registry = registry;
this.factory = factory;
this.libraryResolutionProvider = libraryResolutionProvider;
this.narrativeProvider = narrativeProvider;
this.hqmfProvider = hqmfProvider;
this.dataRequirementsProvider = new DataRequirementsProvider();
this.measureResourceProvider = measureResourceProvider;
}
@Operation(name = "$hqmf", idempotent = true, type = Measure.class)
public Parameters hqmf(@IdParam IdType theId) {
Measure theResource = this.measureResourceProvider.getDao().read(theId);
String hqmf = this.generateHQMF(theResource);
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(hqmf));
return p;
}
@Operation(name = "$refresh-generated-content", type = Measure.class)
public MethodOutcome refreshGeneratedContent(HttpServletRequest theRequest, RequestDetails theRequestDetails,
@IdParam IdType theId) {
Measure theResource = this.measureResourceProvider.getDao().read(theId);
theResource.getRelatedArtifact().removeIf(relatedArtifact -> relatedArtifact.getType().equals(RelatedArtifact.RelatedArtifactType.DEPENDSON));
CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource, this.libraryResolutionProvider);
// Ensure All Related Artifacts for all referenced Libraries
if (!cqfMeasure.getRelatedArtifact().isEmpty()) {
for (RelatedArtifact relatedArtifact : cqfMeasure.getRelatedArtifact()) {
boolean artifactExists = false;
// logger.info("Related Artifact: " + relatedArtifact.getUrl());
for (RelatedArtifact resourceArtifact : theResource.getRelatedArtifact()) {
if (resourceArtifact.equalsDeep(relatedArtifact)) {
// logger.info("Equals deep true");
artifactExists = true;
break;
}
}
if (!artifactExists) {
theResource.addRelatedArtifact(relatedArtifact.copy());
}
}
}
try {
Narrative n = this.narrativeProvider.getNarrative(this.measureResourceProvider.getContext(), cqfMeasure);
theResource.setText(n.copy());
} catch (Exception e) {
//Ignore the exception so the resource still gets updated
}
return this.measureResourceProvider.update(theRequest, theResource, theId,
theRequestDetails.getConditionalUrl(RestOperationTypeEnum.UPDATE), theRequestDetails);
}
@Operation(name = "$get-narrative", idempotent = true, type = Measure.class)
public Parameters getNarrative(@IdParam IdType theId) {
Measure theResource = this.measureResourceProvider.getDao().read(theId);
CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource, this.libraryResolutionProvider);
Narrative n = this.narrativeProvider.getNarrative(this.measureResourceProvider.getContext(), cqfMeasure);
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(n.getDivAsString()));
return p;
}
private String generateHQMF(Measure theResource) {
CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource, this.libraryResolutionProvider);
return this.hqmfProvider.generateHQMF(cqfMeasure);
}
/*
*
* NOTE that the source, user, and pass parameters are not standard parameters
* for the FHIR $evaluate-measure operation
*
*/
@Operation(name = "$evaluate-measure", idempotent = true, type = Measure.class)
public MeasureReport evaluateMeasure(@IdParam IdType theId, @RequiredParam(name = "periodStart") String periodStart,
@RequiredParam(name = "periodEnd") String periodEnd, @OptionalParam(name = "measure") String measureRef,
@OptionalParam(name = "reportType") String reportType, @OptionalParam(name = "patient") String patientRef,
@OptionalParam(name = "productLine") String productLine,
@OptionalParam(name = "practitioner") String practitionerRef,
@OptionalParam(name = "lastReceivedOn") String lastReceivedOn,
@OptionalParam(name = "source") String source, @OptionalParam(name = "user") String user,
@OptionalParam(name = "pass") String pass) throws InternalErrorException, FHIRException {
LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResolutionProvider);
MeasureEvaluationSeed seed = new MeasureEvaluationSeed(this.factory, libraryLoader, this.libraryResolutionProvider);
Measure measure = this.measureResourceProvider.getDao().read(theId);
if (measure == null) {
throw new RuntimeException("Could not find Measure/" + theId.getIdPart());
}
seed.setup(measure, periodStart, periodEnd, productLine, source, user, pass);
// resolve report type
MeasureEvaluation evaluator = new MeasureEvaluation(seed.getDataProvider(), this.registry, seed.getMeasurementPeriod());
if (reportType != null) {
switch (reportType) {
case "patient":
return evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
case "patient-list":
return evaluator.evaluateSubjectListMeasure(seed.getMeasure(), seed.getContext(), practitionerRef);
case "population":
return evaluator.evaluatePopulationMeasure(seed.getMeasure(), seed.getContext());
default:
throw new IllegalArgumentException("Invalid report type: " + reportType);
}
}
// default report type is patient
MeasureReport report = evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
if (productLine != null)
{
Extension ext = new Extension();
ext.setUrl("http://hl7.org/fhir/us/cqframework/cqfmeasures/StructureDefinition/cqfm-productLine");
ext.setValue(new StringType(productLine));
report.addExtension(ext);
}
return report;
}
// @Operation(name = "$evaluate-measure-with-source", idempotent = true)
// public MeasureReport evaluateMeasure(@IdParam IdType theId,
// @OperationParam(name = "sourceData", min = 1, max = 1, type = Bundle.class) Bundle sourceData,
// @OperationParam(name = "periodStart", min = 1, max = 1) String periodStart,
// @OperationParam(name = "periodEnd", min = 1, max = 1) String periodEnd) {
// if (periodStart == null || periodEnd == null) {
// throw new IllegalArgumentException("periodStart and periodEnd are required for measure evaluation");
// }
// LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
// MeasureEvaluationSeed seed = new MeasureEvaluationSeed(this.factory, libraryLoader, this.libraryResourceProvider);
// Measure measure = this.getDao().read(theId);
// if (measure == null) {
// throw new RuntimeException("Could not find Measure/" + theId.getIdPart());
// }
// seed.setup(measure, periodStart, periodEnd, null, null, null, null);
// BundleDataProviderStu3 bundleProvider = new BundleDataProviderStu3(sourceData);
// bundleProvider.setTerminologyProvider(provider.getTerminologyProvider());
// seed.getContext().registerDataProvider("http://hl7.org/fhir", bundleProvider);
// MeasureEvaluation evaluator = new MeasureEvaluation(bundleProvider, seed.getMeasurementPeriod());
// return evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), "");
// }
@Operation(name = "$care-gaps", idempotent = true, type = Measure.class)
public Bundle careGapsReport(@RequiredParam(name = "periodStart") String periodStart,
@RequiredParam(name = "periodEnd") String periodEnd,
@RequiredParam(name = "subject") String subject, @OptionalParam(name = "topic") String topic) {
//TODO: topic should be many
if (subject == null || subject.equals("")) {
throw new IllegalArgumentException("Subject is required.");
}
//TODO: this is an org hack. Need to figure out what the right thing is.
IFhirResourceDao<Organization> orgDao = this.registry.getResourceDao(Organization.class);
var org = orgDao.search(new SearchParameterMap()).getResources(0, 1);
SearchParameterMap theParams = new SearchParameterMap();
// if (theId != null) {
// var measureParam = new StringParam(theId.getIdPart());
// theParams.add("_id", measureParam);
// }
if (topic != null && !topic.equals("")) {
var topicParam = new TokenParam(topic);
theParams.add("topic", topicParam);
}
List<IBaseResource> measures = this.measureResourceProvider.getDao().search(theParams).getResources(0, 1000);
Bundle careGapReport = new Bundle();
careGapReport.setType(Bundle.BundleType.DOCUMENT);
Composition composition = new Composition();
composition.setStatus(Composition.CompositionStatus.FINAL)
.setSubject(new Reference(subject.startsWith("Patient/") ? subject : "Patient/" + subject))
.setTitle("Care Gap Report");
List<MeasureReport> reports = new ArrayList<>();
MeasureReport report = null;
for (IBaseResource resource : measures) {
Measure measure = (Measure) resource;
Composition.SectionComponent section = new Composition.SectionComponent();
if (measure.hasTitle()) {
section.setTitle(measure.getTitle());
}
LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResolutionProvider);
MeasureEvaluationSeed seed = new MeasureEvaluationSeed(this.factory, libraryLoader, this.libraryResolutionProvider);
seed.setup(measure, periodStart, periodEnd, null, null, null, null);
MeasureEvaluation evaluator = new MeasureEvaluation(seed.getDataProvider(), this.registry, seed.getMeasurementPeriod());
// TODO - this is configured for patient-level evaluation only
report = evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), subject);
report.setId(UUID.randomUUID().toString());
report.setDate(new Date());
report.setImprovementNotation(measure.getImprovementNotation());
//TODO: this is an org hack
report.setReporter(new Reference("Organization/" + org.get(0).getIdElement().getIdPart()));
report.setMeta(new Meta().addProfile("http://hl7.org/fhir/us/davinci-deqm/StructureDefinition/indv-measurereport-deqm"));
section.setFocus(new Reference("MeasureReport/" + report.getId()));
//TODO: DetectedIssue
//section.addEntry(new Reference("MeasureReport/" + report.getId()));
if (report.hasGroup() && measure.hasScoring()) {
int numerator = 0;
int denominator = 0;
for (MeasureReport.MeasureReportGroupComponent group : report.getGroup()) {
if (group.hasPopulation()) {
for (MeasureReport.MeasureReportGroupPopulationComponent population : group.getPopulation()) {
// TODO - currently configured for measures with only 1 numerator and 1
// denominator
if (population.hasCode()) {
if (population.getCode().hasCoding()) {
for (Coding coding : population.getCode().getCoding()) {
if (coding.hasCode()) {
if (coding.getCode().equals("numerator") && population.hasCount()) {
numerator = population.getCount();
} else if (coding.getCode().equals("denominator")
&& population.hasCount()) {
denominator = population.getCount();
}
}
}
}
}
}
}
}
double proportion = 0.0;
if (measure.getScoring().hasCoding() && denominator != 0) {
for (Coding coding : measure.getScoring().getCoding()) {
if (coding.hasCode() && coding.getCode().equals("proportion")) {
proportion = numerator / denominator;
}
}
}
// TODO - this is super hacky ... change once improvementNotation is specified
// as a code
if (measure.getImprovementNotation().getCodingFirstRep().getCode().toLowerCase().equals("increase")) {
if (proportion < 1.0) {
composition.addSection(section);
reports.add(report);
}
} else if (measure.getImprovementNotation().getCodingFirstRep().getCode().toLowerCase().equals("decrease")) {
if (proportion > 0.0) {
composition.addSection(section);
reports.add(report);
}
}
// TODO - add other types of improvement notation cases
}
}
careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(composition));
for (MeasureReport rep : reports) {
careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(rep));
}
return careGapReport;
}
@Operation(name = "$collect-data", idempotent = true, type = Measure.class)
public Parameters collectData(@IdParam IdType theId, @RequiredParam(name = "periodStart") String periodStart,
@RequiredParam(name = "periodEnd") String periodEnd, @OptionalParam(name = "patient") String patientRef,
@OptionalParam(name = "practitioner") String practitionerRef,
@OptionalParam(name = "lastReceivedOn") String lastReceivedOn) throws FHIRException {
// TODO: Spec says that the periods are not required, but I am not sure what to
// do when they aren't supplied so I made them required
MeasureReport report = evaluateMeasure(theId, periodStart, periodEnd, null, null, patientRef, null,
practitionerRef, lastReceivedOn, null, null, null);
report.setGroup(null);
Parameters parameters = new Parameters();
parameters.addParameter(
new Parameters.ParametersParameterComponent().setName("measurereport").setResource(report));
if (report.hasContained()) {
for (Resource contained : report.getContained()) {
if (contained instanceof Bundle) {
addEvaluatedResourcesToParameters((Bundle) contained, parameters);
}
}
}
// TODO: need a way to resolve referenced resources within the evaluated
// resources
// Should be able to use _include search with * wildcard, but HAPI doesn't
// support that
return parameters;
}
private void addEvaluatedResourcesToParameters(Bundle contained, Parameters parameters) {
Map<String, Resource> resourceMap = new HashMap<>();
if (contained.hasEntry()) {
for (Bundle.BundleEntryComponent entry : contained.getEntry()) {
if (entry.hasResource() && !(entry.getResource() instanceof ListResource)) {
if (!resourceMap.containsKey(entry.getResource().getIdElement().getValue())) {
parameters.addParameter(new Parameters.ParametersParameterComponent().setName("resource")
.setResource(entry.getResource()));
resourceMap.put(entry.getResource().getIdElement().getValue(), entry.getResource());
resolveReferences(entry.getResource(), parameters, resourceMap);
}
}
}
}
}
private void resolveReferences(Resource resource, Parameters parameters, Map<String, Resource> resourceMap) {
List<IBase> values;
for (BaseRuntimeChildDefinition child : this.measureResourceProvider.getContext().getResourceDefinition(resource).getChildren()) {
values = child.getAccessor().getValues(resource);
if (values == null || values.isEmpty()) {
continue;
}
else if (values.get(0) instanceof Reference
&& ((Reference) values.get(0)).getReferenceElement().hasResourceType()
&& ((Reference) values.get(0)).getReferenceElement().hasIdPart()) {
Resource fetchedResource = (Resource) registry
.getResourceDao(((Reference) values.get(0)).getReferenceElement().getResourceType())
.read(new IdType(((Reference) values.get(0)).getReferenceElement().getIdPart()));
if (!resourceMap.containsKey(fetchedResource.getIdElement().getValue())) {
parameters.addParameter(new Parameters.ParametersParameterComponent().setName("resource")
.setResource(fetchedResource));
resourceMap.put(fetchedResource.getIdElement().getValue(), fetchedResource);
}
}
}
}
// TODO - this needs a lot of work
@Operation(name = "$data-requirements", idempotent = true, type = Measure.class)
public org.hl7.fhir.r4.model.Library dataRequirements(@IdParam IdType theId,
@RequiredParam(name = "startPeriod") String startPeriod,
@RequiredParam(name = "endPeriod") String endPeriod) throws InternalErrorException, FHIRException {
Measure measure = this.measureResourceProvider.getDao().read(theId);
return this.dataRequirementsProvider.getDataRequirements(measure, this.libraryResolutionProvider);
}
@Operation(name = "$submit-data", idempotent = true, type = Measure.class)
public Resource submitData(RequestDetails details, @IdParam IdType theId,
@OperationParam(name = "measure-report", min = 1, max = 1, type = MeasureReport.class) MeasureReport report,
@OperationParam(name = "resource") List<IAnyResource> resources) {
Bundle transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION);
/*
* TODO - resource validation using $data-requirements operation (params are the
* provided id and the measurement period from the MeasureReport)
*
* TODO - profile validation ... not sure how that would work ... (get
* StructureDefinition from URL or must it be stored in Ruler?)
*/
transactionBundle.addEntry(createTransactionEntry(report));
for (IAnyResource resource : resources) {
Resource res = (Resource) resource;
if (res instanceof Bundle) {
for (Bundle.BundleEntryComponent entry : createTransactionBundle((Bundle) res).getEntry()) {
transactionBundle.addEntry(entry);
}
} else {
// Build transaction bundle
transactionBundle.addEntry(createTransactionEntry(res));
}
}
return (Resource) this.registry.getSystemDao().transaction(details, transactionBundle);
}
private Bundle createTransactionBundle(Bundle bundle) {
Bundle transactionBundle;
if (bundle != null) {
if (bundle.hasType() && bundle.getType() == Bundle.BundleType.TRANSACTION) {
transactionBundle = bundle;
} else {
transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION);
if (bundle.hasEntry()) {
for (Bundle.BundleEntryComponent entry : bundle.getEntry()) {
if (entry.hasResource()) {
transactionBundle.addEntry(createTransactionEntry(entry.getResource()));
}
}
}
}
} else {
transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION).setEntry(new ArrayList<>());
}
return transactionBundle;
}
private Bundle.BundleEntryComponent createTransactionEntry(Resource resource) {
Bundle.BundleEntryComponent transactionEntry = new Bundle.BundleEntryComponent().setResource(resource);
if (resource.hasId()) {
transactionEntry.setRequest(
new Bundle.BundleEntryRequestComponent().setMethod(Bundle.HTTPVerb.PUT).setUrl(resource.getId()));
} else {
transactionEntry.setRequest(new Bundle.BundleEntryRequestComponent().setMethod(Bundle.HTTPVerb.POST)
.setUrl(resource.fhirType()));
}
return transactionEntry;
}
}
|
r4/src/main/java/org/opencds/cqf/r4/providers/MeasureOperationsProvider.java
|
package org.opencds.cqf.r4.providers;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.hl7.fhir.r4.model.Bundle;
import org.hl7.fhir.r4.model.Coding;
import org.hl7.fhir.r4.model.Composition;
import org.hl7.fhir.r4.model.Extension;
import org.hl7.fhir.r4.model.IdType;
import org.hl7.fhir.r4.model.ListResource;
import org.hl7.fhir.r4.model.Measure;
import org.hl7.fhir.r4.model.MeasureReport;
import org.hl7.fhir.r4.model.Meta;
import org.hl7.fhir.r4.model.Narrative;
import org.hl7.fhir.r4.model.Organization;
import org.hl7.fhir.r4.model.Parameters;
import org.hl7.fhir.r4.model.Reference;
import org.hl7.fhir.r4.model.RelatedArtifact;
import org.hl7.fhir.r4.model.Resource;
import org.hl7.fhir.r4.model.StringType;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.utilities.xhtml.XhtmlNode;
import org.opencds.cqf.common.evaluation.EvaluationProviderFactory;
import org.opencds.cqf.common.providers.LibraryResolutionProvider;
import org.opencds.cqf.cql.execution.LibraryLoader;
import org.opencds.cqf.library.r4.NarrativeProvider;
import org.opencds.cqf.measure.r4.CqfMeasure;
import org.opencds.cqf.r4.evaluation.MeasureEvaluation;
import org.opencds.cqf.r4.evaluation.MeasureEvaluationSeed;
import org.opencds.cqf.r4.helpers.LibraryHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.jpa.dao.DaoRegistry;
import ca.uhn.fhir.jpa.dao.IFhirResourceDao;
import ca.uhn.fhir.jpa.rp.r4.MeasureResourceProvider;
import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
import ca.uhn.fhir.model.api.IQueryParameterType;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.Operation;
import ca.uhn.fhir.rest.annotation.OperationParam;
import ca.uhn.fhir.rest.annotation.OptionalParam;
import ca.uhn.fhir.rest.annotation.RequiredParam;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.param.StringParam;
import ca.uhn.fhir.rest.param.TokenParam;
import ca.uhn.fhir.rest.param.TokenParamModifier;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
public class MeasureOperationsProvider {
private NarrativeProvider narrativeProvider;
private HQMFProvider hqmfProvider;
private DataRequirementsProvider dataRequirementsProvider;
private LibraryResolutionProvider<org.hl7.fhir.r4.model.Library> libraryResolutionProvider;
private MeasureResourceProvider measureResourceProvider;
private DaoRegistry registry;
private EvaluationProviderFactory factory;
private static final Logger logger = LoggerFactory.getLogger(MeasureOperationsProvider.class);
public MeasureOperationsProvider(DaoRegistry registry, EvaluationProviderFactory factory, NarrativeProvider narrativeProvider, HQMFProvider hqmfProvider, LibraryResolutionProvider<org.hl7.fhir.r4.model.Library> libraryResolutionProvider,
MeasureResourceProvider measureResourceProvider) {
this.registry = registry;
this.factory = factory;
this.libraryResolutionProvider = libraryResolutionProvider;
this.narrativeProvider = narrativeProvider;
this.hqmfProvider = hqmfProvider;
this.dataRequirementsProvider = new DataRequirementsProvider();
this.measureResourceProvider = measureResourceProvider;
}
@Operation(name = "$hqmf", idempotent = true, type = Measure.class)
public Parameters hqmf(@IdParam IdType theId) {
Measure theResource = this.measureResourceProvider.getDao().read(theId);
String hqmf = this.generateHQMF(theResource);
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(hqmf));
return p;
}
@Operation(name = "$refresh-generated-content", type = Measure.class)
public MethodOutcome refreshGeneratedContent(HttpServletRequest theRequest, RequestDetails theRequestDetails,
@IdParam IdType theId) {
Measure theResource = this.measureResourceProvider.getDao().read(theId);
theResource.getRelatedArtifact().removeIf(relatedArtifact -> relatedArtifact.getType().equals(RelatedArtifact.RelatedArtifactType.DEPENDSON));
CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource, this.libraryResolutionProvider);
// Ensure All Related Artifacts for all referenced Libraries
if (!cqfMeasure.getRelatedArtifact().isEmpty()) {
for (RelatedArtifact relatedArtifact : cqfMeasure.getRelatedArtifact()) {
boolean artifactExists = false;
// logger.info("Related Artifact: " + relatedArtifact.getUrl());
for (RelatedArtifact resourceArtifact : theResource.getRelatedArtifact()) {
if (resourceArtifact.equalsDeep(relatedArtifact)) {
// logger.info("Equals deep true");
artifactExists = true;
break;
}
}
if (!artifactExists) {
theResource.addRelatedArtifact(relatedArtifact.copy());
}
}
}
try {
Narrative n = this.narrativeProvider.getNarrative(this.measureResourceProvider.getContext(), cqfMeasure);
theResource.setText(n.copy());
} catch (Exception e) {
//Ignore the exception so the resource still gets updated
}
return this.measureResourceProvider.update(theRequest, theResource, theId,
theRequestDetails.getConditionalUrl(RestOperationTypeEnum.UPDATE), theRequestDetails);
}
@Operation(name = "$get-narrative", idempotent = true, type = Measure.class)
public Parameters getNarrative(@IdParam IdType theId) {
Measure theResource = this.measureResourceProvider.getDao().read(theId);
CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource, this.libraryResolutionProvider);
Narrative n = this.narrativeProvider.getNarrative(this.measureResourceProvider.getContext(), cqfMeasure);
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(n.getDivAsString()));
return p;
}
private String generateHQMF(Measure theResource) {
CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource, this.libraryResolutionProvider);
return this.hqmfProvider.generateHQMF(cqfMeasure);
}
/*
*
* NOTE that the source, user, and pass parameters are not standard parameters
* for the FHIR $evaluate-measure operation
*
*/
@Operation(name = "$evaluate-measure", idempotent = true, type = Measure.class)
public MeasureReport evaluateMeasure(@IdParam IdType theId, @RequiredParam(name = "periodStart") String periodStart,
@RequiredParam(name = "periodEnd") String periodEnd, @OptionalParam(name = "measure") String measureRef,
@OptionalParam(name = "reportType") String reportType, @OptionalParam(name = "patient") String patientRef,
@OptionalParam(name = "productLine") String productLine,
@OptionalParam(name = "practitioner") String practitionerRef,
@OptionalParam(name = "lastReceivedOn") String lastReceivedOn,
@OptionalParam(name = "source") String source, @OptionalParam(name = "user") String user,
@OptionalParam(name = "pass") String pass) throws InternalErrorException, FHIRException {
LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResolutionProvider);
MeasureEvaluationSeed seed = new MeasureEvaluationSeed(this.factory, libraryLoader, this.libraryResolutionProvider);
Measure measure = this.measureResourceProvider.getDao().read(theId);
if (measure == null) {
throw new RuntimeException("Could not find Measure/" + theId.getIdPart());
}
seed.setup(measure, periodStart, periodEnd, productLine, source, user, pass);
// resolve report type
MeasureEvaluation evaluator = new MeasureEvaluation(seed.getDataProvider(), this.registry, seed.getMeasurementPeriod());
if (reportType != null) {
switch (reportType) {
case "patient":
return evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
case "patient-list":
return evaluator.evaluateSubjectListMeasure(seed.getMeasure(), seed.getContext(), practitionerRef);
case "population":
return evaluator.evaluatePopulationMeasure(seed.getMeasure(), seed.getContext());
default:
throw new IllegalArgumentException("Invalid report type: " + reportType);
}
}
// default report type is patient
MeasureReport report = evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
if (productLine != null)
{
Extension ext = new Extension();
ext.setUrl("http://hl7.org/fhir/us/cqframework/cqfmeasures/StructureDefinition/cqfm-productLine");
ext.setValue(new StringType(productLine));
report.addExtension(ext);
}
return report;
}
// @Operation(name = "$evaluate-measure-with-source", idempotent = true)
// public MeasureReport evaluateMeasure(@IdParam IdType theId,
// @OperationParam(name = "sourceData", min = 1, max = 1, type = Bundle.class) Bundle sourceData,
// @OperationParam(name = "periodStart", min = 1, max = 1) String periodStart,
// @OperationParam(name = "periodEnd", min = 1, max = 1) String periodEnd) {
// if (periodStart == null || periodEnd == null) {
// throw new IllegalArgumentException("periodStart and periodEnd are required for measure evaluation");
// }
// LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
// MeasureEvaluationSeed seed = new MeasureEvaluationSeed(this.factory, libraryLoader, this.libraryResourceProvider);
// Measure measure = this.getDao().read(theId);
// if (measure == null) {
// throw new RuntimeException("Could not find Measure/" + theId.getIdPart());
// }
// seed.setup(measure, periodStart, periodEnd, null, null, null, null);
// BundleDataProviderStu3 bundleProvider = new BundleDataProviderStu3(sourceData);
// bundleProvider.setTerminologyProvider(provider.getTerminologyProvider());
// seed.getContext().registerDataProvider("http://hl7.org/fhir", bundleProvider);
// MeasureEvaluation evaluator = new MeasureEvaluation(bundleProvider, seed.getMeasurementPeriod());
// return evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), "");
// }
@Operation(name = "$care-gaps", idempotent = true, type = Measure.class)
public Bundle careGapsReport(@RequiredParam(name = "periodStart") String periodStart,
@RequiredParam(name = "periodEnd") String periodEnd,
@RequiredParam(name = "subject") String subject, @OptionalParam(name = "topic") String topic) {
if (subject == null || subject.equals("")) {
throw new IllegalArgumentException("Subject is required.");
}
//TODO: this is an org hack. Need to figure out what the right thing is.
IFhirResourceDao<Organization> orgDao = this.registry.getResourceDao(Organization.class);
var org = orgDao.search(new SearchParameterMap()).getResources(0, 1);
SearchParameterMap theParams = new SearchParameterMap();
// if (theId != null) {
// var measureParam = new StringParam(theId.getIdPart());
// theParams.add("_id", measureParam);
// }
if (topic != null && !topic.equals("")) {
var topicParam = new TokenParam(topic);
theParams.add("topic", topicParam);
}
List<IBaseResource> measures = this.measureResourceProvider.getDao().search(theParams).getResources(0, 1000);
Bundle careGapReport = new Bundle();
careGapReport.setType(Bundle.BundleType.DOCUMENT);
Composition composition = new Composition();
composition.setStatus(Composition.CompositionStatus.FINAL)
.setSubject(new Reference(subject.startsWith("Patient/") ? subject : "Patient/" + subject))
.setTitle("Care Gap Report");
List<MeasureReport> reports = new ArrayList<>();
MeasureReport report = null;
for (IBaseResource resource : measures) {
Measure measure = (Measure) resource;
Composition.SectionComponent section = new Composition.SectionComponent();
if (measure.hasTitle()) {
section.setTitle(measure.getTitle());
}
LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResolutionProvider);
MeasureEvaluationSeed seed = new MeasureEvaluationSeed(this.factory, libraryLoader, this.libraryResolutionProvider);
seed.setup(measure, periodStart, periodEnd, null, null, null, null);
MeasureEvaluation evaluator = new MeasureEvaluation(seed.getDataProvider(), this.registry, seed.getMeasurementPeriod());
// TODO - this is configured for patient-level evaluation only
report = evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), subject);
report.setId(UUID.randomUUID().toString());
report.setDate(new Date());
report.setImprovementNotation(measure.getImprovementNotation());
//TODO: this is an org hack
report.setReporter(new Reference("Organization/" + org.get(0).getIdElement().getIdPart()));
report.setMeta(new Meta().addProfile("http://hl7.org/fhir/us/davinci-deqm/StructureDefinition/indv-measurereport-deqm"));
section.setFocus(new Reference("MeasureReport/" + report.getId()));
//TODO: DetectedIssue
//section.addEntry(new Reference("MeasureReport/" + report.getId()));
if (report.hasGroup() && measure.hasScoring()) {
int numerator = 0;
int denominator = 0;
for (MeasureReport.MeasureReportGroupComponent group : report.getGroup()) {
if (group.hasPopulation()) {
for (MeasureReport.MeasureReportGroupPopulationComponent population : group.getPopulation()) {
// TODO - currently configured for measures with only 1 numerator and 1
// denominator
if (population.hasCode()) {
if (population.getCode().hasCoding()) {
for (Coding coding : population.getCode().getCoding()) {
if (coding.hasCode()) {
if (coding.getCode().equals("numerator") && population.hasCount()) {
numerator = population.getCount();
} else if (coding.getCode().equals("denominator")
&& population.hasCount()) {
denominator = population.getCount();
}
}
}
}
}
}
}
}
double proportion = 0.0;
if (measure.getScoring().hasCoding() && denominator != 0) {
for (Coding coding : measure.getScoring().getCoding()) {
if (coding.hasCode() && coding.getCode().equals("proportion")) {
proportion = numerator / denominator;
}
}
}
// TODO - this is super hacky ... change once improvementNotation is specified
// as a code
if (measure.getImprovementNotation().getCodingFirstRep().getCode().toLowerCase().equals("increase")) {
if (proportion < 1.0) {
composition.addSection(section);
reports.add(report);
}
} else if (measure.getImprovementNotation().getCodingFirstRep().getCode().toLowerCase().equals("decrease")) {
if (proportion > 0.0) {
composition.addSection(section);
reports.add(report);
}
}
// TODO - add other types of improvement notation cases
}
}
careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(composition));
for (MeasureReport rep : reports) {
careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(rep));
}
return careGapReport;
}
@Operation(name = "$collect-data", idempotent = true, type = Measure.class)
public Parameters collectData(@IdParam IdType theId, @RequiredParam(name = "periodStart") String periodStart,
@RequiredParam(name = "periodEnd") String periodEnd, @OptionalParam(name = "patient") String patientRef,
@OptionalParam(name = "practitioner") String practitionerRef,
@OptionalParam(name = "lastReceivedOn") String lastReceivedOn) throws FHIRException {
// TODO: Spec says that the periods are not required, but I am not sure what to
// do when they aren't supplied so I made them required
MeasureReport report = evaluateMeasure(theId, periodStart, periodEnd, null, null, patientRef, null,
practitionerRef, lastReceivedOn, null, null, null);
report.setGroup(null);
Parameters parameters = new Parameters();
parameters.addParameter(
new Parameters.ParametersParameterComponent().setName("measurereport").setResource(report));
if (report.hasContained()) {
for (Resource contained : report.getContained()) {
if (contained instanceof Bundle) {
addEvaluatedResourcesToParameters((Bundle) contained, parameters);
}
}
}
// TODO: need a way to resolve referenced resources within the evaluated
// resources
// Should be able to use _include search with * wildcard, but HAPI doesn't
// support that
return parameters;
}
private void addEvaluatedResourcesToParameters(Bundle contained, Parameters parameters) {
Map<String, Resource> resourceMap = new HashMap<>();
if (contained.hasEntry()) {
for (Bundle.BundleEntryComponent entry : contained.getEntry()) {
if (entry.hasResource() && !(entry.getResource() instanceof ListResource)) {
if (!resourceMap.containsKey(entry.getResource().getIdElement().getValue())) {
parameters.addParameter(new Parameters.ParametersParameterComponent().setName("resource")
.setResource(entry.getResource()));
resourceMap.put(entry.getResource().getIdElement().getValue(), entry.getResource());
resolveReferences(entry.getResource(), parameters, resourceMap);
}
}
}
}
}
private void resolveReferences(Resource resource, Parameters parameters, Map<String, Resource> resourceMap) {
List<IBase> values;
for (BaseRuntimeChildDefinition child : this.measureResourceProvider.getContext().getResourceDefinition(resource).getChildren()) {
values = child.getAccessor().getValues(resource);
if (values == null || values.isEmpty()) {
continue;
}
else if (values.get(0) instanceof Reference
&& ((Reference) values.get(0)).getReferenceElement().hasResourceType()
&& ((Reference) values.get(0)).getReferenceElement().hasIdPart()) {
Resource fetchedResource = (Resource) registry
.getResourceDao(((Reference) values.get(0)).getReferenceElement().getResourceType())
.read(new IdType(((Reference) values.get(0)).getReferenceElement().getIdPart()));
if (!resourceMap.containsKey(fetchedResource.getIdElement().getValue())) {
parameters.addParameter(new Parameters.ParametersParameterComponent().setName("resource")
.setResource(fetchedResource));
resourceMap.put(fetchedResource.getIdElement().getValue(), fetchedResource);
}
}
}
}
// TODO - this needs a lot of work
@Operation(name = "$data-requirements", idempotent = true, type = Measure.class)
public org.hl7.fhir.r4.model.Library dataRequirements(@IdParam IdType theId,
@RequiredParam(name = "startPeriod") String startPeriod,
@RequiredParam(name = "endPeriod") String endPeriod) throws InternalErrorException, FHIRException {
Measure measure = this.measureResourceProvider.getDao().read(theId);
return this.dataRequirementsProvider.getDataRequirements(measure, this.libraryResolutionProvider);
}
@Operation(name = "$submit-data", idempotent = true, type = Measure.class)
public Resource submitData(RequestDetails details, @IdParam IdType theId,
@OperationParam(name = "measure-report", min = 1, max = 1, type = MeasureReport.class) MeasureReport report,
@OperationParam(name = "resource") List<IAnyResource> resources) {
Bundle transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION);
/*
* TODO - resource validation using $data-requirements operation (params are the
* provided id and the measurement period from the MeasureReport)
*
* TODO - profile validation ... not sure how that would work ... (get
* StructureDefinition from URL or must it be stored in Ruler?)
*/
transactionBundle.addEntry(createTransactionEntry(report));
for (IAnyResource resource : resources) {
Resource res = (Resource) resource;
if (res instanceof Bundle) {
for (Bundle.BundleEntryComponent entry : createTransactionBundle((Bundle) res).getEntry()) {
transactionBundle.addEntry(entry);
}
} else {
// Build transaction bundle
transactionBundle.addEntry(createTransactionEntry(res));
}
}
return (Resource) this.registry.getSystemDao().transaction(details, transactionBundle);
}
private Bundle createTransactionBundle(Bundle bundle) {
Bundle transactionBundle;
if (bundle != null) {
if (bundle.hasType() && bundle.getType() == Bundle.BundleType.TRANSACTION) {
transactionBundle = bundle;
} else {
transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION);
if (bundle.hasEntry()) {
for (Bundle.BundleEntryComponent entry : bundle.getEntry()) {
if (entry.hasResource()) {
transactionBundle.addEntry(createTransactionEntry(entry.getResource()));
}
}
}
}
} else {
transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION).setEntry(new ArrayList<>());
}
return transactionBundle;
}
private Bundle.BundleEntryComponent createTransactionEntry(Resource resource) {
Bundle.BundleEntryComponent transactionEntry = new Bundle.BundleEntryComponent().setResource(resource);
if (resource.hasId()) {
transactionEntry.setRequest(
new Bundle.BundleEntryRequestComponent().setMethod(Bundle.HTTPVerb.PUT).setUrl(resource.getId()));
} else {
transactionEntry.setRequest(new Bundle.BundleEntryRequestComponent().setMethod(Bundle.HTTPVerb.POST)
.setUrl(resource.fhirType()));
}
return transactionEntry;
}
}
|
Added note
|
r4/src/main/java/org/opencds/cqf/r4/providers/MeasureOperationsProvider.java
|
Added note
|
|
Java
|
apache-2.0
|
94508d78373e267a9e5645081a997fbfeab466ac
| 0
|
addcninblue/Airplane
|
/**
* Airplane Airlines simulator
* @author Addison Chan, Kyle Bascomb
* @version 11/04/16
*/
import java.util.Scanner;
import java.util.ArrayList;
public class AirlineCompany {
private static Airplane airplane;
private static ArrayList<Passenger> passengers;
public static void main (String [] args){
airplane = new Airplane();
passengers = new ArrayList<Passenger>();
Scanner in = new Scanner(System.in);
System.out.println("Welcome to Java Airlines.");
while(true){
System.out.println("Please select what you would like to do:");
System.out.println("1. Display Occupancy");
System.out.println("2. Reserve seats manually");
System.out.println("3. Reserve seats automatically");
System.out.println("4. Preferential seating arrangement");
System.out.println("5. Cancel seating by name or seat number");
System.out.println("6. Print all passenger info");
System.out.println("7. Print all reserved seats info");
System.out.println("8. Reserve seats by seat class and preferential seating");
System.out.println("0. Exit");
System.out.print("> ");
int choice = 0; // allows for loop to restart
try{
choice = in.nextInt();
} catch (Exception e){
System.out.println("Not a choice");
in.nextLine();
continue;
}
System.out.println();
if (choice == 0)
break; // kills loop
switch (choice){
case 1:
displayOccupancy();
break;
case 2:
reserveSeatsManually();
break;
case 3:
reserveSeatsAutomatically();
break;
case 4:
preferentialSeating();
break;
case 5:
cancelSeats();
break;
case 6:
printPassengerInfo();
break;
case 7:
printReservedSeatsInfo();
break;
case 8:
reserveSeatsSpecial();
break;
}
}
System.out.println("Thanks for flying Java!");
}
// 1
/**
* Prints out a table of passengers
* (Postcondition: Prints out table of passengers)
* (Precondition: Airplane is initialized)
*/
public static void displayOccupancy(){
int vacant = airplane.getAirplaneSeats().length * airplane.getAirplaneSeats()[0].length; // gets number of seats in an airplane
int occupied = 0;
airplane.getAirplaneSeats()[1][2].isVacant = false;
System.out.println("Airplane Layout:");
System.out.print(" ");
for(int column = 0; column < airplane.getAirplaneSeats().length; column++){
System.out.format("%3s", column + 1);
}
System.out.println();
for(int row = 0; row < airplane.getAirplaneSeats()[0].length ; row++){
System.out.print((char)(row + 65) + " ");
for(int column = 0; column < airplane.getAirplaneSeats().length ; column++){
if(airplane.getAirplaneSeats()[column][row].isVacant)
System.out.print("[ ]");
else {
vacant--;
occupied++;
System.out.print("[x]");
}
}
System.out.println();
}
System.out.format("Seats Vacant: %s | Seats Occupied: %s", vacant, occupied);
System.out.println(); // for format
System.out.println(); // to make newline before prompt again
}
// 2
/**
* Reserve seats manually
* (Postcondition: Reserves seats)
* (Precondition: Airplane is initialized)
*/
public static void reserveSeatsManually(){
String firstName;
String lastName;
int row;
int column;
Scanner in = new Scanner(System.in);
System.out.print("Please enter your first name: ");
firstName = in.nextLine();
System.out.print("Please enter your last name: ");
lastName = in.nextLine();
System.out.print("Please enter the seat you would like to reserve, ie. A1: ");
String userChoice = in.nextLine();
// get input for seat
try {
char rowChar = userChoice.charAt(0);
if('a' <= rowChar && rowChar <= 'z')
rowChar = (char) (rowChar - 32);
else if (rowChar < 'A' || 'Z' < rowChar)
throw new Exception("Not valid row");
row = rowChar - 64;
if (userChoice.length() == 2)
column = Integer.parseInt(userChoice.substring(1,2));
else if (userChoice.length() == 3)
column = Integer.parseInt(userChoice.substring(1,3));
else
throw new Exception("not valid input");
} catch(Exception e) {
System.out.println("That was not a valid input");
System.out.println();
return;
}
passengers.add(new Passenger(firstName, lastName, row, column)); // adds new passenger to list
airplane.setAirplaneSeatName(row, column, firstName, lastName); // adds passenger to
// Debugging purposes
// System.out.format("%s%s %s %s",
// passengers.get(0).getColumn(),
// passengers.get(0).getRow(),
// passengers.get(0).getFirstName(),
// passengers.get(0).getLastName());
System.out.println();
}
// 3
/**
* Reserve seats automatically
* (Postcondition: Reserves seats)
* (Precondition: Airplane is initialized)
*/
public static void reserveSeatsAutomatically(){
}
// 4
/**
* Reserve seats with preferences
* (Postcondition: Reserves seats)
* (Precondition: Airplane is initialized)
*/
public static void preferentialSeating(){
}
// 5
/**
* Cancel seats
* (Postcondition: Cancels seats)
* (Precondition: Airplane is initialized)
*/
public static void cancelSeats(){
}
// 6
/**
* Prints passenger info
* (Postcondition: Prints passenger info)
* (Precondition: Airplane is initialized)
*/
public static void printPassengerInfo(){
}
// 7
/**
* Prints reserved seats info
* (Postcondition: Prints reserved seats info)
* (Precondition: Airplane is initialized)
*/
public static void printReservedSeatsInfo(){
}
// 8
/**
* Reserve seats by seat class and preferential seating
* (Postcondition: Reserves seats)
* (Precondition: Airplane is initialized)
*/
public static void reserveSeatsSpecial(){
}
}
|
AirlineCompany.java
|
/**
* Airplane Airlines simulator
* @author Addison Chan, Kyle Bascomb
* @version 11/04/16
*/
import java.util.Scanner;
public class AirlineCompany {
private static Airplane airplane;
public static void main (String [] args){
airplane = new Airplane();
Scanner in = new Scanner(System.in);
System.out.println("Welcome to Java Airlines.");
while(true){
System.out.println("Please select what you would like to do:");
System.out.println("1. Display Occupancy");
System.out.println("2. Reserve seats manually");
System.out.println("3. Reserve seats automatically");
System.out.println("4. Preferential seating arrangement");
System.out.println("5. Cancel seating by name or seat number");
System.out.println("6. Print all passenger info");
System.out.println("7. Print all reserved seats info");
System.out.println("8. Reserve seats by seat class and preferential seating");
System.out.println("0. Exit");
System.out.print("> ");
int choice = 0; // allows for loop to restart
try{
choice = in.nextInt();
} catch (Exception e){
System.out.println("Not a choice");
in.nextLine();
continue;
}
if (choice == 0)
break; // kills loop
switch (choice){
case 1:
displayOccupancy();
break;
case 2:
reserveSeatsManually();
break;
case 3:
reserveSeatsAutomatically();
break;
case 4:
preferentialSeating();
break;
case 5:
cancelSeats();
break;
case 6:
printPassengerInfo();
break;
case 7:
printReservedSeatsInfo();
break;
case 8:
reserveSeatsSpecial();
break;
}
}
System.out.println("Thanks for flying Java!");
}
// 1
/**
* prints out a table of passengers
* (Postcondition: Prints out table of passengers)
* (Precondition: Airplane is initialized)
*/
public static void displayOccupancy(){
airplane.airplaneSeats[1][2].isVacant = false;
for(int row = 0; row < airplane.airplaneSeats[0].length ; row++){
for(int column = 0; column < airplane.airplaneSeats.length ; column++){
if(airplane.airplaneSeats[column][row].isVacant)
System.out.print("[ ]");
else
System.out.print("[x]");
}
System.out.println();
}
}
// 2
/**
* Reserve seats manually
* (Postcondition: Reserves seats)
* (Precondition: Airplane is initialized)
*/
public static void reserveSeatsManually(){
}
// 3
/**
* Reserve seats automatically
* (Postcondition: Reserves seats)
* (Precondition: Airplane is initialized)
*/
public static void reserveSeatsAutomatically(){
}
// 4
/**
* Reserve seats with preferences
* (Postcondition: Reserves seats)
* (Precondition: Airplane is initialized)
*/
public static void preferentialSeating(){
}
// 5
/**
* Cancel seats
* (Postcondition: Cancels seats)
* (Precondition: Airplane is initialized)
*/
public static void cancelSeats(){
}
// 6
/**
* Prints passenger info
* (Postcondition: Prints passenger info)
* (Precondition: Airplane is initialized)
*/
public static void printPassengerInfo(){
}
// 7
/**
* Prints reserved seats info
* (Postcondition: Prints reserved seats info)
* (Precondition: Airplane is initialized)
*/
public static void printReservedSeatsInfo(){
}
// 8
/**
* Reserve seats by seat class and preferential seating
* (Postcondition: Reserves seats)
* (Precondition: Airplane is initialized)
*/
public static void reserveSeatsSpecial(){
}
}
|
Implemented second method
|
AirlineCompany.java
|
Implemented second method
|
|
Java
|
apache-2.0
|
e5c40f92eaa2aef25f3e8a673302dd58da33e708
| 0
|
KFGD/Cacli,KFGD/Cacli
|
package hack.com.cacli;
import android.location.Address;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.location.Geocoder;
import android.widget.Toast;
import com.nhn.android.maps.NMapContext;
import com.nhn.android.maps.NMapView;
import com.nhn.android.maps.maplib.NGeoPoint;
import com.nhn.android.maps.overlay.NMapPOIdata;
import com.nhn.android.maps.overlay.NMapPOIitem;
import com.nhn.android.mapviewer.overlay.NMapOverlayManager;
import com.nhn.android.mapviewer.overlay.NMapPOIdataOverlay;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
/**
* A simple {@link Fragment} subclass.
*/
public class MapFragment extends Fragment {
private NMapContext mMapContext;
private static final String CLIENT_ID = "HTSOdNC5nUu2HRqBtirR";
private Geocoder mGeocoder;
private GPSModule gpsModule;
public MapFragment() {
// Required empty public constructor
}
public static MapFragment getInstance(){
MapFragment mapFragment = new MapFragment();
return mapFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_map, container, false);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMapContext = new NMapContext(super.getActivity());
mGeocoder = new Geocoder(getActivity(), Locale.KOREA);
mMapContext.onCreate();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final NMapView mapView = (NMapView)getView().findViewById(R.id.mapView);
initMapView(mapView);
final NMapViewerResourceProvider mMapViewerResourceProvider = new NMapViewerResourceProvider(getActivity());
final NMapOverlayManager mapOverlayManager = new NMapOverlayManager(getActivity(), mapView, mMapViewerResourceProvider);
mapView.getMapController().setMapCenter(findGeoPoint("강남역"),13);
GPSModule gpsModule = new GPSModule(getActivity(), new GPSModule.OnSuccessListener() {
@Override
public void success(Location location) {
if(location == null) {
Toast.makeText(getActivity(), "GPS을 확인해주시기 바랍니다.", Toast.LENGTH_SHORT).show();
return;
}
Log.i("info", String.format(Locale.KOREA, "위도 : %s 경도 : %s", String.valueOf(location.getLongitude()), String.valueOf(location.getLatitude())));
NGeoPoint point = new NGeoPoint(location.getLongitude(), location.getLatitude());
mapView.getMapController().setMapCenter(point, 13);
int markerId = NMapPOIflagType.PIN;
// set POI data
NMapPOIdata poiData = new NMapPOIdata(2, mMapViewerResourceProvider);
poiData.beginPOIdata(1);
poiData.addPOIitem(location.getLongitude(), location.getLatitude(), "Pizza 777-111", markerId, 0);
poiData.endPOIdata();
// create POI data overlay
NMapPOIdataOverlay poiDataOverlay = mapOverlayManager.createPOIdataOverlay(poiData, null);
// show all POI data
poiDataOverlay.showAllPOIdata(0);
//set event listener to the overlay
poiDataOverlay.setOnStateChangeListener(new NMapPOIdataOverlay.OnStateChangeListener() {
@Override
public void onFocusChanged(NMapPOIdataOverlay nMapPOIdataOverlay, NMapPOIitem nMapPOIitem) {
}
@Override
public void onCalloutClick(NMapPOIdataOverlay nMapPOIdataOverlay, NMapPOIitem nMapPOIitem) {
NGeoPoint point = nMapPOIitem.getPoint();
try {
List<Address> addressList = mGeocoder.getFromLocation(point.getLatitude(), point.getLongitude(), 1);
if(addressList != null && addressList.size() > 0){
Toast.makeText(getActivity(), String.format(Locale.KOREA,"현재 위치의 주소는 %s", addressList.get(0).getAddressLine(0).toString()), Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
gpsModule.getCurrentLocation();
}
private void initMapView(NMapView mapView) {
mapView.setClientId(CLIENT_ID);
mapView.setClickable(true);
mapView.setEnabled(true);
mapView.setFocusable(true);
mapView.setFocusableInTouchMode(true);
mapView.requestFocus();
mMapContext.setupMapView(mapView);
}
/**
* 주소로부터 위치정보 취득
* @param address 주소
*/
private NGeoPoint findGeoPoint(String address) {
Geocoder geocoder = new Geocoder(getActivity());
Address addr;
NGeoPoint location = null;
Log.i("info","findGeoPoint");
try {
List<Address> listAddress = geocoder.getFromLocationName(address, 1);
if (listAddress.size() > 0) { // 주소값이 존재 하면
addr = listAddress.get(0); // Address형태로
int lat = (int) ((addr.getLatitude()) * 1E6);
int lng = (int) ((addr.getLongitude()) * 1E6);
location = new NGeoPoint(lng, lat);
Log.i("info", "주소로부터 취득한 위도 : " + lat + ", 경도 : " + lng);
}
} catch (IOException e) {
e.printStackTrace();
}
return location;
}
@Override
public void onStart() {
super.onStart();
mMapContext.onStart();
}
@Override
public void onResume() {
super.onResume();
mMapContext.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapContext.onPause();
}
@Override
public void onStop() {
mMapContext.onStop();
super.onStop();
}
@Override
public void onDestroy() {
mMapContext.onDestroy();
super.onDestroy();
}
}
|
app/src/main/java/hack/com/cacli/MapFragment.java
|
package hack.com.cacli;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.nhn.android.maps.NMapContext;
import com.nhn.android.maps.NMapView;
import com.nhn.android.maps.maplib.NGeoPoint;
import com.nhn.android.maps.overlay.NMapPOIdata;
import com.nhn.android.maps.overlay.NMapPOIitem;
import com.nhn.android.mapviewer.overlay.NMapOverlayManager;
import com.nhn.android.mapviewer.overlay.NMapPOIdataOverlay;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
/**
* A simple {@link Fragment} subclass.
*/
public class MapFragment extends Fragment {
private NMapContext mMapContext;
private static final String CLIENT_ID = "HTSOdNC5nUu2HRqBtirR";
private Geocoder mGeocoder;
private GPSModule gpsModule;
public MapFragment() {
// Required empty public constructor
}
public static MapFragment getInstance(){
MapFragment mapFragment = new MapFragment();
return mapFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_map, container, false);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMapContext = new NMapContext(super.getActivity());
mGeocoder = new Geocoder(getActivity(), Locale.KOREA);
mMapContext.onCreate();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final NMapView mapView = (NMapView)getView().findViewById(R.id.mapView);
initMapView(mapView);
final NMapViewerResourceProvider mMapViewerResourceProvider = new NMapViewerResourceProvider(getActivity());
final NMapOverlayManager mapOverlayManager = new NMapOverlayManager(getActivity(), mapView, mMapViewerResourceProvider);
gpsModule = new GPSModule(getActivity(), new GPSModule.OnSuccessListener() {
@Override
public void success(Location location) {
if(location == null) {
Toast.makeText(getActivity(), "GPS을 확인해주시기 바랍니다.", Toast.LENGTH_SHORT).show();
return;
}
Log.i("info", String.format(Locale.KOREA, "위도 : %s 경도 : %s", String.valueOf(location.getLongitude()), String.valueOf(location.getLatitude())));
NGeoPoint point = new NGeoPoint(location.getLongitude(), location.getLatitude());
mapView.getMapController().setMapCenter(point, 13);
int markerId = NMapPOIflagType.PIN;
// set POI data
NMapPOIdata poiData = new NMapPOIdata(2, mMapViewerResourceProvider);
poiData.beginPOIdata(1);
poiData.addPOIitem(location.getLongitude(), location.getLatitude(), "Pizza 777-111", markerId, 0);
poiData.endPOIdata();
// create POI data overlay
NMapPOIdataOverlay poiDataOverlay = mapOverlayManager.createPOIdataOverlay(poiData, null);
// show all POI data
poiDataOverlay.showAllPOIdata(0);
//set event listener to the overlay
poiDataOverlay.setOnStateChangeListener(new NMapPOIdataOverlay.OnStateChangeListener() {
@Override
public void onFocusChanged(NMapPOIdataOverlay nMapPOIdataOverlay, NMapPOIitem nMapPOIitem) {
}
@Override
public void onCalloutClick(NMapPOIdataOverlay nMapPOIdataOverlay, NMapPOIitem nMapPOIitem) {
NGeoPoint point = nMapPOIitem.getPoint();
try {
List<Address> addressList = mGeocoder.getFromLocation(point.getLatitude(), point.getLongitude(), 1);
if(addressList != null && addressList.size() > 0){
Toast.makeText(getActivity(), String.format(Locale.KOREA,"현재 위치의 주소는 %s", addressList.get(0).getAddressLine(0).toString()), Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
gpsModule.getCurrentLocation();
}
private void initMapView(NMapView mapView) {
mapView.setClientId(CLIENT_ID);
mapView.setClickable(true);
mapView.setEnabled(true);
mapView.setFocusable(true);
mapView.setFocusableInTouchMode(true);
mapView.requestFocus();
mMapContext.setupMapView(mapView);
}
@Override
public void onStart() {
super.onStart();
mMapContext.onStart();
}
@Override
public void onResume() {
super.onResume();
mMapContext.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapContext.onPause();
}
@Override
public void onStop() {
mMapContext.onStop();
super.onStop();
}
@Override
public void onDestroy() {
mMapContext.onDestroy();
super.onDestroy();
}
}
|
Fixed Conflict
|
app/src/main/java/hack/com/cacli/MapFragment.java
|
Fixed Conflict
|
|
Java
|
bsd-3-clause
|
7e7eb59f7b3cafb0542612a6bef5d5a66c871ecb
| 0
|
NCIP/cananolab,NCIP/cananolab,NCIP/cananolab
|
package gov.nih.nci.cananolab.service.sample.helper;
import gov.nih.nci.cananolab.domain.agentmaterial.OtherFunctionalizingEntity;
import gov.nih.nci.cananolab.domain.common.Keyword;
import gov.nih.nci.cananolab.domain.function.OtherFunction;
import gov.nih.nci.cananolab.domain.nanomaterial.OtherNanomaterialEntity;
import gov.nih.nci.cananolab.domain.particle.Characterization;
import gov.nih.nci.cananolab.domain.particle.ComposingElement;
import gov.nih.nci.cananolab.domain.particle.Function;
import gov.nih.nci.cananolab.domain.particle.FunctionalizingEntity;
import gov.nih.nci.cananolab.domain.particle.NanomaterialEntity;
import gov.nih.nci.cananolab.domain.particle.Sample;
import gov.nih.nci.cananolab.system.applicationservice.CustomizedApplicationService;
import gov.nih.nci.cananolab.util.ClassUtils;
import gov.nih.nci.cananolab.util.Constants;
import gov.nih.nci.cananolab.util.StringUtils;
import gov.nih.nci.cananolab.util.TextMatchMode;
import gov.nih.nci.system.client.ApplicationServiceProvider;
import gov.nih.nci.system.query.hibernate.HQLCriteria;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.hibernate.FetchMode;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
/**
* Helper class providing implementations of search methods needed for both
* local implementation of SampleService and grid service *
*
* @author pansu, tanq
*
*/
public class SampleServiceHelper {
public List<Sample> findSamplesBy(String samplePointOfContact,
String[] nanomaterialEntityClassNames,
String[] otherNanomaterialEntityTypes,
String[] functionalizingEntityClassNames,
String[] otherFunctionalizingEntityTypes,
String[] functionClassNames, String[] otherFunctionTypes,
String[] characterizationClassNames, String[] wordList)
throws Exception {
List<Sample> particles = new ArrayList<Sample>();
// can't query for the entire Sample object due to
// limitations in pagination in SDK
DetachedCriteria crit = DetachedCriteria.forClass(Sample.class)
.setProjection(Projections.distinct(Property.forName("id")));
if (samplePointOfContact != null && samplePointOfContact.length() > 0) {
TextMatchMode pocMatchMode = new TextMatchMode(samplePointOfContact);
Disjunction disjunction = Restrictions.disjunction();
crit.createAlias("primaryPointOfContact", "pointOfContact");
crit.createAlias("pointOfContact.organization", "organization");
crit.createAlias("otherPointOfContactCollection", "otherPoc",
CriteriaSpecification.LEFT_JOIN);
crit.createAlias("otherPoc.organization", "otherOrg",
CriteriaSpecification.LEFT_JOIN);
String critStrs[] = { "pointOfContact.lastName",
"pointOfContact.firstName", "pointOfContact.role",
"organization.name", "otherPoc.lastName",
"otherPoc.firstName", "otherOrg.name" };
for (String critStr : critStrs) {
Criterion pocCrit = Restrictions.ilike(critStr, pocMatchMode
.getUpdatedText(), pocMatchMode.getMatchMode());
disjunction.add(pocCrit);
}
crit.add(disjunction);
}
// join composition and nanomaterial entity
if (nanomaterialEntityClassNames != null
&& nanomaterialEntityClassNames.length > 0
|| otherNanomaterialEntityTypes != null
&& otherNanomaterialEntityTypes.length > 0
|| functionClassNames != null && functionClassNames.length > 0
|| otherFunctionTypes != null && otherFunctionTypes.length > 0) {
crit.createAlias("sampleComposition", "comp");
crit.createAlias("comp.nanomaterialEntityCollection", "nanoEntity");
}
// nanomaterial entity
if (nanomaterialEntityClassNames != null
&& nanomaterialEntityClassNames.length > 0
|| otherNanomaterialEntityTypes != null
&& otherNanomaterialEntityTypes.length > 0
|| functionClassNames != null && functionClassNames.length > 0
|| otherFunctionTypes != null && otherFunctionTypes.length > 0) {
Disjunction disjunction = Restrictions.disjunction();
if (nanomaterialEntityClassNames != null
&& nanomaterialEntityClassNames.length > 0) {
Criterion nanoEntityCrit = Restrictions.in("nanoEntity.class",
nanomaterialEntityClassNames);
disjunction.add(nanoEntityCrit);
}
if (otherNanomaterialEntityTypes != null
&& otherNanomaterialEntityTypes.length > 0) {
Criterion otherNanoCrit1 = Restrictions.eq("nanoEntity.class",
"OtherNanomaterialEntity");
Criterion otherNanoCrit2 = Restrictions.in("nanoEntity.type",
otherNanomaterialEntityTypes);
Criterion otherNanoCrit = Restrictions.and(otherNanoCrit1,
otherNanoCrit2);
disjunction.add(otherNanoCrit);
}
crit.add(disjunction);
}
// function
if (functionClassNames != null && functionClassNames.length > 0
|| otherFunctionTypes != null && otherFunctionTypes.length > 0) {
Disjunction disjunction = Restrictions.disjunction();
crit.createAlias(
"sampleComposition.functionalizingEntityCollection",
"funcEntity", CriteriaSpecification.LEFT_JOIN);
crit.createAlias("nanoEntity.composingElementCollection",
"compElement", CriteriaSpecification.LEFT_JOIN)
.createAlias("compElement.inherentFunctionCollection",
"inFunc", CriteriaSpecification.LEFT_JOIN);
crit.createAlias("funcEntity.functionCollection", "func",
CriteriaSpecification.LEFT_JOIN);
if (functionClassNames != null && functionClassNames.length > 0) {
Criterion funcCrit1 = Restrictions.in("inFunc.class",
functionClassNames);
Criterion funcCrit2 = Restrictions.in("func.class",
functionClassNames);
disjunction.add(funcCrit1).add(funcCrit2);
}
if (otherFunctionTypes != null && otherFunctionTypes.length > 0) {
Criterion otherFuncCrit1 = Restrictions.and(Restrictions.eq(
"inFunc.class", "OtherFunction"), Restrictions.in(
"inFunc.type", otherFunctionTypes));
Criterion otherFuncCrit2 = Restrictions.and(Restrictions.eq(
"func.class", "OtherFunction"), Restrictions.in(
"func.type", otherFunctionTypes));
disjunction.add(otherFuncCrit1).add(otherFuncCrit2);
}
crit.add(disjunction);
}
// characterization and text
if (characterizationClassNames != null
&& characterizationClassNames.length > 0 || wordList != null
&& wordList.length > 0) {
crit.createAlias("characterizationCollection", "chara",
CriteriaSpecification.LEFT_JOIN);
if (characterizationClassNames != null
&& characterizationClassNames.length > 0) {
crit.add(Restrictions.in("chara.class",
characterizationClassNames));
}
if (wordList != null && wordList.length > 0) {
// turn words into upper case before searching keywords
String[] upperKeywords = new String[wordList.length];
for (int i = 0; i < wordList.length; i++) {
upperKeywords[i] = wordList[i].toUpperCase();
}
Disjunction disjunction = Restrictions.disjunction();
crit.createAlias("keywordCollection", "keyword1",
CriteriaSpecification.LEFT_JOIN);
for (String keyword : upperKeywords) {
Criterion keywordCrit1 = Restrictions.like("keyword1.name",
keyword, MatchMode.ANYWHERE);
disjunction.add(keywordCrit1);
}
crit.createAlias("chara.findingCollection",
"finding", CriteriaSpecification.LEFT_JOIN)
.createAlias("finding.fileCollection", "charFile",
CriteriaSpecification.LEFT_JOIN).createAlias(
"charFile.keywordCollection", "keyword2",
CriteriaSpecification.LEFT_JOIN);
;
for (String keyword : upperKeywords) {
Criterion keywordCrit2 = Restrictions.like("keyword2.name",
keyword, MatchMode.ANYWHERE);
disjunction.add(keywordCrit2);
}
for (String word : wordList) {
Criterion summaryCrit1 = Restrictions.ilike(
"chara.designMethodsDescription", word, MatchMode.ANYWHERE);
Criterion summaryCrit2 = Restrictions.ilike(
"charFile.description", word, MatchMode.ANYWHERE);
Criterion summaryCrit = Restrictions.or(summaryCrit1,
summaryCrit2);
disjunction.add(summaryCrit);
}
// publication keywords
crit.createAlias("publicationCollection", "pub1",
CriteriaSpecification.LEFT_JOIN);
crit.createAlias("pub1.keywordCollection", "keyword3",
CriteriaSpecification.LEFT_JOIN);
for (String keyword : upperKeywords) {
Criterion keywordCrit3 = Restrictions.like("keyword3.name",
keyword, MatchMode.ANYWHERE);
disjunction.add(keywordCrit3);
}
crit.add(disjunction);
}
}
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
List results = appService.query(crit);
// don't need this if Hibernate would've allowed for functionalizing
// entities in the where clause
List<String> functionalizingEntityTypes = null;
if (functionalizingEntityClassNames != null
&& functionalizingEntityClassNames.length > 0
|| otherFunctionalizingEntityTypes != null
&& otherFunctionalizingEntityTypes.length > 0) {
functionalizingEntityTypes = new ArrayList<String>(Arrays
.asList(functionalizingEntityClassNames));
functionalizingEntityTypes.addAll(Arrays
.asList(otherFunctionalizingEntityTypes));
}
for (Object obj : results) {
Sample particle = loadSample(obj.toString());
// don't need this if Hibernate would've allowed for functionalizing
// entities in the where clause
boolean matching = hasMatchingFunctionalizingEntities(particle,
functionalizingEntityTypes);
if (matching) {
particles.add(particle);
}
}
return particles;
}
// workaround to filter out publications that don't have matching
// functionalizing entities due to bug in hibernate in handling having
// .class in
// where clause in multi-level inheritance
private boolean hasMatchingFunctionalizingEntities(Sample particle,
List<String> functionalizingEntityTypes) throws Exception {
if (functionalizingEntityTypes == null) {
return true;
}
boolean status = false;
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria
.forClass(FunctionalizingEntity.class);
crit.createAlias("sampleComposition", "comp");
crit.createAlias("comp.sample", "sample");
crit.add(Restrictions.eq("sample.id", particle.getId()));
List result = appService.query(crit);
if (!result.isEmpty()) {
FunctionalizingEntity entity = (FunctionalizingEntity) result
.get(0);
String entityName;
if (entity instanceof OtherFunctionalizingEntity) {
entityName = ((OtherFunctionalizingEntity) entity).getType();
} else {
entityName = ClassUtils.getShortClassName(entity.getClass()
.getName());
}
if (functionalizingEntityTypes.contains(entityName)) {
return true;
}
}
return status;
}
/**
* Return all stored functionalizing entity class names. In case of
* OtherFunctionalizingEntity, store the OtherFunctionalizingEntity type
*
* @param particleSample
* @return
*/
public SortedSet<String> getStoredFunctionalizingEntityClassNames(
Sample particleSample) {
SortedSet<String> storedEntities = new TreeSet<String>();
if (particleSample.getSampleComposition() != null
&& particleSample.getSampleComposition()
.getFunctionalizingEntityCollection() != null) {
for (FunctionalizingEntity entity : particleSample
.getSampleComposition()
.getFunctionalizingEntityCollection()) {
if (entity instanceof OtherFunctionalizingEntity) {
storedEntities.add(((OtherFunctionalizingEntity) entity)
.getType());
} else {
storedEntities.add(ClassUtils.getShortClassName(entity
.getClass().getCanonicalName()));
}
}
}
return storedEntities;
}
/**
* Return all stored function class names. In case of OtherFunction, store
* the otherFunction type
*
* @param particleSample
* @return
*/
public SortedSet<String> getStoredFunctionClassNames(Sample particleSample) {
SortedSet<String> storedFunctions = new TreeSet<String>();
if (particleSample.getSampleComposition() != null) {
if (particleSample.getSampleComposition()
.getNanomaterialEntityCollection() != null) {
for (NanomaterialEntity entity : particleSample
.getSampleComposition()
.getNanomaterialEntityCollection()) {
if (entity.getComposingElementCollection() != null) {
for (ComposingElement element : entity
.getComposingElementCollection()) {
if (element.getInherentFunctionCollection() != null) {
for (Function function : element
.getInherentFunctionCollection()) {
if (function instanceof OtherFunction) {
storedFunctions
.add(((OtherFunction) function)
.getType());
} else {
storedFunctions.add(ClassUtils
.getShortClassName(function
.getClass()
.getCanonicalName()));
}
}
}
}
}
}
}
if (particleSample.getSampleComposition()
.getFunctionalizingEntityCollection() != null) {
for (FunctionalizingEntity entity : particleSample
.getSampleComposition()
.getFunctionalizingEntityCollection()) {
if (entity.getFunctionCollection() != null) {
for (Function function : entity.getFunctionCollection()) {
if (function instanceof OtherFunction) {
storedFunctions.add(((OtherFunction) function)
.getType());
} else {
storedFunctions.add(ClassUtils
.getShortClassName(function.getClass()
.getCanonicalName()));
}
}
}
}
}
}
return storedFunctions;
}
/**
* Return all stored nanomaterial entity class names. In case of
* OtherNanomaterialEntity, store the otherNanomaterialEntity type
*
* @param particleSample
* @return
*/
public SortedSet<String> getStoredNanomaterialEntityClassNames(
Sample particleSample) {
SortedSet<String> storedEntities = new TreeSet<String>();
if (particleSample.getSampleComposition() != null
&& particleSample.getSampleComposition()
.getNanomaterialEntityCollection() != null) {
for (NanomaterialEntity entity : particleSample
.getSampleComposition().getNanomaterialEntityCollection()) {
if (entity instanceof OtherNanomaterialEntity) {
storedEntities.add(((OtherNanomaterialEntity) entity)
.getType());
} else {
storedEntities.add(ClassUtils.getShortClassName(entity
.getClass().getCanonicalName()));
}
}
}
return storedEntities;
}
public SortedSet<String> getStoredCharacterizationClassNames(Sample particle) {
SortedSet<String> storedChars = new TreeSet<String>();
if (particle.getCharacterizationCollection() != null) {
for (Characterization achar : particle
.getCharacterizationCollection()) {
storedChars.add(ClassUtils.getShortClassName(achar.getClass()
.getCanonicalName()));
}
}
return storedChars;
}
public Sample findSampleById(String sampleId) throws Exception {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria.forClass(Sample.class).add(
Property.forName("id").eq(new Long(sampleId)));
crit.setFetchMode("keywordCollection", FetchMode.JOIN);
crit.setFetchMode("primaryPointOfContact", FetchMode.JOIN);
crit.setFetchMode("primaryPointOfContact.organization", FetchMode.JOIN);
crit.setFetchMode("otherPointOfContactCollection", FetchMode.JOIN);
crit.setFetchMode("otherPointOfContactCollection.organization",
FetchMode.JOIN);
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
List result = appService.query(crit);
Sample particleSample = null;
if (!result.isEmpty()) {
particleSample = (Sample) result.get(0);
}
return particleSample;
}
private Sample loadSample(String sampleId) throws Exception {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria.forClass(Sample.class).add(
Property.forName("id").eq(new Long(sampleId)));
crit.setFetchMode("primaryPointOfContact", FetchMode.JOIN);
crit.setFetchMode("primaryPointOfContact.organization", FetchMode.JOIN);
crit.setFetchMode("otherPointOfContactCollection", FetchMode.JOIN);
crit.setFetchMode("otherPointOfContactCollection.organization",
FetchMode.JOIN);
crit.setFetchMode("keywordCollection", FetchMode.JOIN);
crit.setFetchMode("characterizationCollection", FetchMode.JOIN);
crit.setFetchMode("sampleComposition.nanomaterialEntityCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.nanomaterialEntityCollection.composingElementCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.nanomaterialEntityCollection.composingElementCollection.inherentFunctionCollection",
FetchMode.JOIN);
crit.setFetchMode("sampleComposition.functionalizingEntityCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.functionalizingEntityCollection.functionCollection",
FetchMode.JOIN);
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
List result = appService.query(crit);
Sample particleSample = null;
if (!result.isEmpty()) {
particleSample = (Sample) result.get(0);
}
return particleSample;
}
public Sample findSampleByName(String sampleName) throws Exception {
Sample particleSample = null;
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria.forClass(Sample.class).add(
Property.forName("name").eq(sampleName));
crit.setFetchMode("primaryPointOfContact", FetchMode.JOIN); // eager
// load not
// set in
// caDSR
crit.setFetchMode("characterizationCollection", FetchMode.JOIN);
crit.setFetchMode("sampleComposition.nanomaterialEntityCollection",
FetchMode.JOIN);
crit.setFetchMode("sampleComposition.fileCollection", FetchMode.JOIN);
crit.setFetchMode("sampleComposition.chemicalAssociationCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.chemicalAssociationCollection.associatedElementA",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.chemicalAssociationCollection.associatedElementB",
FetchMode.JOIN);
crit.setFetchMode("sampleComposition.functionalizingEntityCollection",
FetchMode.JOIN);
crit.setFetchMode("publicationCollection", FetchMode.JOIN);
crit.setFetchMode("publicationCollection.authorCollection",
FetchMode.JOIN);
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
List result = appService.query(crit);
if (!result.isEmpty()) {
particleSample = (Sample) result.get(0);
}
return particleSample;
}
public List<Keyword> findKeywordsBySampleId(String sampleId)
throws Exception {
List<Keyword> keywords = new ArrayList<Keyword>();
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
HQLCriteria crit = new HQLCriteria(
"select aSample.keywordCollection from gov.nih.nci.cananolab.domain.particle.Sample aSample where aSample.id = "
+ sampleId);
List results = appService.query(crit);
for (Object obj : results) {
Keyword keyword = (Keyword) obj;
keywords.add(keyword);
}
return keywords;
}
public int getNumberOfPublicSamples() throws Exception {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
List<String> publicData = appService.getPublicData();
HQLCriteria crit = new HQLCriteria(
"select name from gov.nih.nci.cananolab.domain.particle.Sample");
List results = appService.query(crit);
List<String> publicNames = new ArrayList<String>();
for (Object obj : results) {
String name = (String) obj.toString();
if (StringUtils.containsIgnoreCase(publicData, name)) {
publicNames.add(name);
}
}
return publicNames.size();
}
public String[] getCharacterizationClassNames(String sampleId)
throws Exception {
String hql = "select distinct achar.class from gov.nih.nci.cananolab.domain.particle.characterization.Characterization achar"
+ " where achar.sample.id = " + sampleId;
return this.getClassNames(hql);
}
public String[] getFunctionalizingEntityClassNames(String sampleId)
throws Exception {
SortedSet<String> names = new TreeSet<String>();
DetachedCriteria crit = DetachedCriteria.forClass(Sample.class).add(
Property.forName("id").eq(new Long(sampleId)));
crit.setFetchMode("sampleComposition.functionalizingEntityCollection",
FetchMode.JOIN);
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
List results = appService.query(crit);
for (Object obj : results) {
Sample particleSample = (Sample) obj;
names = this
.getStoredFunctionalizingEntityClassNames(particleSample);
}
return names.toArray(new String[0]);
}
public String[] getFunctionClassNames(String sampleId) throws Exception {
SortedSet<String> names = new TreeSet<String>();
DetachedCriteria crit = DetachedCriteria.forClass(Sample.class).add(
Property.forName("id").eq(new Long(sampleId)));
crit.setFetchMode("sampleComposition.nanomaterialEntityCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.nanomaterialEntityCollection.composingElementCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.nanomaterialEntityCollection.composingElementCollection.inherentFunctionCollection",
FetchMode.JOIN);
crit.setFetchMode("sampleComposition.functionalizingEntityCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.functionalizingEntityCollection.functionCollection",
FetchMode.JOIN);
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
List results = appService.query(crit);
for (Object obj : results) {
Sample particleSample = (Sample) obj;
names = this.getStoredFunctionClassNames(particleSample);
}
return names.toArray(new String[0]);
}
public String[] getNanomaterialEntityClassNames(String sampleId)
throws Exception {
String hql = "select distinct entity.class from "
+ " gov.nih.nci.cananolab.domain.particle.NanomaterialEntity entity"
+ " where entity.class!='OtherNanomaterialEntity' and entity.sampleComposition.sample.id = "
+ sampleId;
String[] classNames = this.getClassNames(hql);
SortedSet<String> names = new TreeSet<String>();
if (classNames.length > 0) {
names.addAll(Arrays.asList(classNames));
}
String hql2 = "select distinct entity.type from "
+ " gov.nih.nci.cananolab.domain.nanomaterial.OtherNanomaterialEntity entity"
+ " where entity.sampleComposition.sample.id = " + sampleId;
String[] otherTypes = this.getClassNames(hql2);
if (otherTypes.length > 0) {
names.addAll(Arrays.asList(otherTypes));
}
return names.toArray(new String[0]);
}
private String[] getClassNames(String hql) throws Exception {
String[] classNames = null;
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
HQLCriteria crit = new HQLCriteria(hql);
List results = appService.query(crit);
if (results != null) {
classNames = new String[results.size()];
} else {
classNames = new String[0];
}
int i = 0;
for (Object obj : results) {
classNames[i] = (String) obj.toString();
i++;
}
return classNames;
}
public String[] getSampleViewStrs(List<Sample> particleSamples) {
List<String> particleStrings = new ArrayList<String>(particleSamples
.size());
// 6 columns
List<String> columns = new ArrayList<String>(7);
for (Sample particleSample : particleSamples) {
columns.clear();
columns.add(particleSample.getId().toString());
columns.add(particleSample.getName());
columns.add(particleSample.getPrimaryPointOfContact()
.getFirstName());
columns
.add(particleSample.getPrimaryPointOfContact()
.getLastName());
// nanoparticle entities and functionalizing entities are in one
// column.
SortedSet<String> entities = new TreeSet<String>();
entities
.addAll(getStoredNanomaterialEntityClassNames(particleSample));
entities
.addAll(getStoredFunctionalizingEntityClassNames(particleSample));
columns.add(StringUtils.join(entities,
Constants.VIEW_CLASSNAME_DELIMITER));
columns.add(StringUtils.join(
getStoredFunctionClassNames(particleSample),
Constants.VIEW_CLASSNAME_DELIMITER));
columns.add(StringUtils.join(
getStoredCharacterizationClassNames(particleSample),
Constants.VIEW_CLASSNAME_DELIMITER));
particleStrings.add(StringUtils.joinEmptyItemIncluded(columns,
Constants.VIEW_COL_DELIMITER));
}
String[] particleStrArray = new String[particleStrings.size()];
return particleStrings.toArray(particleStrArray);
}
public SortedSet<String> findSampleNamesByPublicationId(
String publicationId) throws Exception {
DetachedCriteria crit = DetachedCriteria.forClass(Sample.class);
crit.createAlias("publicationCollection", "pub").add(
Property.forName("pub.id").eq(new Long(publicationId)));
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
List results = appService.query(crit);
SortedSet<String> names = new TreeSet<String>();
for (Object obj : results) {
Sample particleSample = (Sample) obj;
names.add(particleSample.getName());
}
return names;
}
}
|
src/gov/nih/nci/cananolab/service/sample/helper/SampleServiceHelper.java
|
package gov.nih.nci.cananolab.service.sample.helper;
import gov.nih.nci.cananolab.domain.agentmaterial.OtherFunctionalizingEntity;
import gov.nih.nci.cananolab.domain.common.Keyword;
import gov.nih.nci.cananolab.domain.function.OtherFunction;
import gov.nih.nci.cananolab.domain.nanomaterial.OtherNanomaterialEntity;
import gov.nih.nci.cananolab.domain.particle.Characterization;
import gov.nih.nci.cananolab.domain.particle.ComposingElement;
import gov.nih.nci.cananolab.domain.particle.Function;
import gov.nih.nci.cananolab.domain.particle.FunctionalizingEntity;
import gov.nih.nci.cananolab.domain.particle.NanomaterialEntity;
import gov.nih.nci.cananolab.domain.particle.Sample;
import gov.nih.nci.cananolab.system.applicationservice.CustomizedApplicationService;
import gov.nih.nci.cananolab.util.ClassUtils;
import gov.nih.nci.cananolab.util.Constants;
import gov.nih.nci.cananolab.util.StringUtils;
import gov.nih.nci.cananolab.util.TextMatchMode;
import gov.nih.nci.system.client.ApplicationServiceProvider;
import gov.nih.nci.system.query.hibernate.HQLCriteria;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.hibernate.FetchMode;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
/**
* Helper class providing implementations of search methods needed for both
* local implementation of SampleService and grid service *
*
* @author pansu, tanq
*
*/
public class SampleServiceHelper {
public List<Sample> findSamplesBy(String samplePointOfContact,
String[] nanomaterialEntityClassNames,
String[] otherNanomaterialEntityTypes,
String[] functionalizingEntityClassNames,
String[] otherFunctionalizingEntityTypes,
String[] functionClassNames, String[] otherFunctionTypes,
String[] characterizationClassNames, String[] wordList)
throws Exception {
List<Sample> particles = new ArrayList<Sample>();
// can't query for the entire Sample object due to
// limitations in pagination in SDK
DetachedCriteria crit = DetachedCriteria.forClass(Sample.class)
.setProjection(Projections.distinct(Property.forName("id")));
if (samplePointOfContact != null && samplePointOfContact.length() > 0) {
TextMatchMode pocMatchMode = new TextMatchMode(samplePointOfContact);
Disjunction disjunction = Restrictions.disjunction();
crit.createAlias("primaryPointOfContact", "pointOfContact");
crit.createAlias("pointOfContact.organization", "organization");
crit.createAlias("otherPointOfContactCollection", "otherPoc",
CriteriaSpecification.LEFT_JOIN);
crit.createAlias("otherPoc.organization", "otherOrg",
CriteriaSpecification.LEFT_JOIN);
String critStrs[] = { "pointOfContact.lastName",
"pointOfContact.firstName", "pointOfContact.role",
"organization.name", "otherPoc.lastName",
"otherPoc.firstName", "otherOrg.name" };
for (String critStr : critStrs) {
Criterion pocCrit = Restrictions.ilike(critStr, pocMatchMode
.getUpdatedText(), pocMatchMode.getMatchMode());
disjunction.add(pocCrit);
}
crit.add(disjunction);
}
// join composition and nanomaterial entity
if (nanomaterialEntityClassNames != null
&& nanomaterialEntityClassNames.length > 0
|| otherNanomaterialEntityTypes != null
&& otherNanomaterialEntityTypes.length > 0
|| functionClassNames != null && functionClassNames.length > 0
|| otherFunctionTypes != null && otherFunctionTypes.length > 0) {
crit.createAlias("sampleComposition", "comp");
crit.createAlias("comp.nanomaterialEntityCollection", "nanoEntity");
}
// nanomaterial entity
if (nanomaterialEntityClassNames != null
&& nanomaterialEntityClassNames.length > 0
|| otherNanomaterialEntityTypes != null
&& otherNanomaterialEntityTypes.length > 0
|| functionClassNames != null && functionClassNames.length > 0
|| otherFunctionTypes != null && otherFunctionTypes.length > 0) {
Disjunction disjunction = Restrictions.disjunction();
if (nanomaterialEntityClassNames != null
&& nanomaterialEntityClassNames.length > 0) {
Criterion nanoEntityCrit = Restrictions.in("nanoEntity.class",
nanomaterialEntityClassNames);
disjunction.add(nanoEntityCrit);
}
if (otherNanomaterialEntityTypes != null
&& otherNanomaterialEntityTypes.length > 0) {
Criterion otherNanoCrit1 = Restrictions.eq("nanoEntity.class",
"OtherNanomaterialEntity");
Criterion otherNanoCrit2 = Restrictions.in("nanoEntity.type",
otherNanomaterialEntityTypes);
Criterion otherNanoCrit = Restrictions.and(otherNanoCrit1,
otherNanoCrit2);
disjunction.add(otherNanoCrit);
}
crit.add(disjunction);
}
// function
if (functionClassNames != null && functionClassNames.length > 0
|| otherFunctionTypes != null && otherFunctionTypes.length > 0) {
Disjunction disjunction = Restrictions.disjunction();
crit.createAlias(
"sampleComposition.functionalizingEntityCollection",
"funcEntity", CriteriaSpecification.LEFT_JOIN);
crit.createAlias("nanoEntity.composingElementCollection",
"compElement", CriteriaSpecification.LEFT_JOIN)
.createAlias("compElement.inherentFunctionCollection",
"inFunc", CriteriaSpecification.LEFT_JOIN);
crit.createAlias("funcEntity.functionCollection", "func",
CriteriaSpecification.LEFT_JOIN);
if (functionClassNames != null && functionClassNames.length > 0) {
Criterion funcCrit1 = Restrictions.in("inFunc.class",
functionClassNames);
Criterion funcCrit2 = Restrictions.in("func.class",
functionClassNames);
disjunction.add(funcCrit1).add(funcCrit2);
}
if (otherFunctionTypes != null && otherFunctionTypes.length > 0) {
Criterion otherFuncCrit1 = Restrictions.and(Restrictions.eq(
"inFunc.class", "OtherFunction"), Restrictions.in(
"inFunc.type", otherFunctionTypes));
Criterion otherFuncCrit2 = Restrictions.and(Restrictions.eq(
"func.class", "OtherFunction"), Restrictions.in(
"func.type", otherFunctionTypes));
disjunction.add(otherFuncCrit1).add(otherFuncCrit2);
}
crit.add(disjunction);
}
// characterization and text
if (characterizationClassNames != null
&& characterizationClassNames.length > 0 || wordList != null
&& wordList.length > 0) {
crit.createAlias("characterizationCollection", "chara",
CriteriaSpecification.LEFT_JOIN);
if (characterizationClassNames != null
&& characterizationClassNames.length > 0) {
crit.add(Restrictions.in("chara.class",
characterizationClassNames));
}
if (wordList != null && wordList.length > 0) {
// turn words into upper case before searching keywords
String[] upperKeywords = new String[wordList.length];
for (int i = 0; i < wordList.length; i++) {
upperKeywords[i] = wordList[i].toUpperCase();
}
Disjunction disjunction = Restrictions.disjunction();
crit.createAlias("keywordCollection", "keyword1",
CriteriaSpecification.LEFT_JOIN);
for (String keyword : upperKeywords) {
Criterion keywordCrit1 = Restrictions.like("keyword1.name",
keyword, MatchMode.ANYWHERE);
disjunction.add(keywordCrit1);
}
crit.createAlias("chara.findingCollection",
"finding", CriteriaSpecification.LEFT_JOIN)
.createAlias("finding.fileCollection", "charFile",
CriteriaSpecification.LEFT_JOIN).createAlias(
"charFile.keywordCollection", "keyword2",
CriteriaSpecification.LEFT_JOIN);
;
for (String keyword : upperKeywords) {
Criterion keywordCrit2 = Restrictions.like("keyword2.name",
keyword, MatchMode.ANYWHERE);
disjunction.add(keywordCrit2);
}
for (String word : wordList) {
Criterion summaryCrit1 = Restrictions.ilike(
"chara.designMethodsDescription", word, MatchMode.ANYWHERE);
Criterion summaryCrit2 = Restrictions.ilike(
"charFile.description", word, MatchMode.ANYWHERE);
Criterion summaryCrit = Restrictions.or(summaryCrit1,
summaryCrit2);
disjunction.add(summaryCrit);
}
// publication keywords
crit.createAlias("publicationCollection", "pub1",
CriteriaSpecification.LEFT_JOIN);
crit.createAlias("pub1.keywordCollection", "keyword3",
CriteriaSpecification.LEFT_JOIN);
for (String keyword : upperKeywords) {
Criterion keywordCrit3 = Restrictions.like("keyword3.name",
keyword, MatchMode.ANYWHERE);
disjunction.add(keywordCrit3);
}
crit.add(disjunction);
}
}
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
List results = appService.query(crit);
// don't need this if Hibernate would've allowed for functionalizing
// entities in the where clause
List<String> functionalizingEntityTypes = null;
if (functionalizingEntityClassNames != null
&& functionalizingEntityClassNames.length > 0
|| otherFunctionalizingEntityTypes != null
&& otherFunctionalizingEntityTypes.length > 0) {
functionalizingEntityTypes = new ArrayList<String>(Arrays
.asList(functionalizingEntityClassNames));
functionalizingEntityTypes.addAll(Arrays
.asList(otherFunctionalizingEntityTypes));
}
for (Object obj : results) {
Sample particle = loadSample(obj.toString());
// don't need this if Hibernate would've allowed for functionalizing
// entities in the where clause
boolean matching = hasMatchingFunctionalizingEntities(particle,
functionalizingEntityTypes);
if (matching) {
particles.add(particle);
}
}
return particles;
}
// workaround to filter out publications that don't have matching
// functionalizing entities due to bug in hibernate in handling having
// .class in
// where clause in multi-level inheritance
private boolean hasMatchingFunctionalizingEntities(Sample particle,
List<String> functionalizingEntityTypes) throws Exception {
if (functionalizingEntityTypes == null) {
return true;
}
boolean status = false;
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria
.forClass(FunctionalizingEntity.class);
crit.createAlias("sampleComposition", "comp");
crit.createAlias("comp.sample", "sample");
crit.add(Restrictions.eq("sample.id", particle.getId()));
List result = appService.query(crit);
if (!result.isEmpty()) {
FunctionalizingEntity entity = (FunctionalizingEntity) result
.get(0);
String entityName;
if (entity instanceof OtherFunctionalizingEntity) {
entityName = ((OtherFunctionalizingEntity) entity).getType();
} else {
entityName = ClassUtils.getShortClassName(entity.getClass()
.getName());
}
if (functionalizingEntityTypes.contains(entityName)) {
return true;
}
}
return status;
}
/**
* Return all stored functionalizing entity class names. In case of
* OtherFunctionalizingEntity, store the OtherFunctionalizingEntity type
*
* @param particleSample
* @return
*/
public SortedSet<String> getStoredFunctionalizingEntityClassNames(
Sample particleSample) {
SortedSet<String> storedEntities = new TreeSet<String>();
if (particleSample.getSampleComposition() != null
&& particleSample.getSampleComposition()
.getFunctionalizingEntityCollection() != null) {
for (FunctionalizingEntity entity : particleSample
.getSampleComposition()
.getFunctionalizingEntityCollection()) {
if (entity instanceof OtherFunctionalizingEntity) {
storedEntities.add(((OtherFunctionalizingEntity) entity)
.getType());
} else {
storedEntities.add(ClassUtils.getShortClassName(entity
.getClass().getCanonicalName()));
}
}
}
return storedEntities;
}
/**
* Return all stored function class names. In case of OtherFunction, store
* the otherFunction type
*
* @param particleSample
* @return
*/
public SortedSet<String> getStoredFunctionClassNames(Sample particleSample) {
SortedSet<String> storedFunctions = new TreeSet<String>();
if (particleSample.getSampleComposition() != null) {
if (particleSample.getSampleComposition()
.getNanomaterialEntityCollection() != null) {
for (NanomaterialEntity entity : particleSample
.getSampleComposition()
.getNanomaterialEntityCollection()) {
if (entity.getComposingElementCollection() != null) {
for (ComposingElement element : entity
.getComposingElementCollection()) {
if (element.getInherentFunctionCollection() != null) {
for (Function function : element
.getInherentFunctionCollection()) {
if (function instanceof OtherFunction) {
storedFunctions
.add(((OtherFunction) function)
.getType());
} else {
storedFunctions.add(ClassUtils
.getShortClassName(function
.getClass()
.getCanonicalName()));
}
}
}
}
}
}
}
if (particleSample.getSampleComposition()
.getFunctionalizingEntityCollection() != null) {
for (FunctionalizingEntity entity : particleSample
.getSampleComposition()
.getFunctionalizingEntityCollection()) {
if (entity.getFunctionCollection() != null) {
for (Function function : entity.getFunctionCollection()) {
if (function instanceof OtherFunction) {
storedFunctions.add(((OtherFunction) function)
.getType());
} else {
storedFunctions.add(ClassUtils
.getShortClassName(function.getClass()
.getCanonicalName()));
}
}
}
}
}
}
return storedFunctions;
}
/**
* Return all stored nanomaterial entity class names. In case of
* OtherNanomaterialEntity, store the otherNanomaterialEntity type
*
* @param particleSample
* @return
*/
public SortedSet<String> getStoredNanomaterialEntityClassNames(
Sample particleSample) {
SortedSet<String> storedEntities = new TreeSet<String>();
if (particleSample.getSampleComposition() != null
&& particleSample.getSampleComposition()
.getNanomaterialEntityCollection() != null) {
for (NanomaterialEntity entity : particleSample
.getSampleComposition().getNanomaterialEntityCollection()) {
if (entity instanceof OtherNanomaterialEntity) {
storedEntities.add(((OtherNanomaterialEntity) entity)
.getType());
} else {
storedEntities.add(ClassUtils.getShortClassName(entity
.getClass().getCanonicalName()));
}
}
}
return storedEntities;
}
public SortedSet<String> getStoredCharacterizationClassNames(Sample particle) {
SortedSet<String> storedChars = new TreeSet<String>();
if (particle.getCharacterizationCollection() != null) {
for (Characterization achar : particle
.getCharacterizationCollection()) {
storedChars.add(ClassUtils.getShortClassName(achar.getClass()
.getCanonicalName()));
}
}
return storedChars;
}
public Sample findSampleById(String sampleId) throws Exception {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria.forClass(Sample.class).add(
Property.forName("id").eq(new Long(sampleId)));
crit.setFetchMode("keywordCollection", FetchMode.JOIN);
crit.setFetchMode("primaryPointOfContact", FetchMode.JOIN);
crit.setFetchMode("primaryPointOfContact.organization", FetchMode.JOIN);
crit.setFetchMode("otherPointOfContactCollection", FetchMode.JOIN);
crit.setFetchMode("otherPointOfContactCollection.organization",
FetchMode.JOIN);
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
List result = appService.query(crit);
Sample particleSample = null;
if (!result.isEmpty()) {
particleSample = (Sample) result.get(0);
}
return particleSample;
}
private Sample loadSample(String sampleId) throws Exception {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria.forClass(Sample.class).add(
Property.forName("id").eq(new Long(sampleId)));
crit.setFetchMode("primaryPointOfContact", FetchMode.JOIN);
crit.setFetchMode("primaryPointOfContact.organization", FetchMode.JOIN);
crit.setFetchMode("otherPointOfContactCollection", FetchMode.JOIN);
crit.setFetchMode("otherPointOfContactCollection.organization",
FetchMode.JOIN);
crit.setFetchMode("keywordCollection", FetchMode.JOIN);
crit.setFetchMode("characterizationCollection", FetchMode.JOIN);
crit.setFetchMode("sampleComposition.nanomaterialEntityCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.nanomaterialEntityCollection.composingElementCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.nanomaterialEntityCollection.composingElementCollection.inherentFunctionCollection",
FetchMode.JOIN);
crit.setFetchMode("sampleComposition.functionalizingEntityCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.functionalizingEntityCollection.functionCollection",
FetchMode.JOIN);
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
List result = appService.query(crit);
Sample particleSample = null;
if (!result.isEmpty()) {
particleSample = (Sample) result.get(0);
}
return particleSample;
}
public Sample findSampleByName(String sampleName) throws Exception {
Sample particleSample = null;
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
DetachedCriteria crit = DetachedCriteria.forClass(Sample.class).add(
Property.forName("name").eq(sampleName));
crit.setFetchMode("primaryPointOfContact", FetchMode.JOIN); // eager
// load not
// set in
// caDSR
crit.setFetchMode("characterizationCollection", FetchMode.JOIN);
crit.setFetchMode("sampleComposition.nanomaterialEntityCollection",
FetchMode.JOIN);
crit.setFetchMode("sampleComposition.fileCollection", FetchMode.JOIN);
crit.setFetchMode("sampleComposition.chemicalAssociationCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.chemicalAssociationCollection.associatedElementA",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.chemicalAssociationCollection.associatedElementB",
FetchMode.JOIN);
crit.setFetchMode("sampleComposition.functionalizingEntityCollection",
FetchMode.JOIN);
crit.setFetchMode("publicationCollection", FetchMode.JOIN);
crit.setFetchMode("publicationCollection.authorCollection",
FetchMode.JOIN);
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
List result = appService.query(crit);
if (!result.isEmpty()) {
particleSample = (Sample) result.get(0);
}
return particleSample;
}
public List<Keyword> findKeywordsForSampleId(String sampleId)
throws Exception {
List<Keyword> keywords = new ArrayList<Keyword>();
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
HQLCriteria crit = new HQLCriteria(
"select aSample.keywordCollection from gov.nih.nci.cananolab.domain.particle.Sample aSample where aSample.id = "
+ sampleId);
List results = appService.query(crit);
for (Object obj : results) {
Keyword keyword = (Keyword) obj;
keywords.add(keyword);
}
return keywords;
}
public int getNumberOfPublicSamples() throws Exception {
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
List<String> publicData = appService.getPublicData();
HQLCriteria crit = new HQLCriteria(
"select name from gov.nih.nci.cananolab.domain.particle.Sample");
List results = appService.query(crit);
List<String> publicNames = new ArrayList<String>();
for (Object obj : results) {
String name = (String) obj.toString();
if (StringUtils.containsIgnoreCase(publicData, name)) {
publicNames.add(name);
}
}
return publicNames.size();
}
public String[] getCharacterizationClassNames(String sampleId)
throws Exception {
String hql = "select distinct achar.class from gov.nih.nci.cananolab.domain.particle.characterization.Characterization achar"
+ " where achar.sample.id = " + sampleId;
return this.getClassNames(hql);
}
public String[] getFunctionalizingEntityClassNames(String sampleId)
throws Exception {
SortedSet<String> names = new TreeSet<String>();
DetachedCriteria crit = DetachedCriteria.forClass(Sample.class).add(
Property.forName("id").eq(new Long(sampleId)));
crit.setFetchMode("sampleComposition.functionalizingEntityCollection",
FetchMode.JOIN);
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
List results = appService.query(crit);
for (Object obj : results) {
Sample particleSample = (Sample) obj;
names = this
.getStoredFunctionalizingEntityClassNames(particleSample);
}
return names.toArray(new String[0]);
}
public String[] getFunctionClassNames(String sampleId) throws Exception {
SortedSet<String> names = new TreeSet<String>();
DetachedCriteria crit = DetachedCriteria.forClass(Sample.class).add(
Property.forName("id").eq(new Long(sampleId)));
crit.setFetchMode("sampleComposition.nanomaterialEntityCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.nanomaterialEntityCollection.composingElementCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.nanomaterialEntityCollection.composingElementCollection.inherentFunctionCollection",
FetchMode.JOIN);
crit.setFetchMode("sampleComposition.functionalizingEntityCollection",
FetchMode.JOIN);
crit
.setFetchMode(
"sampleComposition.functionalizingEntityCollection.functionCollection",
FetchMode.JOIN);
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
List results = appService.query(crit);
for (Object obj : results) {
Sample particleSample = (Sample) obj;
names = this.getStoredFunctionClassNames(particleSample);
}
return names.toArray(new String[0]);
}
public String[] getNanomaterialEntityClassNames(String sampleId)
throws Exception {
String hql = "select distinct entity.class from "
+ " gov.nih.nci.cananolab.domain.particle.NanomaterialEntity entity"
+ " where entity.class!='OtherNanomaterialEntity' and entity.sampleComposition.sample.id = "
+ sampleId;
String[] classNames = this.getClassNames(hql);
SortedSet<String> names = new TreeSet<String>();
if (classNames.length > 0) {
names.addAll(Arrays.asList(classNames));
}
String hql2 = "select distinct entity.type from "
+ " gov.nih.nci.cananolab.domain.nanomaterial.OtherNanomaterialEntity entity"
+ " where entity.sampleComposition.sample.id = " + sampleId;
String[] otherTypes = this.getClassNames(hql2);
if (otherTypes.length > 0) {
names.addAll(Arrays.asList(otherTypes));
}
return names.toArray(new String[0]);
}
private String[] getClassNames(String hql) throws Exception {
String[] classNames = null;
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
HQLCriteria crit = new HQLCriteria(hql);
List results = appService.query(crit);
if (results != null) {
classNames = new String[results.size()];
} else {
classNames = new String[0];
}
int i = 0;
for (Object obj : results) {
classNames[i] = (String) obj.toString();
i++;
}
return classNames;
}
public String[] getSampleViewStrs(List<Sample> particleSamples) {
List<String> particleStrings = new ArrayList<String>(particleSamples
.size());
// 6 columns
List<String> columns = new ArrayList<String>(7);
for (Sample particleSample : particleSamples) {
columns.clear();
columns.add(particleSample.getId().toString());
columns.add(particleSample.getName());
columns.add(particleSample.getPrimaryPointOfContact()
.getFirstName());
columns
.add(particleSample.getPrimaryPointOfContact()
.getLastName());
// nanoparticle entities and functionalizing entities are in one
// column.
SortedSet<String> entities = new TreeSet<String>();
entities
.addAll(getStoredNanomaterialEntityClassNames(particleSample));
entities
.addAll(getStoredFunctionalizingEntityClassNames(particleSample));
columns.add(StringUtils.join(entities,
Constants.VIEW_CLASSNAME_DELIMITER));
columns.add(StringUtils.join(
getStoredFunctionClassNames(particleSample),
Constants.VIEW_CLASSNAME_DELIMITER));
columns.add(StringUtils.join(
getStoredCharacterizationClassNames(particleSample),
Constants.VIEW_CLASSNAME_DELIMITER));
particleStrings.add(StringUtils.joinEmptyItemIncluded(columns,
Constants.VIEW_COL_DELIMITER));
}
String[] particleStrArray = new String[particleStrings.size()];
return particleStrings.toArray(particleStrArray);
}
public SortedSet<String> findSampleNamesByPublicationId(
String publicationId) throws Exception {
DetachedCriteria crit = DetachedCriteria.forClass(Sample.class);
crit.createAlias("publicationCollection", "pub").add(
Property.forName("pub.id").eq(new Long(publicationId)));
CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider
.getApplicationService();
List results = appService.query(crit);
SortedSet<String> names = new TreeSet<String>();
for (Object obj : results) {
Sample particleSample = (Sample) obj;
names.add(particleSample.getName());
}
return names;
}
}
|
updated findKeywordsForSampleId to findKeywordsBySampleId
SVN-Revision: 15548
|
src/gov/nih/nci/cananolab/service/sample/helper/SampleServiceHelper.java
|
updated findKeywordsForSampleId to findKeywordsBySampleId
|
|
Java
|
mit
|
437e808114827bec70f53a4e7eaf865d86c2db27
| 0
|
ovr/phpinspectionsea-mirror,ovr/phpinspectionsea-mirror,ovr/phpinspectionsea-mirror
|
package com.kalessil.phpStorm.phpInspectionsEA;
import com.intellij.codeInspection.InspectionToolProvider;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.apiUsage.*;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.codeSmell.AmbiguousMethodsCallsInArrayMappingInspector;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.codeSmell.MoreThanThreeArgumentsInspector;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.earlyReturns.NestedPositiveIfStatementsInspector;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.languageConstructions.*;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.semanticalAnalysis.OnlyWritesOnParameterInspector;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.semanticalTransformations.DefaultValueInElseBranchInspector;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.semanticalTransformations.IfReturnReturnSimplificationInspector;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.semanticalTransformations.NotOptimalIfConditionsInspection;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.semanticalTransformations.StrlenInEmptyStringCheckContextInspection;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.strictInterfaces.ArrayTypeOfParameterByDefaultValueInspector;
/*
===Bugs===:
OnlyWritesOnParameterInspector:
- type casting is recognised as write operation
- think of applying on foreach
===Some cases of interest===:
-- review open api
PhpCodeInsightUtil.isEmptyBody
-- not needed initialization
var $member = null;
-- loop statement that doesn't loop
foreach (...) {
throw|break|return;
}
-- suspicious counting in foreach
foreach(... as ...) {
...
$variable++||++$variable;
}
*/
public class PhpInspectionsEAProvider implements InspectionToolProvider {
@Override
public Class[] getInspectionClasses() {
return new Class[]{
IsNullFunctionUsageInspector.class,
IsEmptyFunctionUsageInspector.class,
UnSafeIsSetOverArrayInspector.class,
ForgottenDebugOutputInspector.class,
UnNecessaryDoubleQuotesInspector.class,
TypeUnsafeComparisonInspector.class,
TypeUnsafeArraySearchInspector.class,
IfConditionalsWithoutGroupStatementInspector.class,
NestedPositiveIfStatementsInspector.class,
TernaryOperatorSimplifyInspector.class,
IfReturnReturnSimplificationInspector.class,
/*IfExpressionInEarlyReturnContextInspector.class,*/
DefaultValueInElseBranchInspector.class,
/*DefaultValuesForCallableParametersInspector.class,*/
ArrayTypeOfParameterByDefaultValueInspector.class,
SenselessCommaInArrayDefinitionInspector.class,
MoreThanThreeArgumentsInspector.class,
dirnameCallOnFileConstantInspector.class,
AmbiguousMethodsCallsInArrayMappingInspector.class,
CountInSecondIterateExpressionInspector.class,
SequentialUnSetCallsInspector.class,
NotOptimalIfConditionsInspection.class,
StrlenInEmptyStringCheckContextInspection.class,
OnlyWritesOnParameterInspector.class
};
}
}
|
src/com/kalessil/phpStorm/phpInspectionsEA/PhpInspectionsEAProvider.java
|
package com.kalessil.phpStorm.phpInspectionsEA;
import com.intellij.codeInspection.InspectionToolProvider;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.apiUsage.*;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.codeSmell.AmbiguousMethodsCallsInArrayMappingInspector;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.codeSmell.MoreThanThreeArgumentsInspector;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.earlyReturns.NestedPositiveIfStatementsInspector;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.languageConstructions.*;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.semanticalAnalysis.OnlyWritesOnParameterInspector;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.semanticalTransformations.DefaultValueInElseBranchInspector;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.semanticalTransformations.IfReturnReturnSimplificationInspector;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.semanticalTransformations.NotOptimalIfConditionsInspection;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.semanticalTransformations.StrlenInEmptyStringCheckContextInspection;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.strictInterfaces.ArrayTypeOfParameterByDefaultValueInspector;
/*
Some cases of interest:
-- not needed initialization
var $member = null;
-- suspicious counting in foreach
foreach(... as ...) {
...
$variable++||++$variable;
}
PhpCodeInsightUtil.isEmptyBody
*/
public class PhpInspectionsEAProvider implements InspectionToolProvider {
@Override
public Class[] getInspectionClasses() {
return new Class[]{
IsNullFunctionUsageInspector.class,
IsEmptyFunctionUsageInspector.class,
UnSafeIsSetOverArrayInspector.class,
ForgottenDebugOutputInspector.class,
UnNecessaryDoubleQuotesInspector.class,
TypeUnsafeComparisonInspector.class,
TypeUnsafeArraySearchInspector.class,
IfConditionalsWithoutGroupStatementInspector.class,
NestedPositiveIfStatementsInspector.class,
TernaryOperatorSimplifyInspector.class,
IfReturnReturnSimplificationInspector.class,
/*IfExpressionInEarlyReturnContextInspector.class,*/
DefaultValueInElseBranchInspector.class,
/*DefaultValuesForCallableParametersInspector.class,*/
ArrayTypeOfParameterByDefaultValueInspector.class,
SenselessCommaInArrayDefinitionInspector.class,
MoreThanThreeArgumentsInspector.class,
dirnameCallOnFileConstantInspector.class,
AmbiguousMethodsCallsInArrayMappingInspector.class,
CountInSecondIterateExpressionInspector.class,
SequentialUnSetCallsInspector.class,
NotOptimalIfConditionsInspection.class,
StrlenInEmptyStringCheckContextInspection.class,
OnlyWritesOnParameterInspector.class
};
}
}
|
added remarks about false positives and cases for further study
|
src/com/kalessil/phpStorm/phpInspectionsEA/PhpInspectionsEAProvider.java
|
added remarks about false positives and cases for further study
|
|
Java
|
mit
|
b7561de364b9ee8e0e6f9fdd92e9eded9358bb24
| 0
|
jjoller/aixi
|
package ch.jjoller.mcaixictw;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* Functionality for loading settings.
*
*/
public abstract class Settings implements Cloneable {
/**
* load standard settings
*/
public Settings() {
loadDefaultSettings();
}
/**
* parse from file
*
* @param path
* path to file
*/
public Settings(String path) {
loadDefaultSettings();
File file = new File(path);
parseSettings(file);
}
public abstract void parseSettings(File file);
public abstract void loadDefaultSettings();
public abstract Settings clone();
/**
* parse occurrence of the form "parameter = true" and return the value on
* the right side of the "=". Return the default (def) value if no
* occurrence found.
*
* @param parameter
* @param def
* @param file
* @return
*/
protected boolean parseBoolean(String parameter, boolean def, File file) {
try (Scanner scanner = new Scanner(file)) {
String s = scanner.findWithinHorizon(parameter
+ "\\p{Space}*=\\p{Space}*(true|false)", 10000);
if (s != null) {
s = s.split("=")[1].trim();
return s.equals("true") ? true : false;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return def;
}
/**
* parse occurrence of the form "parameter = 10" and return the value on the
* right side of the "=". Return the default (def) value if no occurrence
* found.
*
* @param parameter
* @param def
* @param file
* @return
*/
protected int parseInt(String parameter, int def, File file) {
try (Scanner scanner = new Scanner(file)) {
String s = scanner.findWithinHorizon(parameter
+ "\\p{Space}*=\\p{Space}*\\d+", 10000);
if (s != null) {
return new Integer(s.split("=")[1].trim());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return def;
}
/**
* parse occurrence of the form "parameter = 10.72" and return the value on
* the right side of the "=". Return the default (def) value if no
* occurrence found.
*
* @param parameter
* @param def
* @param file
* @return
*/
protected double parseDouble(String parameter, double def, File file) {
try (Scanner scanner = new Scanner(file)) {
String s = scanner.findWithinHorizon(parameter
+ "\\p{Space}*=\\p{Space}*\\d+\\.\\d+", 10000);
if (s != null) {
return new Double(s.split("=")[1].trim());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return def;
}
public abstract String toString();
// public String toString() {
// String s = "Agent Settings\n==============\n";
// s += "ctDepth: " + ctDepth + "\n";
// s += "horizon: " + horizon + "\n";
// s += "exploration: " + exploration + "\n";
// s += "exploreDecay: " + exploreDecay + "\n";
// s += "mcSimulations: " + mcSimulations + "\n";
// s += "terminationAge: " + terminationAge + "\n";
// s += "recycleUCT: " + recycleUCT + "\n";
// s += "factorialTree: " + factorialTree + "\n";
// s += "updateCTinMC: " + updateCTinMC + "\n";
// return s;
// }
}
|
MonteCarloAIXIApproximation/src/ch/jjoller/mcaixictw/Settings.java
|
package ch.jjoller.mcaixictw;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public abstract class Settings implements Cloneable {
/**
* load standard settings
*/
public Settings() {
loadDefaultSettings();
}
/**
* parse from file
*
* @param path
* path to file
*/
public Settings(String path) {
loadDefaultSettings();
File file = new File(path);
parseSettings(file);
}
public abstract void parseSettings(File file);
public abstract void loadDefaultSettings();
public abstract Settings clone();
/**
* parse occurrence of the form "parameter = true" and return the value on
* the right side of the "=". Return the default (def) value if no
* occurrence found.
*
* @param parameter
* @param def
* @param file
* @return
*/
protected boolean parseBoolean(String parameter, boolean def, File file) {
try (Scanner scanner = new Scanner(file)) {
String s = scanner.findWithinHorizon(parameter
+ "\\p{Space}*=\\p{Space}*(true|false)", 10000);
if (s != null) {
s = s.split("=")[1].trim();
return s.equals("true") ? true : false;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return def;
}
/**
* parse occurrence of the form "parameter = 10" and return the value on the
* right side of the "=". Return the default (def) value if no occurrence
* found.
*
* @param parameter
* @param def
* @param file
* @return
*/
protected int parseInt(String parameter, int def, File file) {
try (Scanner scanner = new Scanner(file)) {
String s = scanner.findWithinHorizon(parameter
+ "\\p{Space}*=\\p{Space}*\\d+", 10000);
if (s != null) {
return new Integer(s.split("=")[1].trim());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return def;
}
/**
* parse occurrence of the form "parameter = 10.72" and return the value on
* the right side of the "=". Return the default (def) value if no
* occurrence found.
*
* @param parameter
* @param def
* @param file
* @return
*/
protected double parseDouble(String parameter, double def, File file) {
try (Scanner scanner = new Scanner(file)) {
String s = scanner.findWithinHorizon(parameter
+ "\\p{Space}*=\\p{Space}*\\d+\\.\\d+", 10000);
if (s != null) {
return new Double(s.split("=")[1].trim());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return def;
}
public abstract String toString();
// public String toString() {
// String s = "Agent Settings\n==============\n";
// s += "ctDepth: " + ctDepth + "\n";
// s += "horizon: " + horizon + "\n";
// s += "exploration: " + exploration + "\n";
// s += "exploreDecay: " + exploreDecay + "\n";
// s += "mcSimulations: " + mcSimulations + "\n";
// s += "terminationAge: " + terminationAge + "\n";
// s += "recycleUCT: " + recycleUCT + "\n";
// s += "factorialTree: " + factorialTree + "\n";
// s += "updateCTinMC: " + updateCTinMC + "\n";
// return s;
// }
}
|
added some documentation
|
MonteCarloAIXIApproximation/src/ch/jjoller/mcaixictw/Settings.java
|
added some documentation
|
|
Java
|
mit
|
04a5136a6001980e156153f01427151faeb9e85b
| 0
|
Celethor/CS360proj1
|
package proj1.cs360;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.google.maps.DirectionsApi.RouteRestriction;
import com.google.maps.DistanceMatrixApi;
import com.google.maps.DistanceMatrixApiRequest;
import com.google.maps.GeoApiContext;
import com.google.maps.GeocodingApi;
import com.google.maps.errors.ApiException;
import com.google.maps.model.DistanceMatrix;
import com.google.maps.model.GeocodingResult;
import com.google.maps.model.LatLng;
import com.google.maps.model.TravelMode;
/*
* Author: @Celethor (Benjamin Treesh)
*
* THIs Class contains methods to lookup the address of an establishment given its name,
* It also contains a method to determine the distance between 2 establishments
*
* !!NOTE!! YOU WILL NEED TO ACTIVATE BOTH THE GOOGLE GEOCODING API AND THE GOOGLE DISTANCE MATRIX APIS
* FOR YOUR PROJECT IN ORDER TO USE THIS CLASS!!! THANK YOU!! :D
*
* credit to google-maps-services-java project on github for help in this method
* https://github.com/googlemaps/google-maps-services-java
*/
public class EarthSearch {
//private static final String API_KEY = "AIzaSyD2MvqQVbfXo3M0mMu4JPGXbaN3y5z9SIg";
private static final String API_KEY = "AIzaSyDOQ0NoT9r3RI0zYoO3q-p0h14Z4pggpQ0";
// Lookups up and returns the address of an establishment given its name and possible some location attributes
public static String lookupAddr(String establishment) throws ApiException, InterruptedException, IOException {
//set up key
GeoApiContext lookupDoodad = new GeoApiContext.Builder()
.apiKey(API_KEY)
.build();
GeocodingResult[] results = GeocodingApi.geocode(lookupDoodad,
establishment).await();
//converts results into usable address
String address = (results[0].formattedAddress);
return address;
}
// Lookups up and returns the coordinates of an establishment given its name and possible some location attributes
public static LatLng lookupCoord(String establishment) throws ApiException, InterruptedException, IOException {
//set up key
GeoApiContext lookupDoodad = new GeoApiContext.Builder()
.apiKey(API_KEY)
.build();
GeocodingResult[] results = GeocodingApi.geocode(lookupDoodad,
establishment).await();
//converts results into usable Coordinates
LatLng coords = (results[0].geometry.location);
return coords;
}
//given two addresses, calculates the driving distance
public static long getDriveDist(String addrOne, String addrTwo) throws ApiException, InterruptedException, IOException{
//set up key
GeoApiContext distCalcer = new GeoApiContext.Builder()
.apiKey(API_KEY)
.build();
DistanceMatrixApiRequest req = DistanceMatrixApi.newRequest(distCalcer);
DistanceMatrix result = req.origins(addrOne)
.destinations(addrTwo)
.mode(TravelMode.DRIVING)
.avoid(RouteRestriction.TOLLS)
.language("en-US")
.await();
long distApart = result.rows[0].elements[0].distance.inMeters;
return distApart;
}
public static void distanceMatrix(String[] origins, String[] destinations) throws ApiException, InterruptedException, IOException{
GeoApiContext context = new GeoApiContext.Builder()
.apiKey(API_KEY)
.build();
DistanceMatrixApiRequest req=DistanceMatrixApi.newRequest(context);
DistanceMatrix t=req.origins(origins).destinations(destinations).mode(TravelMode.DRIVING).await();
//long[][] array=new long[origins.length][destinations.length];
File file=new File("Matrix.txt");
FileOutputStream out=new FileOutputStream(file);
DataOutputStream outFile=new DataOutputStream(out);
for(int i=0;i<origins.length;i++){
for(int j=0;j<destinations.length;j++){
//System.out.println(t.rows[i].elements[j].distance.inMeters);
outFile.writeLong(t.rows[i].elements[j].distance.inMeters);
}
}
}
}
|
CS360Proj1/src/proj1/cs360/EarthSearch.java
|
package proj1.cs360;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.google.maps.DirectionsApi.RouteRestriction;
import com.google.maps.DistanceMatrixApi;
import com.google.maps.DistanceMatrixApiRequest;
import com.google.maps.GeoApiContext;
import com.google.maps.GeocodingApi;
import com.google.maps.errors.ApiException;
import com.google.maps.model.DistanceMatrix;
import com.google.maps.model.GeocodingResult;
import com.google.maps.model.LatLng;
import com.google.maps.model.TravelMode;
/*
* Author: @Celethor (Benjamin Treesh)
*
* THIs Class contains methods to lookup the address of an establishment given its name,
* It also contains a method to determine the distance between 2 establishments
*
* !!NOTE!! YOU WILL NEED TO ACTIVATE BOTH THE GOOGLE GEOCODING API AND THE GOOGLE DISTANCE MATRIX APIS
* FOR YOUR PROJECT IN ORDER TO USE THIS CLASS!!! THANK YOU!! :D
*
* credit to google-maps-services-java project on github for help in this method
* https://github.com/googlemaps/google-maps-services-java
*/
public class EarthSearch {
//private static final String API_KEY = "AIzaSyD2MvqQVbfXo3M0mMu4JPGXbaN3y5z9SIg";
private static final String API_KEY = "AIzaSyDOQ0NoT9r3RI0zYoO3q-p0h14Z4pggpQ0";
private static long[][] matrix;
// Lookups up and returns the address of an establishment given its name and possible some location attributes
public static String lookupAddr(String establishment) throws ApiException, InterruptedException, IOException {
//set up key
GeoApiContext lookupDoodad = new GeoApiContext.Builder()
.apiKey(API_KEY)
.build();
GeocodingResult[] results = GeocodingApi.geocode(lookupDoodad,
establishment).await();
//converts results into usable address
String address = (results[0].formattedAddress);
return address;
}
// Lookups up and returns the coordinates of an establishment given its name and possible some location attributes
public static LatLng lookupCoord(String establishment) throws ApiException, InterruptedException, IOException {
//set up key
GeoApiContext lookupDoodad = new GeoApiContext.Builder()
.apiKey(API_KEY)
.build();
GeocodingResult[] results = GeocodingApi.geocode(lookupDoodad,
establishment).await();
//converts results into usable Coordinates
LatLng coords = (results[0].geometry.location);
return coords;
}
//given two addresses, calculates the driving distance
public static long getDriveDist(String addrOne, String addrTwo) throws ApiException, InterruptedException, IOException{
//set up key
GeoApiContext distCalcer = new GeoApiContext.Builder()
.apiKey(API_KEY)
.build();
DistanceMatrixApiRequest req = DistanceMatrixApi.newRequest(distCalcer);
DistanceMatrix result = req.origins(addrOne)
.destinations(addrTwo)
.mode(TravelMode.DRIVING)
.avoid(RouteRestriction.TOLLS)
.language("en-US")
.await();
long distApart = result.rows[0].elements[0].distance.inMeters;
return distApart;
}
public static void distanceMatrix(String[] origins, String[] destinations) throws ApiException, InterruptedException, IOException{
GeoApiContext context = new GeoApiContext.Builder()
.apiKey(API_KEY)
.build();
DistanceMatrixApiRequest req=DistanceMatrixApi.newRequest(context);
DistanceMatrix t=req.origins(origins).destinations(destinations).mode(TravelMode.DRIVING).await();
//long[][] array=new long[origins.length][destinations.length];
matrix=new long[origins.length][destinations.length];
File file=new File("Matrix.txt");
FileOutputStream out=new FileOutputStream(file);
DataOutputStream outFile=new DataOutputStream(out);
for(int i=0;i<origins.length;i++){
for(int j=0;j<destinations.length;j++){
//System.out.println(t.rows[i].elements[j].distance.inMeters);
outFile.writeLong(t.rows[i].elements[j].distance.inMeters);
}
}
}
}
|
Deleted unused variables
|
CS360Proj1/src/proj1/cs360/EarthSearch.java
|
Deleted unused variables
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.