lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | bsd-3-clause | 3430a82ad3ab10c147877beaa6c20577db36ec11 | 0 | GeneralElectric/snowizard,jplock/snowizard,jplock/snowizard,GeneralElectric/snowizard | package com.ge.snowizard.service;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import java.io.File;
import javax.ws.rs.core.MediaType;
import org.junit.ClassRule;
import org.junit.Test;
import com.ge.snowizard.service.SnowizardConfiguration;
import com.ge.snowizard.service.SnowizardService;
import com.ge.snowizard.service.resources.IdResource;
import com.ge.snowizard.service.resources.PingResource;
import com.ge.snowizard.service.resources.SnowizardResource;
import com.google.common.io.Resources;
import com.sun.jersey.api.client.Client;
import com.yammer.dropwizard.config.Environment;
import com.yammer.dropwizard.testing.junit.DropwizardServiceRule;
public class SnowizardServiceTest {
private final String AGENT = "snowizard-client";
private final Environment environment = mock(Environment.class);
private final SnowizardService service = new SnowizardService();
private final SnowizardConfiguration config = new SnowizardConfiguration();
@ClassRule
public static final DropwizardServiceRule<SnowizardConfiguration> RULE = new DropwizardServiceRule<SnowizardConfiguration>(
SnowizardService.class, resourceFilePath("test-snowizard.yml"));
@Test
public void buildsAIdResource() throws Exception {
service.run(config, environment);
verify(environment, times(3)).addResource(any(IdResource.class));
verify(environment, times(3)).addResource(any(PingResource.class));
verify(environment, times(3)).addResource(any(SnowizardResource.class));
}
@Test
public void testCanGetIdOverHttp() throws Exception {
final String response = new Client()
.resource("http://localhost:" + RULE.getLocalPort())
.accept(MediaType.TEXT_PLAIN).header("User-Agent", AGENT)
.get(String.class);
final long id = Long.valueOf(response);
assertThat(id).isNotNull();
}
public static String resourceFilePath(String resourceClassPathLocation) {
try {
return new File(Resources.getResource(resourceClassPathLocation)
.toURI()).getAbsolutePath();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| snowizard-service/src/test/java/com/ge/snowizard/service/SnowizardServiceTest.java | package com.ge.snowizard.service;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import java.io.File;
import javax.ws.rs.core.MediaType;
import org.junit.ClassRule;
import org.junit.Test;
import com.ge.snowizard.service.SnowizardConfiguration;
import com.ge.snowizard.service.SnowizardService;
import com.ge.snowizard.service.resources.IdResource;
import com.google.common.io.Resources;
import com.sun.jersey.api.client.Client;
import com.yammer.dropwizard.config.Environment;
import com.yammer.dropwizard.testing.junit.DropwizardServiceRule;
public class SnowizardServiceTest {
private final String AGENT = "snowizard-client";
private final Environment environment = mock(Environment.class);
private final SnowizardService service = new SnowizardService();
private final SnowizardConfiguration config = new SnowizardConfiguration();
@ClassRule
public static final DropwizardServiceRule<SnowizardConfiguration> RULE = new DropwizardServiceRule<SnowizardConfiguration>(
SnowizardService.class, resourceFilePath("test-snowizard.yml"));
@Test
public void buildsAIdResource() throws Exception {
service.run(config, environment);
verify(environment).addResource(any(IdResource.class));
}
@Test
public void testCanGetIdOverHttp() throws Exception {
final String response = new Client()
.resource("http://localhost:" + RULE.getLocalPort())
.accept(MediaType.TEXT_PLAIN).header("User-Agent", AGENT)
.get(String.class);
final long id = Long.valueOf(response);
assertThat(id).isNotNull();
}
public static String resourceFilePath(String resourceClassPathLocation) {
try {
return new File(Resources.getResource(resourceClassPathLocation)
.toURI()).getAbsolutePath();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| Fixed failing unit test after adding PingResource and SnowizardResource
| snowizard-service/src/test/java/com/ge/snowizard/service/SnowizardServiceTest.java | Fixed failing unit test after adding PingResource and SnowizardResource | <ide><path>nowizard-service/src/test/java/com/ge/snowizard/service/SnowizardServiceTest.java
<ide> import com.ge.snowizard.service.SnowizardConfiguration;
<ide> import com.ge.snowizard.service.SnowizardService;
<ide> import com.ge.snowizard.service.resources.IdResource;
<add>import com.ge.snowizard.service.resources.PingResource;
<add>import com.ge.snowizard.service.resources.SnowizardResource;
<ide> import com.google.common.io.Resources;
<ide> import com.sun.jersey.api.client.Client;
<ide> import com.yammer.dropwizard.config.Environment;
<ide> @Test
<ide> public void buildsAIdResource() throws Exception {
<ide> service.run(config, environment);
<del> verify(environment).addResource(any(IdResource.class));
<add> verify(environment, times(3)).addResource(any(IdResource.class));
<add> verify(environment, times(3)).addResource(any(PingResource.class));
<add> verify(environment, times(3)).addResource(any(SnowizardResource.class));
<ide> }
<ide>
<ide> @Test |
|
Java | apache-2.0 | 7f52c64196ac3719bbdb3045f5e730a1e31fefae | 0 | apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere | /*
* 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.shardingsphere.infra.hint;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public final class HintManagerTest {
@Test(expected = IllegalStateException.class)
public void assertGetInstanceTwice() {
try {
HintManager.getInstance();
HintManager.getInstance();
} finally {
HintManager.clear();
}
}
@Test
public void assertSetDatabaseShardingValue() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setDatabaseShardingValue(1);
hintManager.setDatabaseShardingValue(3);
assertTrue(HintManager.isDatabaseShardingOnly());
assertThat(HintManager.getDatabaseShardingValues("").size(), is(1));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getDatabaseShardingValues(""));
assertThat(shardingValues.get(0), is(3));
}
}
@Test
public void assertAddDatabaseShardingValue() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.addDatabaseShardingValue("logicTable", 1);
hintManager.addDatabaseShardingValue("logicTable", 3);
assertThat(HintManager.getDatabaseShardingValues("logicTable").size(), is(2));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getDatabaseShardingValues("logicTable"));
assertThat(shardingValues.get(0), is(1));
assertThat(shardingValues.get(1), is(3));
}
}
@Test
public void assertAddTableShardingValue() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.addTableShardingValue("logicTable", 1);
hintManager.addTableShardingValue("logicTable", 3);
assertThat(HintManager.getTableShardingValues("logicTable").size(), is(2));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getTableShardingValues("logicTable"));
assertThat(shardingValues.get(0), is(1));
assertThat(shardingValues.get(1), is(3));
}
}
@Test
public void assertGetDatabaseShardingValuesWithoutLogicTable() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setDatabaseShardingValue(1);
assertThat(HintManager.getDatabaseShardingValues().size(), is(1));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getDatabaseShardingValues());
assertThat(shardingValues.get(0), is(1));
}
}
@Test
public void assertGetDatabaseShardingValuesWithLogicTable() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.addDatabaseShardingValue("logic_table", 1);
assertThat(HintManager.getDatabaseShardingValues("logic_table").size(), is(1));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getDatabaseShardingValues("logic_table"));
assertThat(shardingValues.get(0), is(1));
}
}
@Test
public void assertGetTableShardingValues() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.addTableShardingValue("logic_table", 1);
assertThat(HintManager.getTableShardingValues("logic_table").size(), is(1));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getTableShardingValues("logic_table"));
assertThat(shardingValues.get(0), is(1));
}
}
@Test
public void assertIsDatabaseShardingOnly() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setDatabaseShardingValue(1);
assertTrue(HintManager.isDatabaseShardingOnly());
}
}
@Test
public void assertIsDatabaseShardingOnlyWithoutSet() {
HintManager hintManager = HintManager.getInstance();
hintManager.close();
assertFalse(HintManager.isDatabaseShardingOnly());
}
@Test
public void assertAddDatabaseShardingValueOnlyDatabaseSharding() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setDatabaseShardingValue(1);
assertTrue(HintManager.isDatabaseShardingOnly());
hintManager.addDatabaseShardingValue("logic_table", 2);
assertFalse(HintManager.isDatabaseShardingOnly());
assertThat(HintManager.getDatabaseShardingValues("logic_table").size(), is(1));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getDatabaseShardingValues("logic_table"));
assertThat(shardingValues.get(0), is(2));
}
}
@Test
public void assertAddTableShardingValueOnlyDatabaseSharding() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setDatabaseShardingValue(1);
assertTrue(HintManager.isDatabaseShardingOnly());
hintManager.addTableShardingValue("logic_table", 2);
assertFalse(HintManager.isDatabaseShardingOnly());
assertThat(HintManager.getTableShardingValues("logic_table").size(), is(1));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getTableShardingValues("logic_table"));
assertThat(shardingValues.get(0), is(2));
}
}
@Test
public void assertSetPrimaryRouteOnly() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setWriteRouteOnly();
assertTrue(HintManager.isWriteRouteOnly());
}
}
@Test
public void assertIsPrimaryRouteOnly() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setWriteRouteOnly();
assertTrue(HintManager.isWriteRouteOnly());
}
}
@Test
public void assertIsPrimaryRouteOnlyWithoutSet() {
HintManager hintManager = HintManager.getInstance();
hintManager.close();
assertFalse(HintManager.isWriteRouteOnly());
}
@Test
public void assertClose() {
HintManager hintManager = HintManager.getInstance();
hintManager.addDatabaseShardingValue("logic_table", 1);
hintManager.addTableShardingValue("logic_table", 1);
hintManager.close();
assertTrue(HintManager.getDatabaseShardingValues("logic_table").isEmpty());
assertTrue(HintManager.getTableShardingValues("logic_table").isEmpty());
}
}
| shardingsphere-infra/shardingsphere-infra-common/src/test/java/org/apache/shardingsphere/infra/hint/HintManagerTest.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.shardingsphere.infra.hint;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public final class HintManagerTest {
@Test(expected = IllegalStateException.class)
public void assertGetInstanceTwice() {
try {
HintManager.getInstance();
HintManager.getInstance();
} finally {
HintManager.clear();
}
}
@Test
public void assertSetDatabaseShardingValue() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setDatabaseShardingValue(1);
hintManager.setDatabaseShardingValue(3);
assertTrue(HintManager.isDatabaseShardingOnly());
assertThat(HintManager.getDatabaseShardingValues("").size(), is(1));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getDatabaseShardingValues(""));
assertThat(shardingValues.get(0), is(3));
}
}
@Test
public void assertAddDatabaseShardingValue() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.addDatabaseShardingValue("logicTable", 1);
hintManager.addDatabaseShardingValue("logicTable", 3);
assertThat(HintManager.getDatabaseShardingValues("logicTable").size(), is(2));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getDatabaseShardingValues("logicTable"));
assertThat(shardingValues.get(0), is(1));
assertThat(shardingValues.get(1), is(3));
}
}
@Test
public void assertAddTableShardingValue() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.addTableShardingValue("logicTable", 1);
hintManager.addTableShardingValue("logicTable", 3);
assertThat(HintManager.getTableShardingValues("logicTable").size(), is(2));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getTableShardingValues("logicTable"));
assertThat(shardingValues.get(0), is(1));
assertThat(shardingValues.get(1), is(3));
}
}
@Test
public void assertGetDatabaseShardingValuesWithoutLogicTable() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setDatabaseShardingValue(1);
assertThat(HintManager.getDatabaseShardingValues().size(), is(1));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getDatabaseShardingValues());
assertThat(shardingValues.get(0), is(1));
}
}
@Test
public void assertGetDatabaseShardingValuesWithLogicTable() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.addDatabaseShardingValue("logic_table", 1);
assertThat(HintManager.getDatabaseShardingValues("logic_table").size(), is(1));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getDatabaseShardingValues("logic_table"));
assertThat(shardingValues.get(0), is(1));
}
}
@Test
public void assertGetTableShardingValues() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.addTableShardingValue("logic_table", 1);
assertThat(HintManager.getTableShardingValues("logic_table").size(), is(1));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getTableShardingValues("logic_table"));
assertThat(shardingValues.get(0), is(1));
}
}
@Test
public void assertIsDatabaseShardingOnly() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setDatabaseShardingValue(1);
assertTrue(HintManager.isDatabaseShardingOnly());
}
}
@Test
public void assertIsDatabaseShardingOnlyWithoutSet() {
HintManager hintManager = HintManager.getInstance();
hintManager.close();
assertFalse(HintManager.isDatabaseShardingOnly());
}
@Test
public void assertAddDatabaseShardingValueOnlyDatabaseSharding() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setDatabaseShardingValue(1);
assertTrue(HintManager.isDatabaseShardingOnly());
hintManager.addDatabaseShardingValue("logic_table", 2);
assertFalse(HintManager.isDatabaseShardingOnly());
assertThat(HintManager.getDatabaseShardingValues("logic_table").size(), is(1));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getDatabaseShardingValues("logic_table"));
assertThat(shardingValues.get(0), is(2));
}
}
@Test
public void assertAddTableShardingValueOnlyDatabaseSharding() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setDatabaseShardingValue(1);
assertTrue(HintManager.isDatabaseShardingOnly());
hintManager.addTableShardingValue("logic_table", 2);
assertFalse(HintManager.isDatabaseShardingOnly());
assertThat(HintManager.getTableShardingValues("logic_table").size(), is(1));
List<Comparable<?>> shardingValues = new ArrayList<>(HintManager.getTableShardingValues("logic_table"));
assertThat(shardingValues.get(0), is(2));
}
}
@Test
public void assertSetPrimaryRouteOnly() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setWriteRouteOnly();
assertTrue(HintManager.isWriteRouteOnly());
}
}
@Test
public void assertIsPrimaryRouteOnly() {
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setWriteRouteOnly();
assertTrue(HintManager.isWriteRouteOnly());
}
}
@Test
public void assertIsPrimaryRouteOnlyWithoutSet() {
HintManager hintManager = HintManager.getInstance();
hintManager.close();
assertFalse(HintManager.isWriteRouteOnly());
}
@Test
public void assertClose() {
HintManager hintManager = HintManager.getInstance();
hintManager.addDatabaseShardingValue("logic_table", 1);
hintManager.addTableShardingValue("logic_table", 1);
hintManager.close();
assertTrue(HintManager.getDatabaseShardingValues("logic_table").isEmpty());
assertTrue(HintManager.getTableShardingValues("logic_table").isEmpty());
}
}
| Revise #9818 (#9829)
| shardingsphere-infra/shardingsphere-infra-common/src/test/java/org/apache/shardingsphere/infra/hint/HintManagerTest.java | Revise #9818 (#9829) | <ide><path>hardingsphere-infra/shardingsphere-infra-common/src/test/java/org/apache/shardingsphere/infra/hint/HintManagerTest.java
<ide> import static org.junit.Assert.assertTrue;
<ide>
<ide> public final class HintManagerTest {
<del>
<add>
<ide> @Test(expected = IllegalStateException.class)
<ide> public void assertGetInstanceTwice() {
<ide> try {
<ide> HintManager.clear();
<ide> }
<ide> }
<del>
<add>
<ide> @Test
<ide> public void assertSetDatabaseShardingValue() {
<ide> try (HintManager hintManager = HintManager.getInstance()) {
<ide> assertThat(shardingValues.get(0), is(3));
<ide> }
<ide> }
<del>
<add>
<ide> @Test
<ide> public void assertAddDatabaseShardingValue() {
<ide> try (HintManager hintManager = HintManager.getInstance()) {
<ide> assertThat(shardingValues.get(1), is(3));
<ide> }
<ide> }
<del>
<add>
<ide> @Test
<ide> public void assertAddTableShardingValue() {
<ide> try (HintManager hintManager = HintManager.getInstance()) {
<ide> assertThat(shardingValues.get(1), is(3));
<ide> }
<ide> }
<del>
<add>
<ide> @Test
<ide> public void assertGetDatabaseShardingValuesWithoutLogicTable() {
<ide> try (HintManager hintManager = HintManager.getInstance()) {
<ide> assertThat(shardingValues.get(0), is(1));
<ide> }
<ide> }
<del>
<add>
<ide> @Test
<ide> public void assertGetDatabaseShardingValuesWithLogicTable() {
<ide> try (HintManager hintManager = HintManager.getInstance()) {
<ide> assertThat(shardingValues.get(0), is(1));
<ide> }
<ide> }
<del>
<add>
<ide> @Test
<ide> public void assertGetTableShardingValues() {
<ide> try (HintManager hintManager = HintManager.getInstance()) {
<ide> assertThat(shardingValues.get(0), is(1));
<ide> }
<ide> }
<del>
<add>
<ide> @Test
<ide> public void assertIsDatabaseShardingOnly() {
<ide> try (HintManager hintManager = HintManager.getInstance()) {
<ide> assertTrue(HintManager.isDatabaseShardingOnly());
<ide> }
<ide> }
<del>
<add>
<ide> @Test
<ide> public void assertIsDatabaseShardingOnlyWithoutSet() {
<ide> HintManager hintManager = HintManager.getInstance();
<ide> hintManager.close();
<ide> assertFalse(HintManager.isDatabaseShardingOnly());
<ide> }
<del>
<add>
<ide> @Test
<ide> public void assertAddDatabaseShardingValueOnlyDatabaseSharding() {
<ide> try (HintManager hintManager = HintManager.getInstance()) {
<ide> assertThat(shardingValues.get(0), is(2));
<ide> }
<ide> }
<del>
<add>
<ide> @Test
<ide> public void assertAddTableShardingValueOnlyDatabaseSharding() {
<ide> try (HintManager hintManager = HintManager.getInstance()) {
<ide> assertThat(shardingValues.get(0), is(2));
<ide> }
<ide> }
<del>
<add>
<ide> @Test
<ide> public void assertSetPrimaryRouteOnly() {
<ide> try (HintManager hintManager = HintManager.getInstance()) {
<ide> assertTrue(HintManager.isWriteRouteOnly());
<ide> }
<ide> }
<del>
<add>
<ide> @Test
<ide> public void assertIsPrimaryRouteOnly() {
<ide> try (HintManager hintManager = HintManager.getInstance()) {
<ide> assertTrue(HintManager.isWriteRouteOnly());
<ide> }
<ide> }
<del>
<add>
<ide> @Test
<ide> public void assertIsPrimaryRouteOnlyWithoutSet() {
<ide> HintManager hintManager = HintManager.getInstance();
<ide> hintManager.close();
<ide> assertFalse(HintManager.isWriteRouteOnly());
<ide> }
<del>
<add>
<ide> @Test
<ide> public void assertClose() {
<ide> HintManager hintManager = HintManager.getInstance(); |
|
JavaScript | mit | 00e8bb5f39b647213df065a65cd96643b79a97f4 | 0 | ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt | 'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class bcex extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'bcex',
'name': 'BCEX',
'countries': [ 'CN', 'CA' ],
'version': '1',
'has': {
'fetchBalance': true,
'fetchMarkets': true,
'createOrder': true,
'cancelOrder': true,
'fetchTicker': true,
'fetchTickers': false,
'fetchTrades': true,
'fetchOrder': true,
'fetchOrders': true,
'fetchOpenOrders': true,
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/43362240-21c26622-92ee-11e8-9464-5801ec526d77.jpg',
'api': 'https://www.bcex.top',
'www': 'https://www.bcex.top',
'doc': 'https://www.bcex.top/api_market/market/',
'fees': 'http://bcex.udesk.cn/hc/articles/57085',
'referral': 'https://www.bcex.top/user/reg/type/2/pid/758978',
},
'api': {
'public': {
'get': [
'Api_Market/getPriceList', // tickers
],
'post': [
'Api_Order/ticker', // last ohlcv candle (ticker)
'Api_Order/depth', // orderbook
'Api_Market/getCoinTrade', // ticker
'Api_Order/marketOrder', // trades...
],
},
'private': {
'post': [
'Api_Order/cancel',
'Api_Order/coinTrust', // limit order
'Api_Order/orderList', // my trades
'Api_Order/orderInfo',
'Api_Order/tradeList', // open / all orders
'Api_Order/trustList', // ?
'Api_User/userBalance',
],
},
},
'fees': {
'trading': {
'tierBased': false,
'percentage': true,
'bid': 0.0,
'ask': 0.02 / 100,
},
'funding': {
'tierBased': false,
'percentage': false,
'withdraw': {
'ckusd': 0.0,
'other': 0.05 / 100,
},
'deposit': {},
},
'exceptions': {
'该币不存在,非法操作': ExchangeError, // { code: 1, msg: "该币不存在,非法操作" } - returned when a required symbol parameter is missing in the request (also, maybe on other types of errors as well)
},
},
});
}
async fetchMarkets () {
let response = await this.publicGetApiMarketGetPriceList ();
let result = [];
let keys = Object.keys (response);
for (let i = 0; i < keys.length; i++) {
let currentMarketId = keys[i];
let currentMarkets = response[currentMarketId];
for (let j = 0; j < currentMarkets.length; j++) {
let market = currentMarkets[j];
let baseId = market['coin_from'];
let quoteId = market['coin_to'];
let base = baseId.toUpperCase ();
let quote = quoteId.toUpperCase ();
base = this.commonCurrencyCode (base);
quote = this.commonCurrencyCode (quote);
let id = baseId + '2' + quoteId;
let symbol = base + '/' + quote;
let active = true;
let precision = {
'amount': undefined, // todo: might need this for proper order placement
'price': undefined, // todo: find a way to get these values
};
let limits = {
'amount': {
'min': undefined, // todo
'max': undefined,
},
'price': {
'min': undefined, // todo
'max': undefined,
},
'cost': {
'min': undefined, // todo
'max': undefined,
},
};
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'active': active,
'precision': precision,
'limits': limits,
'info': market,
});
}
}
return result;
}
parseTrade (trade, market = undefined) {
let symbol = undefined;
if (typeof market !== 'undefined') {
symbol = market['symbol'];
}
let timestamp = trade['date'] * 1000;
return {
'id': trade['tid'],
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': undefined,
'side': trade['type'],
'price': this.safeFloat (trade, 'price'),
'amount': this.safeFloat (trade, 'amount'),
'order': undefined,
'fee': undefined,
};
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let request = {
'symbol': this.marketId (symbol),
};
if (typeof limit !== 'undefined') {
request['limit'] = limit;
}
let market = this.market (symbol);
let response = await this.publicPostApiOrderMarketOrder (this.extend (request, params));
return this.parseTrades (response['data'], market, since, limit);
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
let response = await this.privatePostApiUserUserBalance (params);
let data = response['data'];
let keys = Object.keys (data);
let result = { };
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
let amount = this.safeFloat (data, key);
let parts = key.split ('_');
let currencyId = parts[0];
let lockOrOver = parts[1];
let code = currencyId.toUpperCase ();
if (currencyId in this.currencies_by_id) {
code = this.currencies_by_id[currencyId]['code'];
} else {
code = this.commonCurrencyCode (code);
}
if (!(code in result)) {
let account = this.account ();
result[code] = account;
}
if (lockOrOver === 'lock') {
result[code]['used'] = parseFloat (amount);
} else {
result[code]['free'] = parseFloat (amount);
}
}
keys = Object.keys (result);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
let total = this.sum (result[key]['used'], result[key]['total']);
result[key]['total'] = total;
}
result['info'] = data;
return this.parseBalance (result);
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
let market = this.markets[symbol];
let request = {
'part': market['quoteId'],
'coin': market['baseId'],
};
let response = await this.publicPostApiMarketGetCoinTrade (this.extend (request, params));
let timestamp = this.milliseconds ();
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeFloat (response, 'max'),
'low': this.safeFloat (response, 'min'),
'bid': this.safeFloat (response, 'buy'),
'bidVolume': undefined,
'ask': this.safeFloat (response, 'sale'),
'askVolume': undefined,
'vwap': undefined,
'open': undefined,
'close': this.safeFloat (response, 'price'),
'last': this.safeFloat (response, 'price'),
'previousClose': undefined,
'change': undefined,
'percentage': this.safeFloat (response, 'change_24h'),
'average': undefined,
'baseVolume': this.safeFloat (response, 'volume_24h'),
'quoteVolume': undefined,
'info': response,
};
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
let marketId = this.marketId (symbol);
let request = {
'symbol': marketId,
};
let response = await this.publicPostApiOrderDepth (this.extend (request, params));
let data = response['data'];
let orderbook = this.parseOrderBook (data, data['date']);
return orderbook;
}
parseMyTrade (trade, market) {
let timestamp = trade['created'] * 1000;
return {
'id': trade['order_id'],
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': market.symbol,
'type': undefined,
'side': trade['side'],
'price': this.safeFloat (trade, 'price'),
'amount': this.safeFloat (trade, 'number'),
'order': undefined,
'fee': undefined,
};
}
parseMyTrades (trades, market = undefined, since = undefined, limit = undefined) {
let result = [];
for (let i = 0; i < trades.length; i++) {
result.push (this.parseMyTrade (trades[i], market)); // will edit for parseMyTrade → parseTrade
}
result = this.sortBy (result, 'timestamp');
let symbol = (typeof market !== 'undefined') ? market['symbol'] : undefined;
return this.filterBySymbolSinceLimit (result, symbol, since, limit);
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let marketId = this.marketId (symbol);
let request = {
'symbol': marketId,
};
let response = await this.privatePostApiOrderOrderList (this.extend (request, params));
let market = this.markets_by_id[marketId];
let trades = response['data'];
let result = this.parseMyTrades (trades, market);
return result;
}
parseStatus (statusCode) {
if (statusCode === 0 || statusCode === 1) {
return 'open';
} else if (statusCode === 2) {
return 'closed';
} else if (statusCode === 3) {
return 'canceled';
}
return undefined;
}
async fetchOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let request = {
'symbol': this.marketId (symbol),
'trust_id': id,
};
let response = await this.privatePostApiOrderOrderInfo (this.extend (request, params));
let order = response['data'];
let timestamp = order['created'] * 1000;
let status = this.parseStatus (order['status']);
let result = {
'info': order,
'id': id,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': undefined,
'symbol': symbol,
'type': order['flag'],
'side': undefined,
'price': order['price'],
'cost': undefined,
'average': undefined,
'amount': order['number'],
'filled': order['numberdeal'],
'remaining': order['numberover'],
'status': status,
'fee': undefined,
};
return result;
}
parseOrder (order, market = undefined) {
let id = order['id'].toString ();
let timestamp = order['datetime'] * 1000;
let iso8601 = this.iso8601 (timestamp);
let symbol = market['symbol'];
let type = undefined;
let side = order['type'];
let price = order['price'];
let average = order['avg_price'];
let amount = order['amount'];
let remaining = order['amount_outstanding'];
let filled = amount - remaining;
let status = this.parseStatus (order['status']);
let cost = filled * price;
let fee = undefined;
let result = {
'info': order,
'id': id,
'timestamp': timestamp,
'datetime': iso8601,
'lastTradeTimestamp': undefined,
'symbol': symbol,
'type': type,
'side': side,
'price': price,
'cost': cost,
'average': average,
'amount': amount,
'filled': filled,
'remaining': remaining,
'status': status,
'fee': fee,
};
return result;
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let request = {};
let marketId = this.marketId (symbol);
request['type'] = 'open';
if (typeof symbol !== 'undefined') {
request['symbol'] = marketId;
}
let orders = [];
let response = await this.privatePostApiOrderTradeList (this.extend (request, params));
if ('data' in response) {
orders = response['data'];
}
let market = this.markets_by_id[marketId];
let results = this.parseOrders (orders, market, since, limit);
return results;
}
async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let request = {};
let marketId = this.marketId (symbol);
request['type'] = 'all';
if (typeof symbol !== 'undefined') {
request['symbol'] = marketId;
}
let orders = [];
let response = await this.privatePostApiOrderTradeList (this.extend (request, params));
if ('data' in response) {
orders = response['data'];
}
let market = this.markets_by_id[marketId];
let results = this.parseOrders (orders, market, since, limit);
return results;
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
let order = {
'symbol': this.marketId (symbol),
'type': side,
'price': price,
'number': amount,
};
let response = await this.privatePostApiOrderCoinTrust (this.extend (order, params));
let data = response['data'];
return {
'info': response,
'id': this.safeString (data, 'order_id'),
};
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let request = {};
if (typeof symbol !== 'undefined') {
request['symbol'] = symbol;
}
if (typeof id !== 'undefined') {
request['order_id'] = id;
}
let results = await this.privatePostApiOrderCancel (this.extend (request, params));
return results;
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let request = '/' + this.implodeParams (path, params);
let query = this.omit (params, this.extractParams (path));
if (method === 'GET') {
if (Object.keys (query).length)
request += '?' + this.urlencode (query);
}
let url = this.urls['api'] + request;
if (method === 'POST') {
let messageParts = [];
let keys = Object.keys (params);
let paramsKeys = keys.sort ();
for (let i = 0; i < paramsKeys.length; i++) {
let paramKey = paramsKeys[i];
let param = params[paramKey];
messageParts.push (this.encode (paramKey) + '=' + this.encodeURIComponent (param));
}
if (api === 'private') {
this.checkRequiredCredentials ();
messageParts.unshift ('api_key=' + this.encodeURIComponent (this.apiKey));
body = messageParts.join ('&');
let message = body + '&secret_key=' + this.secret;
let signedMessage = this.hash (message);
body = body + '&sign=' + signedMessage;
params['sign'] = signedMessage;
} else {
body = messageParts.join ('&');
}
headers = {};
headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
handleErrors (code, reason, url, method, headers, body) {
if (body[0] === '{' && (url.indexOf ('private') >= 0)) {
let response = JSON.parse (body);
let code = this.safeValue (response, 'code');
if (code !== 0) {
throw new ExchangeError (this.id + ' ' + body);
}
}
}
};
| js/bcex.js | 'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class bcex extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'bcex',
'name': 'BCEX',
'countries': [ 'CN', 'CA' ],
'version': '1',
'has': {
'fetchBalance': true,
'fetchMarkets': true,
'createOrder': true,
'cancelOrder': true,
'fetchTicker': true,
'fetchTickers': false,
'fetchTrades': true,
'fetchOrder': true,
'fetchOrders': true,
'fetchOpenOrders': true,
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/43362240-21c26622-92ee-11e8-9464-5801ec526d77.jpg',
'api': 'https://www.bcex.top',
'www': 'https://www.bcex.top',
'doc': 'https://www.bcex.top/api_market/market/',
'fees': 'http://bcex.udesk.cn/hc/articles/57085',
'referral': 'https://www.bcex.top/user/reg/type/2/pid/758978',
},
'api': {
'public': {
'get': [
'Api_Market/getPriceList', // tickers
],
'post': [
'Api_Order/ticker', // last ohlcv candle (ticker)
'Api_Order/depth', // orderbook
'Api_Market/getCoinTrade', // ticker
'Api_Order/marketOrder', // trades...
],
},
'private': {
'post': [
'Api_Order/cancel',
'Api_Order/coinTrust', // limit order
'Api_Order/orderList', // my trades
'Api_Order/orderInfo',
'Api_Order/tradeList', // open / all orders
'Api_Order/trustList', // ?
'Api_User/userBalance',
],
},
},
'fees': {
'trading': {
'tierBased': false,
'percentage': true,
'bid': 0.0,
'ask': 0.02 / 100,
},
'funding': {
'tierBased': false,
'percentage': false,
'withdraw': {
'ckusd': 0.0,
'other': 0.05 / 100,
},
'deposit': {},
},
'exceptions': {
'该币不存在,非法操作': ExchangeError, // { code: 1, msg: "该币不存在,非法操作" } - returned when a required symbol parameter is missing in the request (also, maybe on other types of errors as well)
},
},
});
}
async fetchMarkets () {
let response = await this.publicGetApiMarketGetPriceList ();
let result = [];
let keys = Object.keys (response);
for (let i = 0; i < keys.length; i++) {
let currentMarketId = keys[i];
let currentMarkets = response[currentMarketId];
for (let j = 0; j < currentMarkets.length; j++) {
let market = currentMarkets[j];
let baseId = market['coin_from'];
let quoteId = market['coin_to'];
let base = baseId.toUpperCase ();
let quote = quoteId.toUpperCase ();
base = this.commonCurrencyCode (base);
quote = this.commonCurrencyCode (quote);
let id = baseId + '2' + quoteId;
let symbol = base + '/' + quote;
let active = true;
let precision = {
'amount': undefined, // todo: might need this for proper order placement
'price': undefined, // todo: find a way to get these values
};
let limits = {
'amount': {
'min': undefined, // todo
'max': undefined,
},
'price': {
'min': undefined, // todo
'max': undefined,
},
'cost': {
'min': undefined, // todo
'max': undefined,
},
};
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'active': active,
'precision': precision,
'limits': limits,
'info': market,
});
}
}
return result;
}
parseTrade (trade, market = undefined) {
let symbol = undefined;
if (typeof market !== 'undefined') {
symbol = market['symbol'];
}
let timestamp = trade['date'] * 1000;
return {
'id': trade['tid'],
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': undefined,
'side': trade['type'],
'price': this.safeFloat (trade, 'price'),
'amount': this.safeFloat (trade, 'amount'),
'order': undefined,
'fee': undefined,
};
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let request = {
'symbol': this.marketId (symbol),
};
if (typeof limit !== 'undefined') {
request['limit'] = limit;
}
let market = this.market (symbol);
let response = await this.publicPostApiOrderMarketOrder (this.extend (request, params));
return this.parseTrades (response['data'], market, since, limit);
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
let response = await this.privatePostApiUserUserBalance (params);
let data = response['data'];
let keys = Object.keys (data);
let result = { };
for (let i = 0; i < keys.length; i++) {
let currentKey = keys[i];
let currentAmount = data[currentKey];
let split = currentKey.split ('_');
let id = split[0];
let lockOrOver = split[1];
let currency = this.commonCurrencyCode (id);
if (!(currency in result)) {
let account = this.account ();
result[currency] = account;
}
if (lockOrOver === 'lock') {
result[currency]['used'] = parseFloat (currentAmount);
} else {
result[currency]['free'] = parseFloat (currentAmount);
}
}
keys = Object.keys (result);
for (let i = 0; i < keys.length; i++) {
let currentKey = keys[i];
let total = this.sum (result[currentKey]['used'], result[currentKey]['total']);
result[currentKey]['total'] = total;
}
result['info'] = data;
return this.parseBalance (result);
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
let market = this.markets[symbol];
let request = {
'part': market['quoteId'],
'coin': market['baseId'],
};
let response = await this.publicPostApiMarketGetCoinTrade (this.extend (request, params));
let timestamp = this.milliseconds ();
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeFloat (response, 'max'),
'low': this.safeFloat (response, 'min'),
'bid': this.safeFloat (response, 'buy'),
'bidVolume': undefined,
'ask': this.safeFloat (response, 'sale'),
'askVolume': undefined,
'vwap': undefined,
'open': undefined,
'close': this.safeFloat (response, 'price'),
'last': this.safeFloat (response, 'price'),
'previousClose': undefined,
'change': undefined,
'percentage': this.safeFloat (response, 'change_24h'),
'average': undefined,
'baseVolume': this.safeFloat (response, 'volume_24h'),
'quoteVolume': undefined,
'info': response,
};
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
let marketId = this.marketId (symbol);
let request = {
'symbol': marketId,
};
let response = await this.publicPostApiOrderDepth (this.extend (request, params));
let data = response['data'];
let orderbook = this.parseOrderBook (data, data['date']);
return orderbook;
}
parseMyTrade (trade, market) {
let timestamp = trade['created'] * 1000;
return {
'id': trade['order_id'],
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': market.symbol,
'type': undefined,
'side': trade['side'],
'price': this.safeFloat (trade, 'price'),
'amount': this.safeFloat (trade, 'number'),
'order': undefined,
'fee': undefined,
};
}
parseMyTrades (trades, market = undefined, since = undefined, limit = undefined) {
let result = [];
for (let i = 0; i < trades.length; i++) {
result.push (this.parseMyTrade (trades[i], market)); // will edit for parseMyTrade → parseTrade
}
result = this.sortBy (result, 'timestamp');
let symbol = (typeof market !== 'undefined') ? market['symbol'] : undefined;
return this.filterBySymbolSinceLimit (result, symbol, since, limit);
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let marketId = this.marketId (symbol);
let request = {
'symbol': marketId,
};
let response = await this.privatePostApiOrderOrderList (this.extend (request, params));
let market = this.markets_by_id[marketId];
let trades = response['data'];
let result = this.parseMyTrades (trades, market);
return result;
}
parseStatus (statusCode) {
if (statusCode === 0 || statusCode === 1) {
return 'open';
} else if (statusCode === 2) {
return 'closed';
} else if (statusCode === 3) {
return 'canceled';
}
return undefined;
}
async fetchOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let request = {
'symbol': this.marketId (symbol),
'trust_id': id,
};
let response = await this.privatePostApiOrderOrderInfo (this.extend (request, params));
let order = response['data'];
let timestamp = order['created'] * 1000;
let status = this.parseStatus (order['status']);
let result = {
'info': order,
'id': id,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': undefined,
'symbol': symbol,
'type': order['flag'],
'side': undefined,
'price': order['price'],
'cost': undefined,
'average': undefined,
'amount': order['number'],
'filled': order['numberdeal'],
'remaining': order['numberover'],
'status': status,
'fee': undefined,
};
return result;
}
parseOrder (order, market = undefined) {
let id = order['id'].toString ();
let timestamp = order['datetime'] * 1000;
let iso8601 = this.iso8601 (timestamp);
let symbol = market['symbol'];
let type = undefined;
let side = order['type'];
let price = order['price'];
let average = order['avg_price'];
let amount = order['amount'];
let remaining = order['amount_outstanding'];
let filled = amount - remaining;
let status = this.parseStatus (order['status']);
let cost = filled * price;
let fee = undefined;
let result = {
'info': order,
'id': id,
'timestamp': timestamp,
'datetime': iso8601,
'lastTradeTimestamp': undefined,
'symbol': symbol,
'type': type,
'side': side,
'price': price,
'cost': cost,
'average': average,
'amount': amount,
'filled': filled,
'remaining': remaining,
'status': status,
'fee': fee,
};
return result;
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let request = {};
let marketId = this.marketId (symbol);
request['type'] = 'open';
if (typeof symbol !== 'undefined') {
request['symbol'] = marketId;
}
let orders = [];
let response = await this.privatePostApiOrderTradeList (this.extend (request, params));
if ('data' in response) {
orders = response['data'];
}
let market = this.markets_by_id[marketId];
let results = this.parseOrders (orders, market, since, limit);
return results;
}
async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let request = {};
let marketId = this.marketId (symbol);
request['type'] = 'all';
if (typeof symbol !== 'undefined') {
request['symbol'] = marketId;
}
let orders = [];
let response = await this.privatePostApiOrderTradeList (this.extend (request, params));
if ('data' in response) {
orders = response['data'];
}
let market = this.markets_by_id[marketId];
let results = this.parseOrders (orders, market, since, limit);
return results;
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
let order = {
'symbol': this.marketId (symbol),
'type': side,
'price': price,
'number': amount,
};
let response = await this.privatePostApiOrderCoinTrust (this.extend (order, params));
let data = response['data'];
return {
'info': response,
'id': this.safeString (data, 'order_id'),
};
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let request = {};
if (typeof symbol !== 'undefined') {
request['symbol'] = symbol;
}
if (typeof id !== 'undefined') {
request['order_id'] = id;
}
let results = await this.privatePostApiOrderCancel (this.extend (request, params));
return results;
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let request = '/' + this.implodeParams (path, params);
let query = this.omit (params, this.extractParams (path));
if (method === 'GET') {
if (Object.keys (query).length)
request += '?' + this.urlencode (query);
}
let url = this.urls['api'] + request;
if (method === 'POST') {
let messageParts = [];
let keys = Object.keys (params);
let paramsKeys = keys.sort ();
for (let i = 0; i < paramsKeys.length; i++) {
let paramKey = paramsKeys[i];
let param = params[paramKey];
messageParts.push (this.encode (paramKey) + '=' + this.encodeURIComponent (param));
}
if (api === 'private') {
this.checkRequiredCredentials ();
messageParts.unshift ('api_key=' + this.encodeURIComponent (this.apiKey));
body = messageParts.join ('&');
let message = body + '&secret_key=' + this.secret;
let signedMessage = this.hash (message);
body = body + '&sign=' + signedMessage;
params['sign'] = signedMessage;
} else {
body = messageParts.join ('&');
}
headers = {};
headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
handleErrors (code, reason, url, method, headers, body) {
if (body[0] === '{' && (url.indexOf ('private') >= 0)) {
let response = JSON.parse (body);
let code = this.safeValue (response, 'code');
if (code !== 0) {
throw new ExchangeError (this.id + ' ' + body);
}
}
}
};
| bcex fetchBalance and currency codes
| js/bcex.js | bcex fetchBalance and currency codes | <ide><path>s/bcex.js
<ide> let keys = Object.keys (data);
<ide> let result = { };
<ide> for (let i = 0; i < keys.length; i++) {
<del> let currentKey = keys[i];
<del> let currentAmount = data[currentKey];
<del> let split = currentKey.split ('_');
<del> let id = split[0];
<del> let lockOrOver = split[1];
<del> let currency = this.commonCurrencyCode (id);
<del> if (!(currency in result)) {
<add> let key = keys[i];
<add> let amount = this.safeFloat (data, key);
<add> let parts = key.split ('_');
<add> let currencyId = parts[0];
<add> let lockOrOver = parts[1];
<add> let code = currencyId.toUpperCase ();
<add> if (currencyId in this.currencies_by_id) {
<add> code = this.currencies_by_id[currencyId]['code'];
<add> } else {
<add> code = this.commonCurrencyCode (code);
<add> }
<add> if (!(code in result)) {
<ide> let account = this.account ();
<del> result[currency] = account;
<add> result[code] = account;
<ide> }
<ide> if (lockOrOver === 'lock') {
<del> result[currency]['used'] = parseFloat (currentAmount);
<add> result[code]['used'] = parseFloat (amount);
<ide> } else {
<del> result[currency]['free'] = parseFloat (currentAmount);
<add> result[code]['free'] = parseFloat (amount);
<ide> }
<ide> }
<ide> keys = Object.keys (result);
<ide> for (let i = 0; i < keys.length; i++) {
<del> let currentKey = keys[i];
<del> let total = this.sum (result[currentKey]['used'], result[currentKey]['total']);
<del> result[currentKey]['total'] = total;
<add> let key = keys[i];
<add> let total = this.sum (result[key]['used'], result[key]['total']);
<add> result[key]['total'] = total;
<ide> }
<ide> result['info'] = data;
<ide> return this.parseBalance (result); |
|
JavaScript | mit | 3e03256c4e44b342603e6aea795d228044884ad3 | 0 | facebook/regenerator,facebook/regenerator,facebook/regenerator | /**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
(function(
// Reliable reference to the global object (i.e. window in browsers).
global,
// Dummy constructor that we use as the .constructor property for
// functions that return Generator objects.
GeneratorFunction,
// Undefined value, more compressible than void 0.
undefined
) {
var hasOwn = Object.prototype.hasOwnProperty;
if (global.wrapGenerator) {
return;
}
function wrapGenerator(innerFn, self, tryList) {
return new Generator(innerFn, self || null, tryList || []);
}
global.wrapGenerator = wrapGenerator;
if (typeof exports !== "undefined") {
exports.wrapGenerator = wrapGenerator;
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
wrapGenerator.mark = function(genFun) {
genFun.constructor = GeneratorFunction;
return genFun;
};
// Ensure isGeneratorFunction works when Function#name not supported.
if (GeneratorFunction.name !== "GeneratorFunction") {
GeneratorFunction.name = "GeneratorFunction";
}
wrapGenerator.isGeneratorFunction = function(genFun) {
var ctor = genFun && genFun.constructor;
return ctor ? GeneratorFunction.name === ctor.name : false;
};
function Generator(innerFn, self, tryList) {
var generator = this;
var context = new Context(tryList);
var state = GenStateSuspendedStart;
function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
throw new Error("Generator has already finished");
}
while (true) {
var delegate = context.delegate;
if (delegate) {
try {
var info = delegate.generator[method](arg);
// Delegate generator ran and handled its own exceptions so
// regardless of what the method was, we continue as if it is
// "next" with an undefined arg.
method = "next";
arg = undefined;
} catch (uncaught) {
context.delegate = null;
// Like returning generator.throw(uncaught), but without the
// overhead of an extra function call.
method = "throw";
arg = uncaught;
continue;
}
if (info.done) {
context[delegate.resultName] = info.value;
context.next = delegate.nextLoc;
} else {
state = GenStateSuspendedYield;
return info;
}
context.delegate = null;
}
if (method === "next") {
if (state === GenStateSuspendedStart &&
typeof arg !== "undefined") {
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
throw new TypeError(
"attempt to send " + JSON.stringify(arg) + " to newborn generator"
);
}
if (state === GenStateSuspendedYield) {
context.sent = arg;
} else {
delete context.sent;
}
} else if (method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw arg;
}
if (context.dispatchException(arg)) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
method = "next";
arg = undefined;
}
}
state = GenStateExecuting;
try {
var value = innerFn.call(self, context);
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
var info = {
value: value,
done: context.done
};
if (value === ContinueSentinel) {
if (context.delegate && method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
arg = undefined;
}
} else {
return info;
}
} catch (thrown) {
if (method === "next") {
context.dispatchException(thrown);
} else {
arg = thrown;
}
}
}
}
generator.next = invoke.bind(generator, "next");
generator.throw = invoke.bind(generator, "throw");
}
Generator.prototype.toString = function() {
return "[object Generator]";
};
function pushTryEntry(triple) {
var entry = { tryLoc: triple[0] };
if (1 in triple) {
entry.catchLoc = triple[1];
}
if (2 in triple) {
entry.finallyLoc = triple[2];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry, i) {
var record = entry.completion || {};
record.type = i === 0 ? "normal" : "return";
delete record.arg;
entry.completion = record;
}
function Context(tryList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryList.forEach(pushTryEntry, this);
this.reset();
}
Context.prototype = {
constructor: Context,
reset: function() {
this.prev = 0;
this.next = 0;
this.sent = undefined;
this.done = false;
this.delegate = null;
this.tryEntries.forEach(resetTryEntry);
// Pre-initialize at least 20 temporary variables to enable hidden
// class optimizations for simple generators.
for (var tempIndex = 0, tempName;
hasOwn.call(this, tempName = "t" + tempIndex) || tempIndex < 20;
++tempIndex) {
this[tempName] = null;
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
keys: function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
return !!caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
_findFinallyEntry: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") && (
entry.finallyLoc === finallyLoc ||
this.prev < entry.finallyLoc)) {
return entry;
}
}
},
abrupt: function(type, arg) {
var entry = this._findFinallyEntry();
var record = entry ? entry.completion : {};
record.type = type;
record.arg = arg;
if (entry) {
this.next = entry.finallyLoc;
} else {
this.complete(record);
}
return ContinueSentinel;
},
complete: function(record) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = record.arg;
this.next = "end";
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
var entry = this._findFinallyEntry(finallyLoc);
return this.complete(entry.completion);
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry, i);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(generator, resultName, nextLoc) {
this.delegate = {
generator: generator,
resultName: resultName,
nextLoc: nextLoc
};
return ContinueSentinel;
}
};
}).apply(this, Function("return [this, function GeneratorFunction(){}]")());
| runtime/dev.js | /**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
(function(
// Reliable reference to the global object (i.e. window in browsers).
global,
// Dummy constructor that we use as the .constructor property for
// functions that return Generator objects.
GeneratorFunction
) {
var hasOwn = Object.prototype.hasOwnProperty;
if (global.wrapGenerator) {
return;
}
function wrapGenerator(innerFn, self, tryList) {
return new Generator(innerFn, self || null, tryList || []);
}
global.wrapGenerator = wrapGenerator;
if (typeof exports !== "undefined") {
exports.wrapGenerator = wrapGenerator;
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
wrapGenerator.mark = function(genFun) {
genFun.constructor = GeneratorFunction;
return genFun;
};
// Ensure isGeneratorFunction works when Function#name not supported.
if (GeneratorFunction.name !== "GeneratorFunction") {
GeneratorFunction.name = "GeneratorFunction";
}
wrapGenerator.isGeneratorFunction = function(genFun) {
var ctor = genFun && genFun.constructor;
return ctor ? GeneratorFunction.name === ctor.name : false;
};
function Generator(innerFn, self, tryList) {
var generator = this;
var context = new Context(tryList);
var state = GenStateSuspendedStart;
function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
throw new Error("Generator has already finished");
}
while (true) {
var delegate = context.delegate;
if (delegate) {
try {
var info = delegate.generator[method](arg);
// Delegate generator ran and handled its own exceptions so
// regardless of what the method was, we continue as if it is
// "next" with an undefined arg.
method = "next";
arg = void 0;
} catch (uncaught) {
context.delegate = null;
// Like returning generator.throw(uncaught), but without the
// overhead of an extra function call.
method = "throw";
arg = uncaught;
continue;
}
if (info.done) {
context[delegate.resultName] = info.value;
context.next = delegate.nextLoc;
} else {
state = GenStateSuspendedYield;
return info;
}
context.delegate = null;
}
if (method === "next") {
if (state === GenStateSuspendedStart &&
typeof arg !== "undefined") {
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
throw new TypeError(
"attempt to send " + JSON.stringify(arg) + " to newborn generator"
);
}
if (state === GenStateSuspendedYield) {
context.sent = arg;
} else {
delete context.sent;
}
} else if (method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw arg;
}
if (context.dispatchException(arg)) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
method = "next";
arg = void 0;
}
}
state = GenStateExecuting;
try {
var value = innerFn.call(self, context);
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
var info = {
value: value,
done: context.done
};
if (value === ContinueSentinel) {
if (context.delegate && method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
arg = void 0;
}
} else {
return info;
}
} catch (thrown) {
if (method === "next") {
context.dispatchException(thrown);
} else {
arg = thrown;
}
}
}
}
generator.next = invoke.bind(generator, "next");
generator.throw = invoke.bind(generator, "throw");
}
Generator.prototype.toString = function() {
return "[object Generator]";
};
function pushTryEntry(triple) {
var entry = { tryLoc: triple[0] };
if (1 in triple) {
entry.catchLoc = triple[1];
}
if (2 in triple) {
entry.finallyLoc = triple[2];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry, i) {
var record = entry.completion || {};
record.type = i === 0 ? "normal" : "return";
delete record.arg;
entry.completion = record;
}
function Context(tryList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryList.forEach(pushTryEntry, this);
this.reset();
}
Context.prototype = {
constructor: Context,
reset: function() {
this.prev = 0;
this.next = 0;
this.sent = void 0;
this.done = false;
this.delegate = null;
this.tryEntries.forEach(resetTryEntry);
// Pre-initialize at least 20 temporary variables to enable hidden
// class optimizations for simple generators.
for (var tempIndex = 0, tempName;
hasOwn.call(this, tempName = "t" + tempIndex) || tempIndex < 20;
++tempIndex) {
this[tempName] = null;
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
keys: function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
return !!caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
_findFinallyEntry: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") && (
entry.finallyLoc === finallyLoc ||
this.prev < entry.finallyLoc)) {
return entry;
}
}
},
abrupt: function(type, arg) {
var entry = this._findFinallyEntry();
var record = entry ? entry.completion : {};
record.type = type;
record.arg = arg;
if (entry) {
this.next = entry.finallyLoc;
} else {
this.complete(record);
}
return ContinueSentinel;
},
complete: function(record) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = record.arg;
this.next = "end";
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
var entry = this._findFinallyEntry(finallyLoc);
return this.complete(entry.completion);
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry, i);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(generator, resultName, nextLoc) {
this.delegate = {
generator: generator,
resultName: resultName,
nextLoc: nextLoc
};
return ContinueSentinel;
}
};
}).apply(this, Function("return [this, function GeneratorFunction(){}]")());
| Use an undefined variable instead of the void 0 expression.
| runtime/dev.js | Use an undefined variable instead of the void 0 expression. | <ide><path>untime/dev.js
<ide>
<ide> // Dummy constructor that we use as the .constructor property for
<ide> // functions that return Generator objects.
<del> GeneratorFunction
<add> GeneratorFunction,
<add>
<add> // Undefined value, more compressible than void 0.
<add> undefined
<ide> ) {
<ide> var hasOwn = Object.prototype.hasOwnProperty;
<ide>
<ide> // regardless of what the method was, we continue as if it is
<ide> // "next" with an undefined arg.
<ide> method = "next";
<del> arg = void 0;
<add> arg = undefined;
<ide>
<ide> } catch (uncaught) {
<ide> context.delegate = null;
<ide> // If the dispatched exception was caught by a catch block,
<ide> // then let that catch block handle the exception normally.
<ide> method = "next";
<del> arg = void 0;
<add> arg = undefined;
<ide> }
<ide> }
<ide>
<ide> if (context.delegate && method === "next") {
<ide> // Deliberately forget the last sent value so that we don't
<ide> // accidentally pass it on to the delegate.
<del> arg = void 0;
<add> arg = undefined;
<ide> }
<ide> } else {
<ide> return info;
<ide> reset: function() {
<ide> this.prev = 0;
<ide> this.next = 0;
<del> this.sent = void 0;
<add> this.sent = undefined;
<ide> this.done = false;
<ide> this.delegate = null;
<ide> |
|
JavaScript | mit | 9fe45f545b8f9e55201955284fbb4acbed3981b1 | 0 | spatools/ts2jsdoc,spatools/ts2jsdoc,spatools/ts2jsdoc | "use strict";
module.exports = function (grunt) {
// Load grunt tasks automatically
require("jit-grunt")(grunt, {
nugetpack: "grunt-nuget",
nugetpush: "grunt-nuget",
buildcontrol: "grunt-build-control"
});
require("time-grunt")(grunt); // Time how long tasks take. Can help when optimizing build times
var pkg = require("./package.json");
grunt.initConfig({
pkg: pkg,
// Configurable paths
paths: {
bin: "bin",
lib: "lib",
tmpl: "template",
build: "build",
dist: "dist",
all: "{<%= paths.bin %>,<%= paths.lib %>,<%= paths.tmpl %>}",
defs: "typings/_definitions.d.ts",
temp: "temp"
},
typescript: {
options: {
target: "es5",
module: "commonjs",
sourceMap: true,
declaration: false,
removeComments: false
},
src: {
src: ["<%= paths.defs %>", "<%= paths.all %>/**/*.ts", "./*.ts"]
},
dist: {
src: ["<%= typescript.src.src %>"],
options: {
sourceMap: false
}
}
},
jsdoc : {
typescript : {
src: ["node_modules/typescript/bin/typescript.d.ts"],
dest: "<%= paths.dist %>/typescript",
options: { configure: "<%= paths.build %>/conf.typescript.json" }
},
lib : {
src: ["node_modules/typescript/bin/lib.d.ts"],
dest: "<%= paths.dist %>/lib",
options: { configure: "<%= paths.build %>/conf.lib.json" }
},
node : {
src: ["typings/node/node.d.ts"],
dest: "<%= paths.dist %>/node",
options: { configure: "<%= paths.build %>/conf.node.json" }
}
},
tslint: {
options: {
configuration: grunt.file.readJSON("tslint.json")
},
src: {
src: ["<%= paths.all %>/**/*.ts", "./*.ts"]
}
},
clean: {
src: [
"<%= paths.all %>/**/*.{d.ts,js,js.map}",
"./*.{d.ts,js,js.map}",
"!<%= paths.tmpl %>/static/**",
"!./Gruntfile.js",
],
dist: "<%= paths.dist %>",
temp: "<%= paths.temp %>"
},
connect: {
options: {
port: "8080",
livereload: 56765
},
dist: {
options: {
base: "<%= paths.dist %>"
}
}
},
watch: {
tslint: { files: ["<%= tslint.src.src %>"], tasks: ["tslint:src"] },
typescript: { files: ["<%= typescript.src.src %>"], tasks: ["typescript:src"] },
gruntfile: { files: ["Gruntfile.js"] },
livereload: {
options: {
livereload: "<%= connect.options.livereload %>"
},
files: ["<%= paths.dist %>/**/*.{js,html,css}"]
}
},
buildcontrol: {
docs: {
options: {
dir: "<%= paths.dist %>",
commit: true,
push: true,
branch: "gh-pages",
remote: "[email protected]:spatools/ts2jsdoc.git",
message: "Built documentations %sourceName% from commit %sourceCommit% on branch %sourceBranch%"
}
}
}
});
grunt.registerTask("dev", ["tslint:src", "clean:src", "typescript:src"]);
grunt.registerTask("build", ["tslint:src", "clean:src", "typescript:dist"]);
grunt.registerTask("doc", ["clean:dist", "jsdoc:typescript", "jsdoc:node"]);
grunt.registerTask("serve", ["dev", "doc", "connect:dist", "watch"]);
grunt.registerTask("publish", ["build", "doc", "buildcontrol:docs"]);
grunt.registerTask("default", ["build"]);
}; | Gruntfile.js | "use strict";
module.exports = function (grunt) {
// Load grunt tasks automatically
require("jit-grunt")(grunt, {
nugetpack: "grunt-nuget",
nugetpush: "grunt-nuget",
buildcontrol: "grunt-build-control"
});
require("time-grunt")(grunt); // Time how long tasks take. Can help when optimizing build times
var pkg = require("./package.json");
grunt.initConfig({
pkg: pkg,
// Configurable paths
paths: {
bin: "bin",
lib: "lib",
tmpl: "template",
build: "build",
dist: "dist",
all: "{<%= paths.bin %>,<%= paths.lib %>,<%= paths.tmpl %>}",
defs: "typings/_definitions.d.ts",
temp: "temp"
},
typescript: {
options: {
target: "es5",
module: "commonjs",
sourceMap: true,
declaration: false,
removeComments: false
},
src: {
src: ["<%= paths.defs %>", "<%= paths.all %>/**/*.ts", "./*.ts"]
},
dist: {
src: ["<%= typescript.src.src %>"],
options: {
sourceMap: false
}
}
},
jsdoc : {
typescript : {
src: ["node_modules/typescript/bin/typescript.d.ts"],
dest: "<%= paths.dist %>/typescript",
options: { configure: "<%= paths.build %>/conf.typescript.json" }
},
lib : {
src: ["node_modules/typescript/bin/lib.d.ts"],
dest: "<%= paths.dist %>/lib",
options: { configure: "<%= paths.build %>/conf.lib.json" }
},
node : {
src: ["typings/node/node.d.ts"],
dest: "<%= paths.dist %>/node",
options: { configure: "<%= paths.build %>/conf.node.json" }
}
},
tslint: {
options: {
configuration: grunt.file.readJSON("tslint.json")
},
src: {
src: ["<%= paths.all %>/**/*.ts", "./*.ts"]
}
},
clean: {
src: [
"<%= paths.all %>/**/*.{d.ts,js,js.map}",
"./*.{d.ts,js,js.map}",
"!<%= paths.tmpl %>/static/**",
"!./Gruntfile.js",
],
dist: "<%= paths.dist %>",
temp: "<%= paths.temp %>"
},
connect: {
options: {
port: "8080",
livereload: 56765
},
dist: {
options: {
base: "<%= paths.dist %>"
}
}
},
watch: {
tslint: { files: ["<%= tslint.src.src %>"], tasks: ["tslint:src"] },
typescript: { files: ["<%= typescript.src.src %>"], tasks: ["typescript:src"] },
gruntfile: { files: ["Gruntfile.js"] },
livereload: {
options: {
livereload: "<%= connect.options.livereload %>"
},
files: ["<%= paths.dist %>/**/*.{js,html,css}"]
}
},
buildcontrol: {
docs: {
options: {
dir: "<%= paths.dist %>",
commit: true,
push: true,
branch: "gh-pages",
message: "Built documentations %sourceName% from commit %sourceCommit% on branch %sourceBranch%"
}
}
}
});
grunt.registerTask("dev", ["tslint:src", "clean:src", "typescript:src"]);
grunt.registerTask("build", ["tslint:src", "clean:src", "typescript:dist"]);
grunt.registerTask("doc", ["clean:dist", "jsdoc:typescript", "jsdoc:node"]);
grunt.registerTask("serve", ["dev", "doc", "connect:dist", "watch"]);
grunt.registerTask("publish", ["build", "doc", "buildcontrol:docs"]);
grunt.registerTask("default", ["build"]);
}; | Fix issue in buildcontrol task
| Gruntfile.js | Fix issue in buildcontrol task | <ide><path>runtfile.js
<ide> commit: true,
<ide> push: true,
<ide> branch: "gh-pages",
<add> remote: "[email protected]:spatools/ts2jsdoc.git",
<ide> message: "Built documentations %sourceName% from commit %sourceCommit% on branch %sourceBranch%"
<ide> }
<ide> } |
|
Java | mit | 4bdcd1a2c37d1ccf38ac32c83671851637055efb | 0 | GluuFederation/oxTrust,GluuFederation/oxTrust,GluuFederation/oxTrust,GluuFederation/oxTrust,GluuFederation/oxTrust | /*
* oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxtrust.action;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.inject.Inject;
import javax.inject.Named;
import org.gluu.jsf2.message.FacesMessages;
import org.gluu.jsf2.service.ConversationService;
import org.gluu.model.AuthenticationScriptUsageType;
import org.gluu.model.ProgrammingLanguage;
import org.gluu.model.ScriptLocationType;
import org.gluu.model.SimpleCustomProperty;
import org.gluu.model.SimpleExtendedCustomProperty;
import org.gluu.model.SimpleProperty;
import org.gluu.model.custom.script.CustomScriptType;
import org.gluu.model.custom.script.model.CustomScript;
import org.gluu.model.custom.script.model.auth.AuthenticationCustomScript;
import org.gluu.oxtrust.ldap.service.ConfigurationService;
import org.gluu.oxtrust.ldap.service.OrganizationService;
import org.gluu.oxtrust.ldap.service.SamlAcrService;
import org.gluu.oxtrust.model.SimpleCustomPropertiesListModel;
import org.gluu.oxtrust.model.SimplePropertiesListModel;
import org.gluu.oxtrust.util.OxTrustConstants;
import org.gluu.service.custom.script.AbstractCustomScriptService;
import org.gluu.service.security.Secure;
import org.gluu.util.INumGenerator;
import org.gluu.util.OxConstants;
import org.gluu.util.StringHelper;
import org.slf4j.Logger;
/**
* Add/Modify custom script configurations
*
* @author Yuriy Movchan Date: 12/29/2014
*/
@Named("manageCustomScriptAction")
@ConversationScoped
@Secure("#{permissionService.hasPermission('configuration', 'access')}")
public class ManageCustomScriptAction
implements SimplePropertiesListModel, SimpleCustomPropertiesListModel, Serializable {
private static final long serialVersionUID = -3823022039248381963L;
private static final Pattern NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9_\\-\\:\\/\\.]+$");
@Inject
private Logger log;
@Inject
private FacesMessages facesMessages;
@Inject
private ConversationService conversationService;
@Inject
private OrganizationService organizationService;
@Inject
private ConfigurationService configurationService;
@Inject
private AbstractCustomScriptService customScriptService;
private Map<CustomScriptType, List<CustomScript>> customScriptsByTypes;
private boolean initialized;
private static List<String> allAcrs = new ArrayList<>();
@Inject
private SamlAcrService samlAcrService;
public String modify() {
if (this.initialized) {
return OxTrustConstants.RESULT_SUCCESS;
}
CustomScriptType[] allowedCustomScriptTypes = this.configurationService.getCustomScriptTypes();
this.customScriptsByTypes = new HashMap<CustomScriptType, List<CustomScript>>();
for (CustomScriptType customScriptType : allowedCustomScriptTypes) {
this.customScriptsByTypes.put(customScriptType, new ArrayList<CustomScript>());
}
try {
List<CustomScript> customScripts = customScriptService
.findCustomScripts(Arrays.asList(allowedCustomScriptTypes));
for (CustomScript customScript : customScripts) {
CustomScriptType customScriptType = customScript.getScriptType();
List<CustomScript> customScriptsByType = this.customScriptsByTypes.get(customScriptType);
CustomScript typedCustomScript = customScript;
if (CustomScriptType.PERSON_AUTHENTICATION == customScriptType) {
typedCustomScript = new AuthenticationCustomScript(customScript);
}
if (typedCustomScript.getConfigurationProperties() == null) {
typedCustomScript.setConfigurationProperties(new ArrayList<SimpleExtendedCustomProperty>());
}
if (typedCustomScript.getModuleProperties() == null) {
typedCustomScript.setModuleProperties(new ArrayList<SimpleCustomProperty>());
}
customScriptsByType.add(typedCustomScript);
}
} catch (Exception ex) {
log.error("Failed to load custom scripts ", ex);
facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to load custom scripts");
conversationService.endConversation();
return OxTrustConstants.RESULT_FAILURE;
}
this.initialized = true;
return OxTrustConstants.RESULT_SUCCESS;
}
public String save() {
try {
List<CustomScript> oldCustomScripts = customScriptService
.findCustomScripts(Arrays.asList(this.configurationService.getCustomScriptTypes()), "dn", "inum");
List<String> updatedInums = new ArrayList<String>();
for (Entry<CustomScriptType, List<CustomScript>> customScriptsByType : this.customScriptsByTypes
.entrySet()) {
List<CustomScript> customScripts = customScriptsByType.getValue();
for (CustomScript customScript : customScripts) {
String configId = customScript.getName();
if (StringHelper.equalsIgnoreCase(configId, OxConstants.SCRIPT_TYPE_INTERNAL_RESERVED_NAME)) {
facesMessages.add(FacesMessage.SEVERITY_ERROR, "'%s' is reserved script name", configId);
return OxTrustConstants.RESULT_FAILURE;
}
boolean nameValidation = NAME_PATTERN.matcher(customScript.getName()).matches();
if (!nameValidation) {
facesMessages.add(FacesMessage.SEVERITY_ERROR,
"'%s' is invalid script name. Only alphabetic, numeric and underscore characters are allowed in Script Name",
configId);
return OxTrustConstants.RESULT_FAILURE;
}
customScript.setRevision(customScript.getRevision() + 1);
boolean update = true;
String dn = customScript.getDn();
String customScriptId = customScript.getInum();
if (StringHelper.isEmpty(dn)) {
customScriptId = INumGenerator.generate(2);
dn = customScriptService.buildDn(customScriptId);
customScript.setDn(dn);
customScript.setInum(customScriptId);
update = false;
}
;
customScript.setDn(dn);
customScript.setInum(customScriptId);
if (ScriptLocationType.LDAP == customScript.getLocationType()) {
customScript.removeModuleProperty(CustomScript.LOCATION_PATH_MODEL_PROPERTY);
}
if ((customScript.getConfigurationProperties() != null)
&& (customScript.getConfigurationProperties().size() == 0)) {
customScript.setConfigurationProperties(null);
}
if ((customScript.getConfigurationProperties() != null)
&& (customScript.getModuleProperties().size() == 0)) {
customScript.setModuleProperties(null);
}
updatedInums.add(customScriptId);
if (update) {
customScriptService.update(customScript);
} else {
customScriptService.add(customScript);
}
}
}
// Remove removed scripts
for (CustomScript oldCustomScript : oldCustomScripts) {
if (!updatedInums.contains(oldCustomScript.getInum())) {
customScriptService.remove(oldCustomScript);
}
}
} catch (Exception ex) {
log.error("Failed to update custom scripts", ex);
facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to update custom script configuration");
return OxTrustConstants.RESULT_FAILURE;
}
facesMessages.add(FacesMessage.SEVERITY_INFO, "Custom script configuration updated successfully");
return OxTrustConstants.RESULT_SUCCESS;
}
public String cancel() throws Exception {
facesMessages.add(FacesMessage.SEVERITY_INFO, "Custom script configuration not updated");
conversationService.endConversation();
return OxTrustConstants.RESULT_SUCCESS;
}
public Map<CustomScriptType, List<CustomScript>> getCustomScriptsByTypes() {
return this.customScriptsByTypes;
}
public String getId(Object obj) {
return "c" + System.identityHashCode(obj) + "Id";
}
public void addCustomScript(CustomScriptType scriptType) {
List<CustomScript> customScriptsByType = this.customScriptsByTypes.get(scriptType);
CustomScript customScript;
if (CustomScriptType.PERSON_AUTHENTICATION == scriptType) {
AuthenticationCustomScript authenticationCustomScript = new AuthenticationCustomScript();
authenticationCustomScript.setModuleProperties(new ArrayList<SimpleCustomProperty>());
authenticationCustomScript.setUsageType(AuthenticationScriptUsageType.INTERACTIVE);
customScript = authenticationCustomScript;
} else {
customScript = new CustomScript();
customScript.setModuleProperties(new ArrayList<SimpleCustomProperty>());
}
customScript.setLocationType(ScriptLocationType.LDAP);
customScript.setScriptType(scriptType);
customScript.setProgrammingLanguage(ProgrammingLanguage.PYTHON);
customScript.setConfigurationProperties(new ArrayList<SimpleExtendedCustomProperty>());
customScriptsByType.add(customScript);
}
public void removeCustomScript(CustomScript removeCustomScript) {
for (Entry<CustomScriptType, List<CustomScript>> customScriptsByType : this.customScriptsByTypes.entrySet()) {
List<CustomScript> customScripts = customScriptsByType.getValue();
for (Iterator<CustomScript> iterator = customScripts.iterator(); iterator.hasNext();) {
CustomScript customScript = iterator.next();
if (System.identityHashCode(removeCustomScript) == System.identityHashCode(customScript)) {
iterator.remove();
return;
}
}
}
}
@Override
public void addItemToSimpleProperties(List<SimpleProperty> simpleProperties) {
if (simpleProperties != null) {
simpleProperties.add(new SimpleProperty(""));
}
}
@Override
public void removeItemFromSimpleProperties(List<SimpleProperty> simpleProperties, SimpleProperty simpleProperty) {
if (simpleProperties != null) {
simpleProperties.remove(simpleProperty);
}
}
@Override
public void addItemToSimpleCustomProperties(List<SimpleCustomProperty> simpleCustomProperties) {
if (simpleCustomProperties != null) {
simpleCustomProperties.add(new SimpleExtendedCustomProperty("", ""));
}
}
@Override
public void removeItemFromSimpleCustomProperties(List<SimpleCustomProperty> simpleCustomProperties,
SimpleCustomProperty simpleCustomProperty) {
if (simpleCustomProperties != null) {
simpleCustomProperties.remove(simpleCustomProperty);
}
}
public boolean hasCustomScriptError(CustomScript customScript) {
String error = getCustomScriptError(customScript);
return error != null;
}
public String getCustomScriptError(CustomScript customScript) {
if ((customScript == null) || (customScript.getDn() == null)) {
return null;
}
CustomScript currentScript = customScriptService.getCustomScriptByDn(customScript.getDn(), "oxScriptError");
if ((currentScript != null) && (currentScript.getScriptError() != null)) {
return currentScript.getScriptError().getStackTrace();
}
return null;
}
public boolean isInitialized() {
return initialized;
}
public List<String> getAvailableAcrs(String scriptName) {
return new ArrayList<>(cleanAcrs(scriptName));
}
public void initAcrs() {
try {
allAcrs.clear();
allAcrs = Stream.of(samlAcrService.getAll()).map(e -> e.getClassRef()).collect(Collectors.toList());
} catch (Exception e) {
log.info("", e);
}
}
public String getDisplayName(String value) {
return value;
}
public boolean isPersonScript(CustomScript script) {
if (script.getScriptType() != null) {
return script.getScriptType().getValue()
.equalsIgnoreCase(CustomScriptType.PERSON_AUTHENTICATION.getValue());
}
return false;
}
private Set<String> cleanAcrs(String name) {
Set<String> result = new HashSet<>();
result.addAll(allAcrs);
List<CustomScript> scripts = customScriptService
.findCustomScripts(Arrays.asList(CustomScriptType.PERSON_AUTHENTICATION));
for (CustomScript customScript : scripts) {
if (null == customScript.getAliases())
customScript.setAliases(new ArrayList<>());
if (customScript.getName() != null) {
if (!customScript.getName().equals(name)) {
List<String> existing = customScript.getAliases();
if (existing != null && existing.size() > 0) {
for (String value : existing) {
result.remove(value);
}
}
}
}
}
return result;
}
public void resetAcrs(CustomScript script) {
script.setAliases(new ArrayList<>());
}
}
| server/src/main/java/org/gluu/oxtrust/action/ManageCustomScriptAction.java | /*
* oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxtrust.action;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.inject.Inject;
import javax.inject.Named;
import org.gluu.jsf2.message.FacesMessages;
import org.gluu.jsf2.service.ConversationService;
import org.gluu.model.AuthenticationScriptUsageType;
import org.gluu.model.ProgrammingLanguage;
import org.gluu.model.ScriptLocationType;
import org.gluu.model.SimpleCustomProperty;
import org.gluu.model.SimpleExtendedCustomProperty;
import org.gluu.model.SimpleProperty;
import org.gluu.model.custom.script.CustomScriptType;
import org.gluu.model.custom.script.model.CustomScript;
import org.gluu.model.custom.script.model.auth.AuthenticationCustomScript;
import org.gluu.oxtrust.ldap.service.ConfigurationService;
import org.gluu.oxtrust.ldap.service.OrganizationService;
import org.gluu.oxtrust.ldap.service.SamlAcrService;
import org.gluu.oxtrust.model.SimpleCustomPropertiesListModel;
import org.gluu.oxtrust.model.SimplePropertiesListModel;
import org.gluu.oxtrust.util.OxTrustConstants;
import org.gluu.service.custom.script.AbstractCustomScriptService;
import org.gluu.service.security.Secure;
import org.gluu.util.INumGenerator;
import org.gluu.util.OxConstants;
import org.gluu.util.StringHelper;
import org.slf4j.Logger;
/**
* Add/Modify custom script configurations
*
* @author Yuriy Movchan Date: 12/29/2014
*/
@Named("manageCustomScriptAction")
@ConversationScoped
@Secure("#{permissionService.hasPermission('configuration', 'access')}")
public class ManageCustomScriptAction
implements SimplePropertiesListModel, SimpleCustomPropertiesListModel, Serializable {
private static final long serialVersionUID = -3823022039248381963L;
private static final Pattern NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9_\\-\\:\\/\\.]+$");
@Inject
private Logger log;
@Inject
private FacesMessages facesMessages;
@Inject
private ConversationService conversationService;
@Inject
private OrganizationService organizationService;
@Inject
private ConfigurationService configurationService;
@Inject
private AbstractCustomScriptService customScriptService;
private Map<CustomScriptType, List<CustomScript>> customScriptsByTypes;
private boolean initialized;
private static List<String> allAcrs = new ArrayList<>();
@Inject
private SamlAcrService samlAcrService;
public String modify() {
if (this.initialized) {
return OxTrustConstants.RESULT_SUCCESS;
}
CustomScriptType[] allowedCustomScriptTypes = this.configurationService.getCustomScriptTypes();
this.customScriptsByTypes = new HashMap<CustomScriptType, List<CustomScript>>();
for (CustomScriptType customScriptType : allowedCustomScriptTypes) {
this.customScriptsByTypes.put(customScriptType, new ArrayList<CustomScript>());
}
try {
List<CustomScript> customScripts = customScriptService
.findCustomScripts(Arrays.asList(allowedCustomScriptTypes));
for (CustomScript customScript : customScripts) {
CustomScriptType customScriptType = customScript.getScriptType();
List<CustomScript> customScriptsByType = this.customScriptsByTypes.get(customScriptType);
CustomScript typedCustomScript = customScript;
if (CustomScriptType.PERSON_AUTHENTICATION == customScriptType) {
typedCustomScript = new AuthenticationCustomScript(customScript);
}
if (typedCustomScript.getConfigurationProperties() == null) {
typedCustomScript.setConfigurationProperties(new ArrayList<SimpleExtendedCustomProperty>());
}
if (typedCustomScript.getModuleProperties() == null) {
typedCustomScript.setModuleProperties(new ArrayList<SimpleCustomProperty>());
}
customScriptsByType.add(typedCustomScript);
}
} catch (Exception ex) {
log.error("Failed to load custom scripts ", ex);
facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to load custom scripts");
conversationService.endConversation();
return OxTrustConstants.RESULT_FAILURE;
}
this.initialized = true;
return OxTrustConstants.RESULT_SUCCESS;
}
public String save() {
try {
List<CustomScript> oldCustomScripts = customScriptService
.findCustomScripts(Arrays.asList(this.configurationService.getCustomScriptTypes()), "dn", "inum");
List<String> updatedInums = new ArrayList<String>();
for (Entry<CustomScriptType, List<CustomScript>> customScriptsByType : this.customScriptsByTypes
.entrySet()) {
List<CustomScript> customScripts = customScriptsByType.getValue();
for (CustomScript customScript : customScripts) {
String configId = customScript.getName();
if (StringHelper.equalsIgnoreCase(configId, OxConstants.SCRIPT_TYPE_INTERNAL_RESERVED_NAME)) {
facesMessages.add(FacesMessage.SEVERITY_ERROR, "'%s' is reserved script name", configId);
return OxTrustConstants.RESULT_FAILURE;
}
boolean nameValidation = NAME_PATTERN.matcher(customScript.getName()).matches();
if (!nameValidation) {
facesMessages.add(FacesMessage.SEVERITY_ERROR,
"'%s' is invalid script name. Only alphabetic, numeric and underscore characters are allowed in Script Name",
configId);
return OxTrustConstants.RESULT_FAILURE;
}
customScript.setRevision(customScript.getRevision() + 1);
boolean update = true;
String dn = customScript.getDn();
String customScriptId = customScript.getInum();
if (StringHelper.isEmpty(dn)) {
String basedInum = organizationService.getDnForOrganization();
customScriptId = basedInum + "!" + INumGenerator.generate(2);
dn = customScriptService.buildDn(customScriptId);
customScript.setDn(dn);
customScript.setInum(customScriptId);
update = false;
}
;
customScript.setDn(dn);
customScript.setInum(customScriptId);
if (ScriptLocationType.LDAP == customScript.getLocationType()) {
customScript.removeModuleProperty(CustomScript.LOCATION_PATH_MODEL_PROPERTY);
}
if ((customScript.getConfigurationProperties() != null)
&& (customScript.getConfigurationProperties().size() == 0)) {
customScript.setConfigurationProperties(null);
}
if ((customScript.getConfigurationProperties() != null)
&& (customScript.getModuleProperties().size() == 0)) {
customScript.setModuleProperties(null);
}
updatedInums.add(customScriptId);
if (update) {
customScriptService.update(customScript);
} else {
customScriptService.add(customScript);
}
}
}
// Remove removed scripts
for (CustomScript oldCustomScript : oldCustomScripts) {
if (!updatedInums.contains(oldCustomScript.getInum())) {
customScriptService.remove(oldCustomScript);
}
}
} catch (Exception ex) {
log.error("Failed to update custom scripts", ex);
facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to update custom script configuration");
return OxTrustConstants.RESULT_FAILURE;
}
facesMessages.add(FacesMessage.SEVERITY_INFO, "Custom script configuration updated successfully");
return OxTrustConstants.RESULT_SUCCESS;
}
public String cancel() throws Exception {
facesMessages.add(FacesMessage.SEVERITY_INFO, "Custom script configuration not updated");
conversationService.endConversation();
return OxTrustConstants.RESULT_SUCCESS;
}
public Map<CustomScriptType, List<CustomScript>> getCustomScriptsByTypes() {
return this.customScriptsByTypes;
}
public String getId(Object obj) {
return "c" + System.identityHashCode(obj) + "Id";
}
public void addCustomScript(CustomScriptType scriptType) {
List<CustomScript> customScriptsByType = this.customScriptsByTypes.get(scriptType);
CustomScript customScript;
if (CustomScriptType.PERSON_AUTHENTICATION == scriptType) {
AuthenticationCustomScript authenticationCustomScript = new AuthenticationCustomScript();
authenticationCustomScript.setModuleProperties(new ArrayList<SimpleCustomProperty>());
authenticationCustomScript.setUsageType(AuthenticationScriptUsageType.INTERACTIVE);
customScript = authenticationCustomScript;
} else {
customScript = new CustomScript();
customScript.setModuleProperties(new ArrayList<SimpleCustomProperty>());
}
customScript.setLocationType(ScriptLocationType.LDAP);
customScript.setScriptType(scriptType);
customScript.setProgrammingLanguage(ProgrammingLanguage.PYTHON);
customScript.setConfigurationProperties(new ArrayList<SimpleExtendedCustomProperty>());
customScriptsByType.add(customScript);
}
public void removeCustomScript(CustomScript removeCustomScript) {
for (Entry<CustomScriptType, List<CustomScript>> customScriptsByType : this.customScriptsByTypes.entrySet()) {
List<CustomScript> customScripts = customScriptsByType.getValue();
for (Iterator<CustomScript> iterator = customScripts.iterator(); iterator.hasNext();) {
CustomScript customScript = iterator.next();
if (System.identityHashCode(removeCustomScript) == System.identityHashCode(customScript)) {
iterator.remove();
return;
}
}
}
}
@Override
public void addItemToSimpleProperties(List<SimpleProperty> simpleProperties) {
if (simpleProperties != null) {
simpleProperties.add(new SimpleProperty(""));
}
}
@Override
public void removeItemFromSimpleProperties(List<SimpleProperty> simpleProperties, SimpleProperty simpleProperty) {
if (simpleProperties != null) {
simpleProperties.remove(simpleProperty);
}
}
@Override
public void addItemToSimpleCustomProperties(List<SimpleCustomProperty> simpleCustomProperties) {
if (simpleCustomProperties != null) {
simpleCustomProperties.add(new SimpleExtendedCustomProperty("", ""));
}
}
@Override
public void removeItemFromSimpleCustomProperties(List<SimpleCustomProperty> simpleCustomProperties,
SimpleCustomProperty simpleCustomProperty) {
if (simpleCustomProperties != null) {
simpleCustomProperties.remove(simpleCustomProperty);
}
}
public boolean hasCustomScriptError(CustomScript customScript) {
String error = getCustomScriptError(customScript);
return error != null;
}
public String getCustomScriptError(CustomScript customScript) {
if ((customScript == null) || (customScript.getDn() == null)) {
return null;
}
CustomScript currentScript = customScriptService.getCustomScriptByDn(customScript.getDn(), "oxScriptError");
if ((currentScript != null) && (currentScript.getScriptError() != null)) {
return currentScript.getScriptError().getStackTrace();
}
return null;
}
public boolean isInitialized() {
return initialized;
}
public List<String> getAvailableAcrs(String scriptName) {
return new ArrayList<>(cleanAcrs(scriptName));
}
public void initAcrs() {
try {
allAcrs.clear();
allAcrs = Stream.of(samlAcrService.getAll()).map(e -> e.getClassRef()).collect(Collectors.toList());
} catch (Exception e) {
log.info("", e);
}
}
public String getDisplayName(String value) {
return value;
}
public boolean isPersonScript(CustomScript script) {
if (script.getScriptType() != null) {
return script.getScriptType().getValue()
.equalsIgnoreCase(CustomScriptType.PERSON_AUTHENTICATION.getValue());
}
return false;
}
private Set<String> cleanAcrs(String name) {
Set<String> result = new HashSet<>();
result.addAll(allAcrs);
List<CustomScript> scripts = customScriptService
.findCustomScripts(Arrays.asList(CustomScriptType.PERSON_AUTHENTICATION));
for (CustomScript customScript : scripts) {
if (null == customScript.getAliases())
customScript.setAliases(new ArrayList<>());
if (customScript.getName() != null) {
if (!customScript.getName().equals(name)) {
List<String> existing = customScript.getAliases();
if (existing != null && existing.size() > 0) {
for (String value : existing) {
result.remove(value);
}
}
}
}
}
return result;
}
public void resetAcrs(CustomScript script) {
script.setAliases(new ArrayList<>());
}
}
| New CouchBase script INUMs have "o=gluu!" prefix #1879 | server/src/main/java/org/gluu/oxtrust/action/ManageCustomScriptAction.java | New CouchBase script INUMs have "o=gluu!" prefix #1879 | <ide><path>erver/src/main/java/org/gluu/oxtrust/action/ManageCustomScriptAction.java
<ide> String dn = customScript.getDn();
<ide> String customScriptId = customScript.getInum();
<ide> if (StringHelper.isEmpty(dn)) {
<del> String basedInum = organizationService.getDnForOrganization();
<del> customScriptId = basedInum + "!" + INumGenerator.generate(2);
<add> customScriptId = INumGenerator.generate(2);
<ide> dn = customScriptService.buildDn(customScriptId);
<ide>
<ide> customScript.setDn(dn); |
|
Java | apache-2.0 | 35d75b5be3a024a0bf80b228c351d1817efb80b5 | 0 | nickman/heliosutils,nickman/heliosutils | /**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package com.heliosapm.utils.file;
import java.io.File;
import java.io.FileFilter;
import java.net.URL;
import java.util.LinkedHashSet;
import java.util.Set;
import com.heliosapm.utils.url.URLHelper;
/**
* <p>Title: FileFinder</p>
* <p>Description: Scans a given directory for files matching a file filter</p>
* <p>Company: Helios Development Group LLC</p>
* @author Whitehead (nwhitehead AT heliosdev DOT org)
* <p><code>com.heliosapm.utils.file.FileFinder</code></p>
*/
public class FileFinder {
public static final File[] EMPTY_FILE_ARR = {};
public static final URL[] EMPTY_URL_ARR = {};
private static final FileFilter DEFAULT_FILTER = new NOFILTER();
protected FileFilter filter = DEFAULT_FILTER;
protected int maxLevel = Integer.MAX_VALUE;
protected int maxFiles = 1024;
protected int actualLevel = 0;
protected int actualCount = 0;
protected final Set<File> foundFiles = new LinkedHashSet<File>();
protected final Set<File> dirsToSearch = new LinkedHashSet<File>();
private FileFinder(final String...dirs) {
addSearchDir(dirs);
}
FileFinder setFilter(final FileFilter filter) {
this.filter = filter;
return this;
}
public static FileFinder newFileFinder(final String...dirsToSearch) {
return new FileFinder(dirsToSearch);
}
public FileFinder addSearchDir(final String...dirs) {
for(String s : dirs) {
if(s==null || s.trim().isEmpty()) continue;
File f = new File(s.trim());
if(f.exists() && f.isDirectory()) {
dirsToSearch.add(f);
}
}
return this;
}
public FileFinder addSearchDir(final File...dirs) {
for(File f : dirs) {
if(f==null) continue;
if(f.exists() && f.isDirectory()) {
dirsToSearch.add(f);
}
}
return this;
}
public FileFilterBuilder filterBuilder() {
return FileFilterBuilder.newBuilder(this);
}
public FileFinder maxDepth(final int depth) {
if(depth < 0) throw new IllegalArgumentException("Invalid maximum directory depth [" + depth + "]. Must be >= 0");
this.maxLevel = depth;
return this;
}
public FileFinder maxFiles(final int maxFiles) {
if(maxFiles < 0) throw new IllegalArgumentException("Invalid maximum file matches [" + maxFiles + "]. Must be >= 0");
this.maxFiles = maxFiles;
return this;
}
public File[] find() {
foundFiles.clear();
actualCount = 0;
actualLevel = 0;
if(dirsToSearch.isEmpty() || maxFiles==0) return EMPTY_FILE_ARR;
for(File dir: dirsToSearch) {
doIt(dir);
actualLevel = 0;
if(actualCount==maxFiles) break;
}
return foundFiles.toArray(new File[actualCount]);
}
public URL[] findAsURLs() {
final File[] files = find();
if(files.length==0) return EMPTY_URL_ARR;
final URL[] urls = new URL[files.length];
for(int i = 0; i <urls.length; i++) {
urls[i] = URLHelper.toURL(files[i]);
}
return urls;
}
protected void doIt(final File dir) {
if(actualCount==maxFiles) return;
for(File f: dir.listFiles()) {
if(actualCount==maxFiles) return;
if(filter.accept(f)) {
foundFiles.add(f);
actualCount++;
if(actualCount==maxFiles) return;
}
if(f.isDirectory() && actualLevel <= maxLevel) {
actualLevel++;
doIt(f);
}
}
}
public FileChangeWatcher watch(final long scanPeriodSecs, final boolean initBeforeFire, final FileChangeEventListener...listeners) {
return new FileChangeWatcher(this, scanPeriodSecs, initBeforeFire, listeners);
}
private static class NOFILTER implements FileFilter {
@Override
public boolean accept(final File pathname) {
return true;
}
}
}
| src/main/java/com/heliosapm/utils/file/FileFinder.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 com.heliosapm.utils.file;
import java.io.File;
import java.io.FileFilter;
import java.net.URL;
import java.util.LinkedHashSet;
import java.util.Set;
import com.heliosapm.utils.url.URLHelper;
/**
* <p>Title: FileFinder</p>
* <p>Description: Scans a given directory for files matching a file filter</p>
* <p>Company: Helios Development Group LLC</p>
* @author Whitehead (nwhitehead AT heliosdev DOT org)
* <p><code>com.heliosapm.utils.file.FileFinder</code></p>
*/
public class FileFinder {
public static final File[] EMPTY_FILE_ARR = {};
public static final URL[] EMPTY_URL_ARR = {};
private static final FileFilter DEFAULT_FILTER = new NOFILTER();
protected FileFilter filter = DEFAULT_FILTER;
protected int maxLevel = Integer.MAX_VALUE;
protected int maxFiles = 1024;
protected int actualLevel = 0;
protected int actualCount = 0;
protected final Set<File> foundFiles = new LinkedHashSet<File>();
protected final Set<File> dirsToSearch = new LinkedHashSet<File>();
private FileFinder(final String...dirs) {
addSearchDir(dirs);
}
FileFinder setFilter(final FileFilter filter) {
this.filter = filter;
return this;
}
public static FileFinder newFileFinder(final String...dirsToSearch) {
return new FileFinder(dirsToSearch);
}
public FileFinder addSearchDir(final String...dirs) {
for(String s : dirs) {
if(s==null || s.trim().isEmpty()) continue;
File f = new File(s.trim());
if(f.exists() && f.isDirectory()) {
dirsToSearch.add(f);
}
}
return this;
}
public FileFilterBuilder filterBuilder() {
return FileFilterBuilder.newBuilder(this);
}
public FileFinder maxDepth(final int depth) {
if(depth < 0) throw new IllegalArgumentException("Invalid maximum directory depth [" + depth + "]. Must be >= 0");
this.maxLevel = depth;
return this;
}
public FileFinder maxFiles(final int maxFiles) {
if(maxFiles < 0) throw new IllegalArgumentException("Invalid maximum file matches [" + maxFiles + "]. Must be >= 0");
this.maxFiles = maxFiles;
return this;
}
public File[] find() {
foundFiles.clear();
actualCount = 0;
actualLevel = 0;
if(dirsToSearch.isEmpty() || maxFiles==0) return EMPTY_FILE_ARR;
for(File dir: dirsToSearch) {
doIt(dir);
actualLevel = 0;
if(actualCount==maxFiles) break;
}
return foundFiles.toArray(new File[actualCount]);
}
public URL[] findAsURLs() {
final File[] files = find();
if(files.length==0) return EMPTY_URL_ARR;
final URL[] urls = new URL[files.length];
for(int i = 0; i <urls.length; i++) {
urls[i] = URLHelper.toURL(files[i]);
}
return urls;
}
protected void doIt(final File dir) {
if(actualCount==maxFiles) return;
for(File f: dir.listFiles()) {
if(actualCount==maxFiles) return;
if(filter.accept(f)) {
foundFiles.add(f);
actualCount++;
if(actualCount==maxFiles) return;
}
if(f.isDirectory() && actualLevel <= maxLevel) {
actualLevel++;
doIt(f);
}
}
}
public FileChangeWatcher watch(final long scanPeriodSecs, final boolean initBeforeFire, final FileChangeEventListener...listeners) {
return new FileChangeWatcher(this, scanPeriodSecs, initBeforeFire, listeners);
}
private static class NOFILTER implements FileFilter {
@Override
public boolean accept(final File pathname) {
return true;
}
}
}
| DevSync
| src/main/java/com/heliosapm/utils/file/FileFinder.java | DevSync | <ide><path>rc/main/java/com/heliosapm/utils/file/FileFinder.java
<ide> return this;
<ide> }
<ide>
<add> public FileFinder addSearchDir(final File...dirs) {
<add> for(File f : dirs) {
<add> if(f==null) continue;
<add> if(f.exists() && f.isDirectory()) {
<add> dirsToSearch.add(f);
<add> }
<add> }
<add> return this;
<add> }
<add>
<add>
<ide> public FileFilterBuilder filterBuilder() {
<ide> return FileFilterBuilder.newBuilder(this);
<ide> } |
|
Java | apache-2.0 | 4925b3ec5795ea1f415d0fe5053b96ab243d4110 | 0 | Thelonedevil/OTBProject,NthPortal/OTBProject,OTBProject/OTBProject | package com.github.otbproject.otbproject.command.parser;
import com.github.otbproject.otbproject.bot.AbstractBot;
import com.github.otbproject.otbproject.bot.BotInitException;
import com.github.otbproject.otbproject.bot.Control;
import com.github.otbproject.otbproject.bot.nullbot.NullBot;
import com.github.otbproject.otbproject.util.InstallationHelper;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class ParserTest {
private static final String TS = "[["; // Term Start
private static final String TE = "]]"; // Term End
private static final String MD = "."; // Modifier Delimiter
private static final String ES = "{{"; // Embedded String Start
private static final String EE = "}}"; // Embedded String End
private static final String USER = "nthportal";
private static final int COUNT = 1;
private static final String CHANNEL = "the_lone_devil";
@BeforeClass
public static void init() {
InstallationHelper.setupTestInstallation();
Control.setBot(new AbstractBot() {
@Override
public boolean isConnected(String channelName) {
return false;
}
@Override
public boolean isConnected() {
return false;
}
@Override
public boolean isChannel(String channelName) {
return false;
}
@Override
public String getUserName() {
return "test_user_name";
}
@Override
public boolean isUserMod(String channel, String user) {
return false;
}
@Override
public boolean isUserSubscriber(String channel, String user) {
return false;
}
@Override
public void sendMessage(String channel, String message) {
}
@Override
public void startBot() throws BotInitException {
}
@Override
public boolean join(String channelName) {
return false;
}
@Override
public boolean leave(String channelName) {
return false;
}
@Override
public boolean ban(String channelName, String user) {
return false;
}
@Override
public boolean unBan(String channelName, String user) {
return false;
}
@Override
public boolean timeout(String channelName, String user, int timeInSeconds) {
return false;
}
@Override
public boolean removeTimeout(String channelName, String user) {
return false;
}
});
}
@AfterClass
public static void cleanup() {
Control.setBot(NullBot.INSTANCE);
}
@Test
// Term-independent tests
public void generalTest() {
String[] args = new String[2];
args[0] = "foo";
args[1] = "bar";
// InvalidTerm
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "foo" + TE);
assertEquals(TS + "foo" + TE, parsed);
}
@Test
// Tests [[user]] term, as well as some general term parsing
public void userTest() {
String[] args = new String[2];
args[0] = "foo";
args[1] = "bar";
// Basic Test
// Term at beginning of string
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "user" + TE + " says hi.");
assertEquals("nthportal says hi.", parsed);
// Term at end of string
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Go to twitch.tv/" + TS + "user" + TE);
assertEquals("Go to twitch.tv/nthportal", parsed);
// Term in middle of string
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "start-" + TS + "user" + TE + "-end");
assertEquals("start-nthportal-end", parsed);
// Multiple times in one string, next to each other
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "user" + TE + TS + "user" + TE);
assertEquals("nthportalnthportal", parsed);
// Multiple times in one string, apart
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "user" + TE + "-foo-" + TS + "user" + TE);
assertEquals("nthportal-foo-nthportal", parsed);
// Space in term
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "user " + TE + TS + "user" + TE);
assertNotEquals("nthportalnthportal", parsed);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "user" + TE + TS + "user " + TE);
assertNotEquals("nthportalnthportal", parsed);
// Modifiers work for term in general
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "user" + MD + ModifierTypes.UPPER + TE);
assertEquals("NTHPORTAL", parsed);
}
@Test
// Test [[channel]] term
public void channelTest() {
String[] args = new String[2];
args[0] = "foo";
args[1] = "bar";
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "You are in " + TS + "channel" + TE + "'s channel.");
assertEquals("You are in the_lone_devil's channel.", parsed);
// Modifiers work for term in general
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "channel" + MD + ModifierTypes.UPPER + TE);
assertEquals("THE_LONE_DEVIL", parsed);
}
@Test
// Test [[count]] term
public void countTest() {
String[] args = new String[2];
args[0] = "foo";
args[1] = "bar";
// count == 0
int count = 0;
String parsed = CommandResponseParser.parse(USER, CHANNEL, count, args, "This command has been run " + TS + "count" + TE + " times.");
assertEquals("This command has been run 0 times.", parsed);
// large count
count = 30000;
parsed = CommandResponseParser.parse(USER, CHANNEL, count, args, "This command has been run " + TS + "count" + TE + " times.");
assertEquals("This command has been run 30000 times.", parsed);
// negative count (shouldn't ever happen, but testing for it anyway)
count = -30000;
parsed = CommandResponseParser.parse(USER, CHANNEL, count, args, "This command has been run " + TS + "count" + TE + " times.");
assertEquals("This command has been run -30000 times.", parsed);
}
@Test
// Test [[args{{default}}]] term, as well as defaults
// also tests for empty embedded string and term args
public void argsTest() {
// Empty args
String[] args = new String[0];
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + TE + ".");
assertEquals("Hi .", parsed);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + ES + "person" + EE + TE + ".");
assertEquals("Hi person.", parsed);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + ES + TS + "user" + TE + EE + TE + ".");
assertEquals("Hi nthportal.", parsed);
// Empty default (tests for any empty embedded string)
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + ES + EE + TE + ".");
assertEquals("Hi .", parsed);
// 1 arg
args = new String[1];
args[0] = "Justin";
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + TE + ".");
assertEquals("Hi Justin.", parsed);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + ES + "person" + EE + TE + ".");
assertEquals("Hi Justin.", parsed);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + ES + TS + "user" + TE + EE + TE + ".");
assertEquals("Hi Justin.", parsed);
// 2 args
args = new String[2];
args[0] = "awesome";
args[1] = "people";
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + TE + ".");
assertEquals("Hi awesome people.", parsed);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + ES + "person" + EE + TE + ".");
assertEquals("Hi awesome people.", parsed);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + ES + TS + "user" + TE + EE + TE + ".");
assertEquals("Hi awesome people.", parsed);
// Modifiers work for term in general
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + MD + ModifierTypes.UPPER + TE);
assertEquals("AWESOME PEOPLE", parsed);
// Terms as args (should not be parsed)
args[0] = TS + "user" + TE;
args[1] = TS + "channel" + TE;
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + TE);
assertEquals(TS + "user" + TE + " " + TS + "channel" + TE, parsed);
// Embedded string as args
args[0] = ES + "string" + EE;
args[1] = ES + "thing" + EE;
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "start-" + TS + "args" + TE + "-end");
assertEquals("start-" + ES + "string" + EE + " " + ES + "thing" + EE + "-end", parsed);
}
@Test
// Test [[ifargs{{string}}]]
public void ifargsTest() {
// Empty args
String[] args = new String[0];
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi" + TS + "ifargs" + ES + " " + EE + TE + TS + "args" + TE + ".");
assertEquals("Hi.", parsed);
// 1 arg
args = new String[1];
args[0] = "Justin";
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi" + TS + "ifargs" + ES + " " + EE + TE + TS + "args" + TE + ".");
assertEquals("Hi Justin.", parsed);
// 2 args
args = new String[2];
args[0] = "awesome";
args[1] = "people";
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi" + TS + "ifargs" + ES + " " + EE + TE + TS + "args" + TE + ".");
assertEquals("Hi awesome people.", parsed);
// No args with string if none
String rawMsg = TS + "ifarg1" + ES + "args!" + EE + ES + "no args :(" + EE + TE;
args = new String[0];
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("no args :(", parsed);
// 1 arg
args = "test".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("args!", parsed);
}
@Test
// Test [[fromargN.modifier{{default}}]]
public void fromargNTest() {
// fromarg1
// 0 args
String rawMsg = TS + "fromarg1" + TE;
String[] args = new String[0];
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("", parsed);
// 0 args default
rawMsg = TS + "fromarg1" + ES + "word" + EE + TE;
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("word", parsed);
// 1 arg
args = "one".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("one", parsed);
// 2 args
args = "one two".split(" ");
assertEquals(2, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("one two", parsed);
// fromarg2
// 1 arg
rawMsg = TS + "fromarg2" + TE;
args = "one".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("", parsed);
// 2 args
args = "one two".split(" ");
assertEquals(2, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("two", parsed);
// 3 args
args = "one two three".split(" ");
assertEquals(3, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("two three", parsed);
}
@Test
// Test [[ifargN{{string}}]] term (N is a natural number)
public void ifargNTest() {
String rawMsg = "Watch all perspectives at http://kadgar.net/live/" + TS + "channel" + TE + "/"
+ TS + "arg1" + TE + TS + "ifarg1" + ES + "/" + EE + TE + TS + "arg2" + TE + TS + "ifarg2" + ES + "/" + EE + TE
+ TS + "arg3" + TE + TS + "ifarg3" + ES + "/" + EE + TE + TS + "arg4" + TE + TS + "ifarg4" + ES + "/" + EE + TE;
// 0 args
String[] args = new String[0];
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/", parsed);
// 1 arg
args = "maddiiemaneater".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/maddiiemaneater/", parsed);
// 2 args
args = "maddiiemaneater mktheworst".split(" ");
assertEquals(2, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/maddiiemaneater/mktheworst/", parsed);
// 3 args
args = "maddiiemaneater mktheworst aureylian".split(" ");
assertEquals(3, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/maddiiemaneater/mktheworst/aureylian/", parsed);
// 4 args
args = "maddiiemaneater mktheworst aureylian nthportal".split(" ");
assertEquals(4, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/maddiiemaneater/mktheworst/aureylian/nthportal/", parsed);
// 5 args
args = "maddiiemaneater mktheworst aureylian nthportal nefarious411".split(" ");
assertEquals(5, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/maddiiemaneater/mktheworst/aureylian/nthportal/", parsed);
// No args
rawMsg = TS + "ifarg1" + ES + "an arg!" + EE + ES + "no args :(" + EE + TE;
args = new String[0];
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("no args :(", parsed);
// 1 arg
args = "test".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("an arg!", parsed);
}
@Test
// Test [[argN{{default}}]] term (N is a natural number)
public void argNTest() {
// Empty args
String[] args = new String[0];
String rawMsg = "words " + TS + "arg1" + ES + "something" + EE + TE + " words " + TS + "arg2" + ES
+ TS + "arg1" + TE + EE + TE + " words " + TS + "arg3" + ES + TS + "arg2" + ES
+ TS + "arg1" + ES + "dunno" + EE + TE + EE + TE + EE + TE
+ " words " + TS + "arg4" + ES + TS + "arg2" + TE + EE + TE + " words";
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("words something words words dunno words words", parsed);
// 1 arg
args = "one".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("words one words one words one words words", parsed);
// 2 args
args = "one two".split(" ");
assertEquals(2, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("words one words two words two words two words", parsed);
// 3 args
args = "one two three".split(" ");
assertEquals(3, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("words one words two words three words two words", parsed);
// 4 args
args = "one two three four".split(" ");
assertEquals(4, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("words one words two words three words four words", parsed);
// 5 args
args = "one two three four five".split(" ");
assertEquals(5, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("words one words two words three words four words", parsed);
// 2 digit arg number (11)
args = "1 2 3 4 5 6 7 8 9 10 11".split(" ");
assertEquals(11, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "arg11" + TE);
assertEquals("11", parsed);
// Non-number arg in rawMsg
rawMsg = TS + "argNotANumber" + TE;
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals(rawMsg, parsed);
}
@Test
// Test [[foreach{{prepend}}{{append}}]]
public void foreachTest() {
String rawMsg = "Watch all perspectives at http://kadgar.net/live/" + TS + "channel" + TE + "/"
+ TS + "foreach" + ES + EE + ES + "/" + EE + TE;
// 0 args
String[] args = new String[0];
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/", parsed);
// 1 arg
args = "maddiiemaneater".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/maddiiemaneater/", parsed);
// 2 args
args = "maddiiemaneater mktheworst".split(" ");
assertEquals(2, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/maddiiemaneater/mktheworst/", parsed);
rawMsg = "Here are some channels: [" + TS + "channel" + TE + "]" + TS + "foreach" + ES + " [" + EE + ES + "]" + EE + TE;
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Here are some channels: [the_lone_devil] [maddiiemaneater] [mktheworst]", parsed);
// Modifiers work for term in general
rawMsg = "Here are some channels: [" + TS + "channel" + TE + "]" + TS + "foreach" + MD + ModifierTypes.FIRST_CAP + ES + " [" + EE + ES + "]" + EE + TE;
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Here are some channels: [the_lone_devil] [Maddiiemaneater] [Mktheworst]", parsed);
}
@Test
// Test [[numargs]]
public void numargsTest() {
// 0 args
String[] args = new String[0];
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "There are " + TS + "numargs" + TE + " args.");
assertEquals("There are 0 args.", parsed);
// 1 arg
args = "maddiiemaneater".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "There is " + TS + "numargs" + TE + " arg.");
assertEquals("There is 1 arg.", parsed);
// 2 args
args = "maddiiemaneater mktheworst".split(" ");
assertEquals(2, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "There are " + TS + "numargs" + TE + " args.");
assertEquals("There are 2 args.", parsed);
// 3 args
args = "maddiiemaneater mktheworst aureylian".split(" ");
assertEquals(3, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "There are " + TS + "numargs" + TE + " args.");
assertEquals("There are 3 args.", parsed);
}
@Test
// Test [[equal{{compare1}}{{compare2}}{{same}}{{diff}}]]
public void equalTest() {
// Broadcaster test
String rawMsg = "[[equal{{[[user]]}}{{[[channel]]}}{{You are the broadcaster!}}{{You are not the broadcaster.}}]]";
String[] args = new String[0];
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("You are not the broadcaster.", parsed);
parsed = CommandResponseParser.parse(USER, "nthportal", COUNT, args, rawMsg);
assertEquals("You are the broadcaster!", parsed);
// Say hi only to the_lone_devil
rawMsg = "[[equal{{the_lone_devil}}{{[[user]]}}{{Hi Justin!}}]]";
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("", parsed);
parsed = CommandResponseParser.parse("the_lone_devil", CHANNEL, COUNT, args, rawMsg);
assertEquals("Hi Justin!", parsed);
}
@Test
// Test some limited aspects of [[quote]]
public void quoteTest() {
String rawMsg = "Quote: <[[quote{{[[arg1]]}}]]>";
String[] args = "not_a_number".split(" ");
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Quote: <>", parsed);
}
@Test
// [[bot]]
public void botTest() {
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, new String[0], "[[bot]]");
assertEquals(Control.getBot().getUserName(), parsed);
}
@Test
// [[service]]
public void serviceTest() {
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, new String[0], "[[service]]");
assertEquals("Twitch", parsed);
}
@Test
// Test modifiers ([[args]] used for completeness)
public void modifierTest() {
String[] args = "this is a TEST sentence.".split(" ");
// lower
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + MD + ModifierTypes.LOWER + TE);
assertEquals("this is a test sentence.", parsed);
// upper
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + MD + ModifierTypes.UPPER + TE);
assertEquals("THIS IS A TEST SENTENCE.", parsed);
// first_cap
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + MD + ModifierTypes.FIRST_CAP + TE);
assertEquals("This is a test sentence.", parsed);
// word_cap
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + MD + ModifierTypes.WORD_CAP + TE);
assertEquals("This Is A Test Sentence.", parsed);
// first_cap_soft
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + MD + ModifierTypes.FIRST_CAP_SOFT + TE);
assertEquals("This is a TEST sentence.", parsed);
// word_cap_soft
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + MD + ModifierTypes.WORD_CAP_SOFT + TE);
assertEquals("This Is A TEST Sentence.", parsed);
}
}
| src/test/java/com/github/otbproject/otbproject/command/parser/ParserTest.java | package com.github.otbproject.otbproject.command.parser;
import com.github.otbproject.otbproject.App;
import com.github.otbproject.otbproject.bot.AbstractBot;
import com.github.otbproject.otbproject.bot.BotInitException;
import com.github.otbproject.otbproject.bot.Control;
import com.github.otbproject.otbproject.config.Configs;
import com.github.otbproject.otbproject.config.GeneralConfig;
import com.github.otbproject.otbproject.config.Service;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class ParserTest {
private static final String TS = "[["; // Term Start
private static final String TE = "]]"; // Term End
private static final String MD = "."; // Modifier Delimiter
private static final String ES = "{{"; // Embedded String Start
private static final String EE = "}}"; // Embedded String End
private static final String USER = "nthportal";
private static final int COUNT = 1;
private static final String CHANNEL = "the_lone_devil";
@BeforeClass
public static void init() {
Control.setBot(new AbstractBot() {
@Override
public boolean isConnected(String channelName) {
return false;
}
@Override
public boolean isConnected() {
return false;
}
@Override
public boolean isChannel(String channelName) {
return false;
}
@Override
public String getUserName() {
return "test_user_name";
}
@Override
public boolean isUserMod(String channel, String user) {
return false;
}
@Override
public boolean isUserSubscriber(String channel, String user) {
return false;
}
@Override
public void sendMessage(String channel, String message) {
}
@Override
public void startBot() throws BotInitException {
}
@Override
public boolean join(String channelName) {
return false;
}
@Override
public boolean leave(String channelName) {
return false;
}
@Override
public boolean ban(String channelName, String user) {
return false;
}
@Override
public boolean unBan(String channelName, String user) {
return false;
}
@Override
public boolean timeout(String channelName, String user, int timeInSeconds) {
return false;
}
@Override
public boolean removeTimeout(String channelName, String user) {
return false;
}
});
GeneralConfig generalConfig = new GeneralConfig();
generalConfig.setService(Service.BEAM);
App.configManager.setGeneralConfig(generalConfig);
}
@AfterClass
public static void cleanup() {
Control.setBot(null);
App.configManager.setGeneralConfig(null);
}
@Test
// Term-independent tests
public void generalTest() {
String[] args = new String[2];
args[0] = "foo";
args[1] = "bar";
// InvalidTerm
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "foo" + TE);
assertEquals(TS + "foo" + TE, parsed);
}
@Test
// Tests [[user]] term, as well as some general term parsing
public void userTest() {
String[] args = new String[2];
args[0] = "foo";
args[1] = "bar";
// Basic Test
// Term at beginning of string
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "user" + TE + " says hi.");
assertEquals("nthportal says hi.", parsed);
// Term at end of string
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Go to twitch.tv/" + TS + "user" + TE);
assertEquals("Go to twitch.tv/nthportal", parsed);
// Term in middle of string
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "start-" + TS + "user" + TE + "-end");
assertEquals("start-nthportal-end", parsed);
// Multiple times in one string, next to each other
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "user" + TE + TS + "user" + TE);
assertEquals("nthportalnthportal", parsed);
// Multiple times in one string, apart
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "user" + TE + "-foo-" + TS + "user" + TE);
assertEquals("nthportal-foo-nthportal", parsed);
// Space in term
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "user " + TE + TS + "user" + TE);
assertNotEquals("nthportalnthportal", parsed);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "user" + TE + TS + "user " + TE);
assertNotEquals("nthportalnthportal", parsed);
// Modifiers work for term in general
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "user" + MD + ModifierTypes.UPPER + TE);
assertEquals("NTHPORTAL", parsed);
}
@Test
// Test [[channel]] term
public void channelTest() {
String[] args = new String[2];
args[0] = "foo";
args[1] = "bar";
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "You are in " + TS + "channel" + TE + "'s channel.");
assertEquals("You are in the_lone_devil's channel.", parsed);
// Modifiers work for term in general
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "channel" + MD + ModifierTypes.UPPER + TE);
assertEquals("THE_LONE_DEVIL", parsed);
}
@Test
// Test [[count]] term
public void countTest() {
String[] args = new String[2];
args[0] = "foo";
args[1] = "bar";
// count == 0
int count = 0;
String parsed = CommandResponseParser.parse(USER, CHANNEL, count, args, "This command has been run " + TS + "count" + TE + " times.");
assertEquals("This command has been run 0 times.", parsed);
// large count
count = 30000;
parsed = CommandResponseParser.parse(USER, CHANNEL, count, args, "This command has been run " + TS + "count" + TE + " times.");
assertEquals("This command has been run 30000 times.", parsed);
// negative count (shouldn't ever happen, but testing for it anyway)
count = -30000;
parsed = CommandResponseParser.parse(USER, CHANNEL, count, args, "This command has been run " + TS + "count" + TE + " times.");
assertEquals("This command has been run -30000 times.", parsed);
}
@Test
// Test [[args{{default}}]] term, as well as defaults
// also tests for empty embedded string and term args
public void argsTest() {
// Empty args
String[] args = new String[0];
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + TE + ".");
assertEquals("Hi .", parsed);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + ES + "person" + EE + TE + ".");
assertEquals("Hi person.", parsed);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + ES + TS + "user" + TE + EE + TE + ".");
assertEquals("Hi nthportal.", parsed);
// Empty default (tests for any empty embedded string)
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + ES + EE + TE + ".");
assertEquals("Hi .", parsed);
// 1 arg
args = new String[1];
args[0] = "Justin";
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + TE + ".");
assertEquals("Hi Justin.", parsed);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + ES + "person" + EE + TE + ".");
assertEquals("Hi Justin.", parsed);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + ES + TS + "user" + TE + EE + TE + ".");
assertEquals("Hi Justin.", parsed);
// 2 args
args = new String[2];
args[0] = "awesome";
args[1] = "people";
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + TE + ".");
assertEquals("Hi awesome people.", parsed);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + ES + "person" + EE + TE + ".");
assertEquals("Hi awesome people.", parsed);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi " + TS + "args" + ES + TS + "user" + TE + EE + TE + ".");
assertEquals("Hi awesome people.", parsed);
// Modifiers work for term in general
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + MD + ModifierTypes.UPPER + TE);
assertEquals("AWESOME PEOPLE", parsed);
// Terms as args (should not be parsed)
args[0] = TS + "user" + TE;
args[1] = TS + "channel" + TE;
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + TE);
assertEquals(TS + "user" + TE + " " + TS + "channel" + TE, parsed);
// Embedded string as args
args[0] = ES + "string" + EE;
args[1] = ES + "thing" + EE;
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "start-" + TS + "args" + TE + "-end");
assertEquals("start-" + ES + "string" + EE + " " + ES + "thing" + EE + "-end", parsed);
}
@Test
// Test [[ifargs{{string}}]]
public void ifargsTest() {
// Empty args
String[] args = new String[0];
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi" + TS + "ifargs" + ES + " " + EE + TE + TS + "args" + TE + ".");
assertEquals("Hi.", parsed);
// 1 arg
args = new String[1];
args[0] = "Justin";
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi" + TS + "ifargs" + ES + " " + EE + TE + TS + "args" + TE + ".");
assertEquals("Hi Justin.", parsed);
// 2 args
args = new String[2];
args[0] = "awesome";
args[1] = "people";
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "Hi" + TS + "ifargs" + ES + " " + EE + TE + TS + "args" + TE + ".");
assertEquals("Hi awesome people.", parsed);
// No args with string if none
String rawMsg = TS + "ifarg1" + ES + "args!" + EE + ES + "no args :(" + EE + TE;
args = new String[0];
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("no args :(", parsed);
// 1 arg
args = "test".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("args!", parsed);
}
@Test
// Test [[fromargN.modifier{{default}}]]
public void fromargNTest() {
// fromarg1
// 0 args
String rawMsg = TS + "fromarg1" + TE;
String[] args = new String[0];
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("", parsed);
// 0 args default
rawMsg = TS + "fromarg1" + ES + "word" + EE + TE;
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("word", parsed);
// 1 arg
args = "one".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("one", parsed);
// 2 args
args = "one two".split(" ");
assertEquals(2, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("one two", parsed);
// fromarg2
// 1 arg
rawMsg = TS + "fromarg2" + TE;
args = "one".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("", parsed);
// 2 args
args = "one two".split(" ");
assertEquals(2, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("two", parsed);
// 3 args
args = "one two three".split(" ");
assertEquals(3, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("two three", parsed);
}
@Test
// Test [[ifargN{{string}}]] term (N is a natural number)
public void ifargNTest() {
String rawMsg = "Watch all perspectives at http://kadgar.net/live/" + TS + "channel" + TE + "/"
+ TS + "arg1" + TE + TS + "ifarg1" + ES + "/" + EE + TE + TS + "arg2" + TE + TS + "ifarg2" + ES + "/" + EE + TE
+ TS + "arg3" + TE + TS + "ifarg3" + ES + "/" + EE + TE + TS + "arg4" + TE + TS + "ifarg4" + ES + "/" + EE + TE;
// 0 args
String[] args = new String[0];
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/", parsed);
// 1 arg
args = "maddiiemaneater".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/maddiiemaneater/", parsed);
// 2 args
args = "maddiiemaneater mktheworst".split(" ");
assertEquals(2, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/maddiiemaneater/mktheworst/", parsed);
// 3 args
args = "maddiiemaneater mktheworst aureylian".split(" ");
assertEquals(3, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/maddiiemaneater/mktheworst/aureylian/", parsed);
// 4 args
args = "maddiiemaneater mktheworst aureylian nthportal".split(" ");
assertEquals(4, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/maddiiemaneater/mktheworst/aureylian/nthportal/", parsed);
// 5 args
args = "maddiiemaneater mktheworst aureylian nthportal nefarious411".split(" ");
assertEquals(5, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/maddiiemaneater/mktheworst/aureylian/nthportal/", parsed);
// No args
rawMsg = TS + "ifarg1" + ES + "an arg!" + EE + ES + "no args :(" + EE + TE;
args = new String[0];
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("no args :(", parsed);
// 1 arg
args = "test".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("an arg!", parsed);
}
@Test
// Test [[argN{{default}}]] term (N is a natural number)
public void argNTest() {
// Empty args
String[] args = new String[0];
String rawMsg = "words " + TS + "arg1" + ES + "something" + EE + TE + " words " + TS + "arg2" + ES
+ TS + "arg1" + TE + EE + TE + " words " + TS + "arg3" + ES + TS + "arg2" + ES
+ TS + "arg1" + ES + "dunno" + EE + TE + EE + TE + EE + TE
+ " words " + TS + "arg4" + ES + TS + "arg2" + TE + EE + TE + " words";
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("words something words words dunno words words", parsed);
// 1 arg
args = "one".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("words one words one words one words words", parsed);
// 2 args
args = "one two".split(" ");
assertEquals(2, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("words one words two words two words two words", parsed);
// 3 args
args = "one two three".split(" ");
assertEquals(3, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("words one words two words three words two words", parsed);
// 4 args
args = "one two three four".split(" ");
assertEquals(4, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("words one words two words three words four words", parsed);
// 5 args
args = "one two three four five".split(" ");
assertEquals(5, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("words one words two words three words four words", parsed);
// 2 digit arg number (11)
args = "1 2 3 4 5 6 7 8 9 10 11".split(" ");
assertEquals(11, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "arg11" + TE);
assertEquals("11", parsed);
// Non-number arg in rawMsg
rawMsg = TS + "argNotANumber" + TE;
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals(rawMsg, parsed);
}
@Test
// Test [[foreach{{prepend}}{{append}}]]
public void foreachTest() {
String rawMsg = "Watch all perspectives at http://kadgar.net/live/" + TS + "channel" + TE + "/"
+ TS + "foreach" + ES + EE + ES + "/" + EE + TE;
// 0 args
String[] args = new String[0];
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/", parsed);
// 1 arg
args = "maddiiemaneater".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/maddiiemaneater/", parsed);
// 2 args
args = "maddiiemaneater mktheworst".split(" ");
assertEquals(2, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Watch all perspectives at http://kadgar.net/live/the_lone_devil/maddiiemaneater/mktheworst/", parsed);
rawMsg = "Here are some channels: [" + TS + "channel" + TE + "]" + TS + "foreach" + ES + " [" + EE + ES + "]" + EE + TE;
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Here are some channels: [the_lone_devil] [maddiiemaneater] [mktheworst]", parsed);
// Modifiers work for term in general
rawMsg = "Here are some channels: [" + TS + "channel" + TE + "]" + TS + "foreach" + MD + ModifierTypes.FIRST_CAP + ES + " [" + EE + ES + "]" + EE + TE;
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Here are some channels: [the_lone_devil] [Maddiiemaneater] [Mktheworst]", parsed);
}
@Test
// Test [[numargs]]
public void numargsTest() {
// 0 args
String[] args = new String[0];
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "There are " + TS + "numargs" + TE + " args.");
assertEquals("There are 0 args.", parsed);
// 1 arg
args = "maddiiemaneater".split(" ");
assertEquals(1, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "There is " + TS + "numargs" + TE + " arg.");
assertEquals("There is 1 arg.", parsed);
// 2 args
args = "maddiiemaneater mktheworst".split(" ");
assertEquals(2, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "There are " + TS + "numargs" + TE + " args.");
assertEquals("There are 2 args.", parsed);
// 3 args
args = "maddiiemaneater mktheworst aureylian".split(" ");
assertEquals(3, args.length);
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, "There are " + TS + "numargs" + TE + " args.");
assertEquals("There are 3 args.", parsed);
}
@Test
// Test [[equal{{compare1}}{{compare2}}{{same}}{{diff}}]]
public void equalTest() {
// Broadcaster test
String rawMsg = "[[equal{{[[user]]}}{{[[channel]]}}{{You are the broadcaster!}}{{You are not the broadcaster.}}]]";
String[] args = new String[0];
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("You are not the broadcaster.", parsed);
parsed = CommandResponseParser.parse(USER, "nthportal", COUNT, args, rawMsg);
assertEquals("You are the broadcaster!", parsed);
// Say hi only to the_lone_devil
rawMsg = "[[equal{{the_lone_devil}}{{[[user]]}}{{Hi Justin!}}]]";
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("", parsed);
parsed = CommandResponseParser.parse("the_lone_devil", CHANNEL, COUNT, args, rawMsg);
assertEquals("Hi Justin!", parsed);
}
@Test
// Test some limited aspects of [[quote]]
public void quoteTest() {
String rawMsg = "Quote: <[[quote{{[[arg1]]}}]]>";
String[] args = "not_a_number".split(" ");
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, rawMsg);
assertEquals("Quote: <>", parsed);
}
@Test
// [[bot]]
public void botTest() {
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, new String[0], "[[bot]]");
assertEquals(Control.getBot().getUserName(), parsed);
}
@Test
// [[service]]
public void serviceTest() {
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, new String[0], "[[service]]");
assertEquals("Beam", parsed);
}
@Test
// Test modifiers ([[args]] used for completeness)
public void modifierTest() {
String[] args = "this is a TEST sentence.".split(" ");
// lower
String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + MD + ModifierTypes.LOWER + TE);
assertEquals("this is a test sentence.", parsed);
// upper
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + MD + ModifierTypes.UPPER + TE);
assertEquals("THIS IS A TEST SENTENCE.", parsed);
// first_cap
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + MD + ModifierTypes.FIRST_CAP + TE);
assertEquals("This is a test sentence.", parsed);
// word_cap
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + MD + ModifierTypes.WORD_CAP + TE);
assertEquals("This Is A Test Sentence.", parsed);
// first_cap_soft
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + MD + ModifierTypes.FIRST_CAP_SOFT + TE);
assertEquals("This is a TEST sentence.", parsed);
// word_cap_soft
parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, args, TS + "args" + MD + ModifierTypes.WORD_CAP_SOFT + TE);
assertEquals("This Is A TEST Sentence.", parsed);
}
}
| Tweak ParserTest for config changes
Changed test for [[service]] term to use Twitch, so that the
service doesn't need to be changed, which caused concurrency
issues.
| src/test/java/com/github/otbproject/otbproject/command/parser/ParserTest.java | Tweak ParserTest for config changes | <ide><path>rc/test/java/com/github/otbproject/otbproject/command/parser/ParserTest.java
<ide> package com.github.otbproject.otbproject.command.parser;
<ide>
<del>import com.github.otbproject.otbproject.App;
<ide> import com.github.otbproject.otbproject.bot.AbstractBot;
<ide> import com.github.otbproject.otbproject.bot.BotInitException;
<ide> import com.github.otbproject.otbproject.bot.Control;
<del>import com.github.otbproject.otbproject.config.Configs;
<del>import com.github.otbproject.otbproject.config.GeneralConfig;
<del>import com.github.otbproject.otbproject.config.Service;
<add>import com.github.otbproject.otbproject.bot.nullbot.NullBot;
<add>import com.github.otbproject.otbproject.util.InstallationHelper;
<ide> import org.junit.AfterClass;
<ide> import org.junit.BeforeClass;
<ide> import org.junit.Test;
<ide>
<ide> @BeforeClass
<ide> public static void init() {
<add> InstallationHelper.setupTestInstallation();
<ide> Control.setBot(new AbstractBot() {
<ide> @Override
<ide> public boolean isConnected(String channelName) {
<ide> return false;
<ide> }
<ide> });
<del> GeneralConfig generalConfig = new GeneralConfig();
<del> generalConfig.setService(Service.BEAM);
<del> App.configManager.setGeneralConfig(generalConfig);
<ide> }
<ide>
<ide> @AfterClass
<ide> public static void cleanup() {
<del> Control.setBot(null);
<del> App.configManager.setGeneralConfig(null);
<add> Control.setBot(NullBot.INSTANCE);
<ide> }
<ide>
<ide> @Test
<ide> // [[service]]
<ide> public void serviceTest() {
<ide> String parsed = CommandResponseParser.parse(USER, CHANNEL, COUNT, new String[0], "[[service]]");
<del> assertEquals("Beam", parsed);
<add> assertEquals("Twitch", parsed);
<ide> }
<ide>
<ide> @Test |
|
JavaScript | mit | 5a3356aa74b6e5ff8136c8266e96c86035e6dd9c | 0 | depcheck/depcheck,depcheck/depcheck | import fs from 'fs';
import path from 'path';
import walkdir from 'walkdir';
import minimatch from 'minimatch';
import builtInModules from 'builtin-modules';
import requirePackageName from 'require-package-name';
import component from './component';
import getNodes from './utils/get-nodes';
import discoverPropertyDep from './utils/discover-property-dep';
function constructComponent(source, name) {
return source[name].reduce((result, current) =>
Object.assign(result, {
[current]: require(path.resolve(__dirname, name, current)),
}), {});
}
function objectValues(object) {
return Object.keys(object).map(key => object[key]);
}
const availableParsers = constructComponent(component, 'parser');
const availableDetectors = constructComponent(component, 'detector');
const availableSpecials = constructComponent(component, 'special');
const defaultOptions = {
withoutDev: false,
ignoreBinPackage: false,
ignoreMatches: [
],
ignoreDirs: [
'.git',
'.svn',
'.hg',
'.idea',
'node_modules',
'bower_components',
],
parsers: {
'*.js': availableParsers.jsx,
'*.jsx': availableParsers.jsx,
'*.coffee': availableParsers.coffee,
'*.litcoffee': availableParsers.coffee,
'*.coffee.md': availableParsers.coffee,
},
detectors: [
availableDetectors.importDeclaration,
availableDetectors.requireCallExpression,
availableDetectors.gruntLoadTaskCallExpression,
],
specials: objectValues(availableSpecials),
};
function getOrDefault(opt, key) {
return typeof opt[key] !== 'undefined' ? opt[key] : defaultOptions[key];
}
function unifyParser(parsers) {
return Object.assign({}, ...Object.keys(parsers).map(key => ({
[key]: parsers[key] instanceof Array ? parsers[key] : [parsers[key]],
})));
}
function safeDetect(detector, node) {
try {
return detector(node);
} catch (error) {
return [];
}
}
function minus(array1, array2) {
return array1.filter(item => array2.indexOf(item) === -1);
}
function unique(array, item) {
return array.indexOf(item) === -1 ? array.concat([item]) : array;
}
function concat(array, item) {
return array.concat(item);
}
function isStringArray(obj) {
return obj instanceof Array && obj.every(item => typeof item === 'string');
}
function isNpmPackage(dep) {
return dep && dep !== '.' && dep !== '..' && builtInModules.indexOf(dep) === -1;
}
function isModule(dir) {
try {
require(path.resolve(dir, 'package.json'));
return true;
} catch (error) {
return false;
}
}
function mergeBuckets(object1, object2) {
return Object.keys(object2).reduce((result, key) => ({
...result,
[key]: object2[key].concat(object1[key] || []),
}), object1);
}
function getDependencies(dir, filename, deps, parser, detectors) {
const detect = node =>
detectors.map(detector => safeDetect(detector, node)).reduce(concat, []);
return new Promise((resolve, reject) => {
fs.readFile(filename, 'utf8', (error, content) => {
if (error) {
reject(error);
}
try {
resolve(parser(content, filename, deps, dir));
} catch (syntaxError) {
reject(syntaxError);
}
});
}).then(ast => {
// when parser returns string array, skip detector step and treat them as dependencies directly.
if (isStringArray(ast)) {
return ast;
}
const dependencies = getNodes(ast)
.map(detect)
.reduce(concat, [])
.reduce(unique, [])
.map(requirePackageName);
const peerDeps = dependencies
.map(dep => discoverPropertyDep(dep, 'peerDependencies', deps, dir))
.reduce(concat, []);
const optionalDeps = dependencies
.map(dep => discoverPropertyDep(dep, 'optionalDependencies', deps, dir))
.reduce(concat, []);
return dependencies.concat(peerDeps).concat(optionalDeps);
});
}
function checkFile(dir, filename, deps, parsers, detectors) {
const basename = path.basename(filename);
const targets = Object.keys(parsers)
.filter(glob => minimatch(basename, glob, { dot: true }))
.map(key => parsers[key])
.reduce(concat, []);
return targets.map(parser =>
getDependencies(dir, filename, deps, parser, detectors)
.then(using => ({
using: {
[filename]: using.filter(isNpmPackage).reduce(unique, []),
},
}), error => ({
invalidFiles: {
[filename]: error,
},
})));
}
function checkDirectory(dir, rootDir, ignoreDirs, deps, parsers, detectors) {
return new Promise(resolve => {
const promises = [];
const finder = walkdir(dir, { 'no_recurse': true });
finder.on('directory', subdir =>
ignoreDirs.indexOf(path.basename(subdir)) === -1 && !isModule(subdir)
? promises.push(checkDirectory(subdir, rootDir, ignoreDirs, deps, parsers, detectors))
: null);
finder.on('file', filename =>
promises.push(...checkFile(rootDir, filename, deps, parsers, detectors)));
finder.on('error', (dirPath, error) =>
promises.push(Promise.resolve({
invalidDirs: {
[dirPath]: error,
},
})));
finder.on('end', () =>
resolve(Promise.all(promises).then(results =>
results.reduce((obj, current) => ({
using: mergeBuckets(obj.using, current.using || {}),
invalidFiles: Object.assign(obj.invalidFiles, current.invalidFiles),
invalidDirs: Object.assign(obj.invalidDirs, current.invalidDirs),
}), {
using: {},
invalidFiles: {},
invalidDirs: {},
}))));
});
}
function isIgnored(ignoreMatches, dependency) {
return ignoreMatches.some(match => minimatch(dependency, match));
}
function hasBin(rootDir, dependency) {
try {
const metadata = require(path.join(rootDir, 'node_modules', dependency, 'package.json'));
return metadata.hasOwnProperty('bin');
} catch (error) {
return false;
}
}
function filterDependencies(rootDir, ignoreBinPackage, ignoreMatches, dependencies) {
return Object.keys(dependencies)
.filter(dependency =>
ignoreBinPackage && hasBin(rootDir, dependency) ||
isIgnored(ignoreMatches, dependency)
? false
: true);
}
function buildResult(result, deps, devDeps) {
const usingDepsLookup = Object.keys(result.using).reduce((obj, filename) =>
result.using[filename].reduce((object, dep) => ({
...object,
[dep]: [filename].concat(object[dep] || []),
}), obj), {});
const usingDeps = Object.keys(usingDepsLookup);
const missingDeps = minus(usingDeps, deps.concat(devDeps));
return {
dependencies: minus(deps, usingDeps),
devDependencies: minus(devDeps, usingDeps),
missing: missingDeps,
invalidFiles: result.invalidFiles,
invalidDirs: result.invalidDirs,
};
}
export default function depcheck(rootDir, options, callback) {
const withoutDev = getOrDefault(options, 'withoutDev');
const ignoreBinPackage = getOrDefault(options, 'ignoreBinPackage');
const ignoreMatches = getOrDefault(options, 'ignoreMatches');
const ignoreDirs = defaultOptions.ignoreDirs.concat(options.ignoreDirs).reduce(unique, []);
const detectors = getOrDefault(options, 'detectors');
const parsers = Object.assign(
{ '*': getOrDefault(options, 'specials') },
unifyParser(getOrDefault(options, 'parsers')));
const metadata = options.package || require(path.join(rootDir, 'package.json'));
const dependencies = metadata.dependencies || {};
const devDependencies = metadata.devDependencies || {};
const deps = filterDependencies(rootDir, ignoreBinPackage, ignoreMatches, dependencies);
const devDeps = filterDependencies(rootDir, ignoreBinPackage, ignoreMatches, withoutDev ? [] : devDependencies);
const allDeps = deps.concat(devDeps).reduce(unique, []);
return checkDirectory(rootDir, rootDir, ignoreDirs, allDeps, parsers, detectors)
.then(result => buildResult(result, deps, devDeps))
.then(callback);
}
depcheck.parser = availableParsers;
depcheck.detector = availableDetectors;
depcheck.special = availableSpecials;
| src/index.js | import fs from 'fs';
import path from 'path';
import walkdir from 'walkdir';
import minimatch from 'minimatch';
import builtInModules from 'builtin-modules';
import requirePackageName from 'require-package-name';
import component from './component';
import getNodes from './utils/get-nodes';
import discoverPropertyDep from './utils/discover-property-dep';
function constructComponent(source, name) {
return source[name].reduce((result, current) =>
Object.assign(result, {
[current]: require(path.resolve(__dirname, name, current)),
}), {});
}
function objectValues(object) {
return Object.keys(object).map(key => object[key]);
}
const availableParsers = constructComponent(component, 'parser');
const availableDetectors = constructComponent(component, 'detector');
const availableSpecials = constructComponent(component, 'special');
const defaultOptions = {
withoutDev: false,
ignoreBinPackage: false,
ignoreMatches: [
],
ignoreDirs: [
'.git',
'.svn',
'.hg',
'.idea',
'node_modules',
'bower_components',
],
parsers: {
'*.js': availableParsers.jsx,
'*.jsx': availableParsers.jsx,
'*.coffee': availableParsers.coffee,
'*.litcoffee': availableParsers.coffee,
'*.coffee.md': availableParsers.coffee,
},
detectors: [
availableDetectors.importDeclaration,
availableDetectors.requireCallExpression,
availableDetectors.gruntLoadTaskCallExpression,
],
specials: objectValues(availableSpecials),
};
function getOrDefault(opt, key) {
return typeof opt[key] !== 'undefined' ? opt[key] : defaultOptions[key];
}
function unifyParser(parsers) {
return Object.assign({}, ...Object.keys(parsers).map(key => ({
[key]: parsers[key] instanceof Array ? parsers[key] : [parsers[key]],
})));
}
function safeDetect(detector, node) {
try {
return detector(node);
} catch (error) {
return [];
}
}
function minus(array1, array2) {
return array1.filter(item => array2.indexOf(item) === -1);
}
function unique(array, item) {
return array.indexOf(item) === -1 ? array.concat([item]) : array;
}
function concat(array, item) {
return array.concat(item);
}
function isStringArray(obj) {
return obj instanceof Array && obj.every(item => typeof item === 'string');
}
function isModule(dir) {
try {
require(path.resolve(dir, 'package.json'));
return true;
} catch (error) {
return false;
}
}
function getDependencies(dir, filename, deps, parser, detectors) {
const detect = node =>
detectors.map(detector => safeDetect(detector, node)).reduce(concat, []);
return new Promise((resolve, reject) => {
fs.readFile(filename, 'utf8', (error, content) => {
if (error) {
reject(error);
}
try {
resolve(parser(content, filename, deps, dir));
} catch (syntaxError) {
reject(syntaxError);
}
});
}).then(ast => {
// when parser returns string array, skip detector step and treat them as dependencies directly.
if (isStringArray(ast)) {
return ast;
}
const dependencies = getNodes(ast)
.map(detect)
.reduce(concat, [])
.reduce(unique, [])
.map(requirePackageName);
const peerDeps = dependencies
.map(dep => discoverPropertyDep(dep, 'peerDependencies', deps, dir))
.reduce(concat, []);
const optionalDeps = dependencies
.map(dep => discoverPropertyDep(dep, 'optionalDependencies', deps, dir))
.reduce(concat, []);
return dependencies.concat(peerDeps).concat(optionalDeps);
});
}
function checkFile(dir, filename, deps, parsers, detectors) {
const basename = path.basename(filename);
const targets = Object.keys(parsers)
.filter(glob => minimatch(basename, glob, { dot: true }))
.map(key => parsers[key])
.reduce(concat, []);
return targets.map(parser =>
getDependencies(dir, filename, deps, parser, detectors)
.then(used => ({
used: used.filter(dep => dep && dep !== '.' && dep !== '..'),
}), error => ({
invalidFiles: {
[filename]: error,
},
})));
}
function checkDirectory(dir, rootDir, ignoreDirs, deps, parsers, detectors) {
return new Promise(resolve => {
const promises = [];
const finder = walkdir(dir, { 'no_recurse': true });
finder.on('directory', subdir =>
ignoreDirs.indexOf(path.basename(subdir)) === -1 && !isModule(subdir)
? promises.push(checkDirectory(subdir, rootDir, ignoreDirs, deps, parsers, detectors))
: null);
finder.on('file', filename =>
promises.push(...checkFile(rootDir, filename, deps, parsers, detectors)));
finder.on('error', (dirPath, error) =>
promises.push(Promise.resolve({
invalidDirs: {
[dirPath]: error,
},
})));
finder.on('end', () =>
resolve(Promise.all(promises).then(results =>
results.reduce((obj, current) => ({
used: obj.used.concat(current.used || []).reduce(unique, []),
invalidFiles: Object.assign(obj.invalidFiles, current.invalidFiles),
invalidDirs: Object.assign(obj.invalidDirs, current.invalidDirs),
}), {
used: [],
invalidFiles: {},
invalidDirs: {},
}))));
});
}
function isIgnored(ignoreMatches, dependency) {
return ignoreMatches.some(match => minimatch(dependency, match));
}
function hasBin(rootDir, dependency) {
try {
const metadata = require(path.join(rootDir, 'node_modules', dependency, 'package.json'));
return metadata.hasOwnProperty('bin');
} catch (error) {
return false;
}
}
function filterDependencies(rootDir, ignoreBinPackage, ignoreMatches, dependencies) {
return Object.keys(dependencies)
.filter(dependency =>
ignoreBinPackage && hasBin(rootDir, dependency) ||
isIgnored(ignoreMatches, dependency)
? false
: true);
}
export default function depcheck(rootDir, options, callback) {
const withoutDev = getOrDefault(options, 'withoutDev');
const ignoreBinPackage = getOrDefault(options, 'ignoreBinPackage');
const ignoreMatches = getOrDefault(options, 'ignoreMatches');
const ignoreDirs = defaultOptions.ignoreDirs.concat(options.ignoreDirs).reduce(unique, []);
const detectors = getOrDefault(options, 'detectors');
const parsers = Object.assign(
{ '*': getOrDefault(options, 'specials') },
unifyParser(getOrDefault(options, 'parsers')));
const metadata = options.package || require(path.join(rootDir, 'package.json'));
const dependencies = metadata.dependencies || {};
const devDependencies = metadata.devDependencies || {};
const deps = filterDependencies(rootDir, ignoreBinPackage, ignoreMatches, dependencies);
const devDeps = filterDependencies(rootDir, ignoreBinPackage, ignoreMatches, withoutDev ? [] : devDependencies);
const allDeps = deps.concat(devDeps).reduce(unique, []);
return checkDirectory(rootDir, rootDir, ignoreDirs, allDeps, parsers, detectors)
.then(result => ({
dependencies: minus(deps, result.used),
devDependencies: minus(devDeps, result.used),
missing: minus(result.used, allDeps).filter(dep => builtInModules.indexOf(dep) === -1),
invalidFiles: result.invalidFiles,
invalidDirs: result.invalidDirs,
}))
.then(callback);
}
depcheck.parser = availableParsers;
depcheck.detector = availableDetectors;
depcheck.special = availableSpecials;
| Build up using dependencies lookup in internal process.
| src/index.js | Build up using dependencies lookup in internal process. | <ide><path>rc/index.js
<ide> return obj instanceof Array && obj.every(item => typeof item === 'string');
<ide> }
<ide>
<add>function isNpmPackage(dep) {
<add> return dep && dep !== '.' && dep !== '..' && builtInModules.indexOf(dep) === -1;
<add>}
<add>
<ide> function isModule(dir) {
<ide> try {
<ide> require(path.resolve(dir, 'package.json'));
<ide> } catch (error) {
<ide> return false;
<ide> }
<add>}
<add>
<add>function mergeBuckets(object1, object2) {
<add> return Object.keys(object2).reduce((result, key) => ({
<add> ...result,
<add> [key]: object2[key].concat(object1[key] || []),
<add> }), object1);
<ide> }
<ide>
<ide> function getDependencies(dir, filename, deps, parser, detectors) {
<ide>
<ide> return targets.map(parser =>
<ide> getDependencies(dir, filename, deps, parser, detectors)
<del> .then(used => ({
<del> used: used.filter(dep => dep && dep !== '.' && dep !== '..'),
<add> .then(using => ({
<add> using: {
<add> [filename]: using.filter(isNpmPackage).reduce(unique, []),
<add> },
<ide> }), error => ({
<ide> invalidFiles: {
<ide> [filename]: error,
<ide> finder.on('end', () =>
<ide> resolve(Promise.all(promises).then(results =>
<ide> results.reduce((obj, current) => ({
<del> used: obj.used.concat(current.used || []).reduce(unique, []),
<add> using: mergeBuckets(obj.using, current.using || {}),
<ide> invalidFiles: Object.assign(obj.invalidFiles, current.invalidFiles),
<ide> invalidDirs: Object.assign(obj.invalidDirs, current.invalidDirs),
<ide> }), {
<del> used: [],
<add> using: {},
<ide> invalidFiles: {},
<ide> invalidDirs: {},
<ide> }))));
<ide> : true);
<ide> }
<ide>
<add>function buildResult(result, deps, devDeps) {
<add> const usingDepsLookup = Object.keys(result.using).reduce((obj, filename) =>
<add> result.using[filename].reduce((object, dep) => ({
<add> ...object,
<add> [dep]: [filename].concat(object[dep] || []),
<add> }), obj), {});
<add>
<add> const usingDeps = Object.keys(usingDepsLookup);
<add> const missingDeps = minus(usingDeps, deps.concat(devDeps));
<add>
<add> return {
<add> dependencies: minus(deps, usingDeps),
<add> devDependencies: minus(devDeps, usingDeps),
<add> missing: missingDeps,
<add> invalidFiles: result.invalidFiles,
<add> invalidDirs: result.invalidDirs,
<add> };
<add>}
<add>
<ide> export default function depcheck(rootDir, options, callback) {
<ide> const withoutDev = getOrDefault(options, 'withoutDev');
<ide> const ignoreBinPackage = getOrDefault(options, 'ignoreBinPackage');
<ide> const allDeps = deps.concat(devDeps).reduce(unique, []);
<ide>
<ide> return checkDirectory(rootDir, rootDir, ignoreDirs, allDeps, parsers, detectors)
<del> .then(result => ({
<del> dependencies: minus(deps, result.used),
<del> devDependencies: minus(devDeps, result.used),
<del> missing: minus(result.used, allDeps).filter(dep => builtInModules.indexOf(dep) === -1),
<del> invalidFiles: result.invalidFiles,
<del> invalidDirs: result.invalidDirs,
<del> }))
<add> .then(result => buildResult(result, deps, devDeps))
<ide> .then(callback);
<ide> }
<ide> |
|
JavaScript | mit | 5c55c3a36e92f44ad4a864bf5952cdf41b3703eb | 0 | enesser/vCards-js | /********************************************************************************
vCards-js, Eric J Nesser, November 2014
********************************************************************************/
/*jslint node: true */
'use strict';
/**
* Represents a contact that can be imported into Outlook, iOS, Mac OS, Android devices, and more
*/
var vCard = (function () {
/**
* Get photo object for storing photos in vCards
*/
function getPhoto() {
return {
url: '',
mediaType: '',
base64: false,
/**
* Attach a photo from a URL
* @param {string} url URL where photo can be found
* @param {string} mediaType Media type of photo (JPEG, PNG, GIF)
*/
attachFromUrl: function(url, mediaType) {
this.url = url;
this.mediaType = mediaType;
this.base64 = false;
},
/**
* Embed a photo from a file using base-64 encoding (not implemented yet)
* @param {string} filename
*/
embedFromFile: function(fileLocation) {
var fs = require('fs');
var path = require('path');
this.mediaType = path.extname(fileLocation).toUpperCase().replace(/\./g, "");
var imgData = fs.readFileSync(fileLocation);
this.url = imgData.toString('base64');
this.base64 = true;
},
/**
* Embed a photo from a base-64 string
* @param {string} base64String
*/
embedFromString: function(base64String, mediaType) {
this.mediaType = mediaType;
this.url = base64String;
this.base64 = true;
}
};
}
/**
* Get a mailing address to attach to a vCard.
*/
function getMailingAddress() {
return {
/**
* Represents the actual text that should be put on the mailing label when delivering a physical package
* @type {String}
*/
label: '',
/**
* Street address
* @type {String}
*/
street: '',
/**
* City
* @type {String}
*/
city: '',
/**
* State or province
* @type {String}
*/
stateProvince: '',
/**
* Postal code
* @type {String}
*/
postalCode: '',
/**
* Country or region
* @type {String}
*/
countryRegion: ''
};
}
/**
* Get social media URLs
* @return {object} Social media URL hash group
*/
function getSocialUrls() {
return {
'facebook': '',
'linkedIn': '',
'twitter': '',
'flickr': ''
};
}
/********************************************************************************
* Public interface for vCard
********************************************************************************/
return {
/**
* Date of birth
* @type {Datetime}
*/
birthday: '',
/**
* Cell phone number
* @type {String}
*/
cellPhone: '',
/**
* Other cell phone number or pager
* @type {String}
*/
pagerPhone: '',
/**
* The address for private electronic mail communication
* @type {String}
*/
email: '',
/**
* The address for work-related electronic mail communication
* @type {String}
*/
workEmail: '',
/**
* First name
* @type {String}
*/
firstName: '',
/**
* Formatted name string associated with the vCard object (will automatically populate if not set)
* @type {String}
*/
formattedName: '',
/**
* Gender.
* @type {String} Must be M or F for Male or Female
*/
gender: '',
/**
* Home mailing address
* @type {object}
*/
homeAddress: getMailingAddress(),
/**
* Home phone
* @type {String}
*/
homePhone: '',
/**
* Home facsimile
* @type {String}
*/
homeFax: '',
/**
* Last name
* @type {String}
*/
lastName: '',
/**
* Logo
* @type {object}
*/
logo: getPhoto(),
/**
* Middle name
* @type {String}
*/
middleName: '',
/**
* Prefix for individual's name
* @type {String}
*/
namePrefix: '',
/**
* Suffix for individual's name
* @type {String}
*/
nameSuffix: '',
/**
* Nickname of individual
* @type {String}
*/
nickname: '',
/**
* Specifies supplemental information or a comment that is associated with the vCard
* @type {String}
*/
note: '',
/**
* The name and optionally the unit(s) of the organization associated with the vCard object
* @type {String}
*/
organization: '',
/**
* Individual's photo
* @type {object}
*/
photo: getPhoto(),
/**
* The role, occupation, or business category of the vCard object within an organization
* @type {String}
*/
role: '',
/**
* Social URLs attached to the vCard object (ex: Facebook, Twitter, LinkedIn)
* @type {String}
*/
socialUrls: getSocialUrls(),
/**
* A URL that can be used to get the latest version of this vCard
* @type {String}
*/
source: '',
/**
* Specifies the job title, functional position or function of the individual within an organization
* @type {String}
*/
title: '',
/**
* URL pointing to a website that represents the person in some way
* @type {String}
*/
url: '',
/**
* URL pointing to a website that represents the person's work in some way
* @type {String}
*/
workUrl: '',
/**
* Work mailing address
* @type {object}
*/
workAddress: getMailingAddress(),
/**
* Work phone
* @type {String}
*/
workPhone: '',
/**
* Work facsimile
* @type {String}
*/
workFax: '',
/**
* vCard version
* @type {String}
*/
version: '3.0',
/**
* Get major version of the vCard format
* @return {integer}
*/
getMajorVersion: function() {
var majorVersionString = this.version ? this.version.split('.')[0] : '4';
if (!isNaN(majorVersionString)) {
return parseInt(majorVersionString);
}
return 4;
},
/**
* Get formatted vCard
* @return {String} Formatted vCard in VCF format
*/
getFormattedString: function() {
var vCardFormatter = require('./lib/vCardFormatter');
return vCardFormatter.getFormattedString(this);
},
/**
* Save formatted vCard to file
* @param {String} filename
*/
saveToFile: function(filename) {
var vCardFormatter = require('./lib/vCardFormatter');
var contents = vCardFormatter.getFormattedString(this);
var fs = require('fs');
fs.writeFileSync(filename, contents, { encoding: 'utf8' });
}
};
});
module.exports = vCard;
| index.js | /********************************************************************************
vCards-js, Eric J Nesser, November 2014
********************************************************************************/
/*jslint node: true */
'use strict';
/**
* Represents a contact that can be imported into Outlook, iOS, Mac OS, Android devices, and more
*/
var vCard = (function () {
var fs = require('fs');
var path = require('path');
/**
* Get photo object for storing photos in vCards
*/
function getPhoto() {
return {
url: '',
mediaType: '',
base64: false,
/**
* Attach a photo from a URL
* @param {string} url URL where photo can be found
* @param {string} mediaType Media type of photo (JPEG, PNG, GIF)
*/
attachFromUrl: function(url, mediaType) {
this.url = url;
this.mediaType = mediaType;
this.base64 = false;
},
/**
* Embed a photo from a file using base-64 encoding (not implemented yet)
* @param {string} filename
*/
embedFromFile: function(fileLocation) {
this.mediaType = path.extname(fileLocation).toUpperCase().replace(/\./g, "");
var imgData = fs.readFileSync(fileLocation);
this.url = imgData.toString('base64');
this.base64 = true;
}
};
}
/**
* Get a mailing address to attach to a vCard.
*/
function getMailingAddress() {
return {
/**
* Represents the actual text that should be put on the mailing label when delivering a physical package
* @type {String}
*/
label: '',
/**
* Street address
* @type {String}
*/
street: '',
/**
* City
* @type {String}
*/
city: '',
/**
* State or province
* @type {String}
*/
stateProvince: '',
/**
* Postal code
* @type {String}
*/
postalCode: '',
/**
* Country or region
* @type {String}
*/
countryRegion: ''
};
}
/**
* Get social media URLs
* @return {object} Social media URL hash group
*/
function getSocialUrls() {
return {
'facebook': '',
'linkedIn': '',
'twitter': '',
'flickr': ''
};
}
/********************************************************************************
* Public interface for vCard
********************************************************************************/
return {
/**
* Date of birth
* @type {Datetime}
*/
birthday: '',
/**
* Cell phone number
* @type {String}
*/
cellPhone: '',
/**
* Other cell phone number or pager
* @type {String}
*/
pagerPhone: '',
/**
* The address for private electronic mail communication
* @type {String}
*/
email: '',
/**
* The address for work-related electronic mail communication
* @type {String}
*/
workEmail: '',
/**
* First name
* @type {String}
*/
firstName: '',
/**
* Formatted name string associated with the vCard object (will automatically populate if not set)
* @type {String}
*/
formattedName: '',
/**
* Gender.
* @type {String} Must be M or F for Male or Female
*/
gender: '',
/**
* Home mailing address
* @type {object}
*/
homeAddress: getMailingAddress(),
/**
* Home phone
* @type {String}
*/
homePhone: '',
/**
* Home facsimile
* @type {String}
*/
homeFax: '',
/**
* Last name
* @type {String}
*/
lastName: '',
/**
* Logo
* @type {object}
*/
logo: getPhoto(),
/**
* Middle name
* @type {String}
*/
middleName: '',
/**
* Prefix for individual's name
* @type {String}
*/
namePrefix: '',
/**
* Suffix for individual's name
* @type {String}
*/
nameSuffix: '',
/**
* Nickname of individual
* @type {String}
*/
nickname: '',
/**
* Specifies supplemental information or a comment that is associated with the vCard
* @type {String}
*/
note: '',
/**
* The name and optionally the unit(s) of the organization associated with the vCard object
* @type {String}
*/
organization: '',
/**
* Individual's photo
* @type {object}
*/
photo: getPhoto(),
/**
* The role, occupation, or business category of the vCard object within an organization
* @type {String}
*/
role: '',
/**
* Social URLs attached to the vCard object (ex: Facebook, Twitter, LinkedIn)
* @type {String}
*/
socialUrls: getSocialUrls(),
/**
* A URL that can be used to get the latest version of this vCard
* @type {String}
*/
source: '',
/**
* Specifies the job title, functional position or function of the individual within an organization
* @type {String}
*/
title: '',
/**
* URL pointing to a website that represents the person in some way
* @type {String}
*/
url: '',
/**
* URL pointing to a website that represents the person's work in some way
* @type {String}
*/
workUrl: '',
/**
* Work mailing address
* @type {object}
*/
workAddress: getMailingAddress(),
/**
* Work phone
* @type {String}
*/
workPhone: '',
/**
* Work facsimile
* @type {String}
*/
workFax: '',
/**
* vCard version
* @type {String}
*/
version: '3.0',
/**
* Get major version of the vCard format
* @return {integer}
*/
getMajorVersion: function() {
var majorVersionString = this.version ? this.version.split('.')[0] : '4';
if (!isNaN(majorVersionString)) {
return parseInt(majorVersionString);
}
return 4;
},
/**
* Get formatted vCard
* @return {String} Formatted vCard in VCF format
*/
getFormattedString: function() {
var vCardFormatter = require('./lib/vCardFormatter');
return vCardFormatter.getFormattedString(this);
},
/**
* Save formatted vCard to file
* @param {String} filename
*/
saveToFile: function(filename) {
var vCardFormatter = require('./lib/vCardFormatter');
var contents = vCardFormatter.getFormattedString(this);
var fs = require('fs');
fs.writeFileSync(filename, contents, { encoding: 'utf8' });
}
};
});
module.exports = vCard;
| Allow embedding image from base64 string. Require node-specific packages inside methods that require them, making it easier to use this package in the browser.
| index.js | Allow embedding image from base64 string. Require node-specific packages inside methods that require them, making it easier to use this package in the browser. | <ide><path>ndex.js
<ide> * Represents a contact that can be imported into Outlook, iOS, Mac OS, Android devices, and more
<ide> */
<ide> var vCard = (function () {
<del>
<del> var fs = require('fs');
<del> var path = require('path');
<del>
<ide> /**
<ide> * Get photo object for storing photos in vCards
<ide> */
<ide> * @param {string} filename
<ide> */
<ide> embedFromFile: function(fileLocation) {
<add> var fs = require('fs');
<add> var path = require('path');
<ide> this.mediaType = path.extname(fileLocation).toUpperCase().replace(/\./g, "");
<ide> var imgData = fs.readFileSync(fileLocation);
<ide> this.url = imgData.toString('base64');
<add> this.base64 = true;
<add> },
<add>
<add> /**
<add> * Embed a photo from a base-64 string
<add> * @param {string} base64String
<add> */
<add> embedFromString: function(base64String, mediaType) {
<add> this.mediaType = mediaType;
<add> this.url = base64String;
<ide> this.base64 = true;
<ide> }
<ide> }; |
|
Java | agpl-3.0 | 39c63eee50127dc5ad09ce7dc4ff94fdc1c9ea73 | 0 | podd/podd-redesign,podd/podd-redesign,podd/podd-redesign,podd/podd-redesign | /**
* PODD is an OWL ontology database used for scientific project management
*
* Copyright (C) 2009-2013 The University Of Queensland
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.podd.client.impl.restlet;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.openrdf.model.Literal;
import org.openrdf.model.Model;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.LinkedHashModel;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.Rio;
import org.openrdf.rio.UnsupportedRDFormatException;
import org.restlet.data.CharacterSet;
import org.restlet.data.CookieSetting;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.representation.InputRepresentation;
import org.restlet.representation.ReaderRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;
import org.restlet.util.Series;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.ansell.propertyutil.PropertyUtil;
import com.github.ansell.restletutils.RestletUtilMediaType;
import com.github.ansell.restletutils.RestletUtilRole;
import com.github.ansell.restletutils.SesameRealmConstants;
import com.github.podd.api.DanglingObjectPolicy;
import com.github.podd.api.DataReferenceVerificationPolicy;
import com.github.podd.api.data.DataReference;
import com.github.podd.api.data.DataReferenceConstants;
import com.github.podd.client.api.PoddClient;
import com.github.podd.client.api.PoddClientException;
import com.github.podd.utils.InferredOWLOntologyID;
import com.github.podd.utils.OntologyUtils;
import com.github.podd.utils.PODD;
import com.github.podd.utils.PoddRoles;
import com.github.podd.utils.PoddUser;
import com.github.podd.utils.PoddWebConstants;
/**
* Restlet based PODD Client implementation.
*
* @author Peter Ansell [email protected]
*/
public class RestletPoddClientImpl implements PoddClient
{
protected final Logger log = LoggerFactory.getLogger(this.getClass());
public final static String DEFAULT_PROPERTY_BUNDLE = "poddclient";
public static final String PROP_PODD_SERVER_URL = "podd.serverurl";
public static final String DEFAULT_PODD_SERVER_URL = "http://localhost:8080/podd/";
public final static String TEMP_UUID_PREFIX = "urn:temp:uuid:";
private Series<CookieSetting> currentCookies = new Series<CookieSetting>(CookieSetting.class);
private PropertyUtil props;
private volatile String serverUrl = null;
/**
* Shortcut to {@link PODD#VF}
*/
protected final static ValueFactory vf = PODD.VF;
public RestletPoddClientImpl()
{
this.props = new PropertyUtil(RestletPoddClientImpl.DEFAULT_PROPERTY_BUNDLE);
}
public RestletPoddClientImpl(final String poddServerUrl)
{
this();
this.serverUrl = poddServerUrl;
}
@Override
public void addRole(final String userIdentifier, final RestletUtilRole role, final InferredOWLOntologyID artifact)
throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_USER_ROLES));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_USER_IDENTIFIER, userIdentifier);
final Map<RestletUtilRole, Collection<URI>> mappings = new HashMap<>();
final Collection<URI> artifacts = Arrays.asList(artifact.getOntologyIRI().toOpenRDFURI());
mappings.put(role, artifacts);
final Model model = new LinkedHashModel();
PoddRoles.dumpRoleMappingsUser(mappings, model);
final Representation post = this.postRdf(resource, model);
try
{
final Model parsedStatements = this.parseRdf(post);
if(!parsedStatements.contains(null, SesameRealmConstants.OAS_USERIDENTIFIER,
PODD.VF.createLiteral(userIdentifier)))
{
this.log.warn("Role edit response did not seem to contain the user identifier");
}
}
catch(final IOException e)
{
throw new PoddClientException("Could not parse results due to an IOException", e);
}
}
@Override
public InferredOWLOntologyID appendArtifact(final InferredOWLOntologyID ontologyIRI,
final InputStream partialInputStream, final RDFFormat format) throws PoddClientException
{
return this.appendArtifact(ontologyIRI, partialInputStream, format, DanglingObjectPolicy.REPORT,
DataReferenceVerificationPolicy.DO_NOT_VERIFY);
}
@Override
public InferredOWLOntologyID appendArtifact(final InferredOWLOntologyID artifactID,
final InputStream partialInputStream, final RDFFormat format,
final DanglingObjectPolicy danglingObjectPolicy,
final DataReferenceVerificationPolicy dataReferenceVerificationPolicy) throws PoddClientException
{
final InputRepresentation rep =
new InputRepresentation(partialInputStream, MediaType.valueOf(format.getDefaultMIMEType()));
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_EDIT));
resource.getCookies().addAll(this.currentCookies);
this.log.info("cookies: {}", this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_EDIT_WITH_REPLACE, Boolean.toString(false));
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactID.getOntologyIRI().toString());
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_VERSION_IDENTIFIER, artifactID.getVersionIRI()
.toString());
if(danglingObjectPolicy == DanglingObjectPolicy.FORCE_CLEAN)
{
resource.addQueryParameter(PoddWebConstants.KEY_EDIT_WITH_FORCE, "true");
}
if(dataReferenceVerificationPolicy == DataReferenceVerificationPolicy.VERIFY)
{
resource.addQueryParameter(PoddWebConstants.KEY_EDIT_VERIFY_FILE_REFERENCES, "true");
}
resource.addQueryParameter("format", format.getDefaultMIMEType());
// Request the results in Turtle to reduce the bandwidth
final Representation post = resource.post(rep, MediaType.APPLICATION_RDF_TURTLE);
try
{
final Model parsedStatements = this.parseRdf(post);
final Collection<InferredOWLOntologyID> result =
OntologyUtils.modelToOntologyIDs(parsedStatements, true, false);
if(!result.isEmpty())
{
return result.iterator().next();
}
throw new PoddClientException("Failed to verify that the artifact was uploaded correctly.");
}
catch(final IOException e)
{
throw new PoddClientException("Could not parse artifact details due to an IOException", e);
}
}
@Override
public InferredOWLOntologyID attachDataReference(final DataReference ref) throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_ATTACH_DATA_REF));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, ref.getArtifactID().getOntologyIRI()
.toString());
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_VERSION_IDENTIFIER, ref.getArtifactID()
.getVersionIRI().toString());
resource.addQueryParameter(DataReferenceConstants.KEY_OBJECT_URI, ref.getObjectIri().toString());
final Model model = ref.toRDF();
final Representation post = this.postRdf(resource, model);
try
{
final Model parsedStatements = this.parseRdf(post);
final Collection<InferredOWLOntologyID> result =
OntologyUtils.modelToOntologyIDs(parsedStatements, true, false);
if(!result.isEmpty())
{
return result.iterator().next();
}
throw new PoddClientException("Failed to verify that the file reference was attached correctly.");
}
catch(final IOException e)
{
throw new PoddClientException("Could not parse artifact details due to an IOException", e);
}
}
@Override
public PoddUser createUser(final PoddUser user) throws PoddClientException
{
try
{
final Model model = new LinkedHashModel();
user.toModel(model, true);
final ByteArrayOutputStream output = new ByteArrayOutputStream(4096);
Rio.write(model, output, RDFFormat.RDFJSON);
final InputRepresentation rep =
new InputRepresentation(new ByteArrayInputStream(output.toByteArray()),
MediaType.valueOf(RDFFormat.RDFJSON.getDefaultMIMEType()));
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_USER_ADD));
resource.getCookies().addAll(this.currentCookies);
this.log.info("cookies: {}", this.currentCookies);
resource.addQueryParameter("format", RDFFormat.RDFJSON.getDefaultMIMEType());
// Request the results in Turtle to reduce the bandwidth
final Representation post = resource.post(rep, MediaType.APPLICATION_RDF_TURTLE);
final Model parsedStatements = this.parseRdf(post);
final PoddUser result = PoddUser.fromModel(model);
return result;
}
catch(final IOException | RDFHandlerException | ResourceException e)
{
throw new PoddClientException("Could not parse artifact details due to an exception", e);
}
}
@Override
public boolean deleteArtifact(final InferredOWLOntologyID artifactId) throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_DELETE));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactId.getOntologyIRI().toString());
if(artifactId.getVersionIRI() != null)
{
// FIXME: Versions are not supported in general by PODD, but they are important for
// verifying the state of the client to allow for early failure in cases where the
// client is out of date.
resource.addQueryParameter("versionUri", artifactId.getVersionIRI().toString());
}
resource.delete();
if(resource.getStatus().isSuccess())
{
return true;
}
else
{
throw new PoddClientException("Failed to successfully delete artifact: "
+ artifactId.getOntologyIRI().toString());
}
}
@Override
public Model doSPARQL(final String queryString, final InferredOWLOntologyID artifactId) throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_SPARQL));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactId.getOntologyIRI().toString());
// TODO: Parse query to make sure it is syntactically valid before sending query
resource.addQueryParameter(PoddWebConstants.KEY_SPARQLQUERY, queryString);
if(artifactId.getVersionIRI() != null)
{
// FIXME: Versions are not supported in general by PODD, but they are important for
// verifying the state of the client to allow for early failure in cases where the
// client is out of date.
resource.addQueryParameter("versionUri", artifactId.getVersionIRI().toString());
}
// Pass the desired format to the get method of the ClientResource
final Representation get = resource.get(RestletUtilMediaType.APPLICATION_RDF_JSON);
final StringWriter writer = new StringWriter(4096);
try
{
get.write(writer);
return Rio.parse(new StringReader(writer.toString()), "", RDFFormat.RDFJSON);
}
catch(final IOException | RDFParseException | UnsupportedRDFormatException e)
{
throw new PoddClientException("Could not process SPARQL query results", e);
}
}
@Override
public void downloadArtifact(final InferredOWLOntologyID artifactId, final OutputStream outputStream,
final RDFFormat format) throws PoddClientException
{
Objects.requireNonNull(artifactId);
Objects.requireNonNull(outputStream);
Objects.requireNonNull(format);
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_GET_BASE));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactId.getOntologyIRI().toString());
if(artifactId.getVersionIRI() != null)
{
// FIXME: Versions are not supported in general by PODD, but they are important for
// verifying the state of the client to allow for early failure in cases where the
// client is out of date.
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_VERSION_IDENTIFIER, artifactId.getVersionIRI()
.toString());
}
// Pass the desired format to the get method of the ClientResource
final Representation get = resource.get(MediaType.valueOf(format.getDefaultMIMEType()));
try
{
get.write(outputStream);
}
catch(final IOException e)
{
throw new PoddClientException("Could not write downloaded artifact to output stream", e);
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.client.api.PoddClient#getPoddServerUrl()
*/
@Override
public String getPoddServerUrl()
{
String result = this.serverUrl;
if(result == null)
{
synchronized(this)
{
result = this.serverUrl;
if(result == null)
{
this.serverUrl =
this.props.get(RestletPoddClientImpl.PROP_PODD_SERVER_URL,
RestletPoddClientImpl.DEFAULT_PODD_SERVER_URL);
}
result = this.serverUrl;
}
}
return result;
}
public PropertyUtil getProps()
{
return this.props;
}
public void setProps(final PropertyUtil props)
{
this.props = props;
}
/**
* Creates the URL for a given path using the current {@link #getPoddServerUrl()} result, or
* throws an IllegalStateException if the server URL has not been set.
*
* @param path
* The path of the web service to get a full URL for.
* @return The full URL to the given path.
* @throws IllegalStateException
* If {@link #setPoddServerUrl(String)} has not been called with a valid URL before
* this point.
*/
private String getUrl(final String path)
{
if(this.serverUrl == null)
{
throw new IllegalStateException("PODD Server URL has not been set for this client");
}
if(path == null)
{
throw new NullPointerException("Path cannot be null");
}
if(!path.startsWith("/"))
{
return this.serverUrl + "/" + path;
}
else
{
return this.serverUrl + path;
}
}
@Override
public PoddUser getUserDetails(final String userIdentifier) throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_USER_DETAILS));
resource.addQueryParameter(PoddWebConstants.KEY_USER_IDENTIFIER, userIdentifier);
resource.getCookies().addAll(this.currentCookies);
try
{
final Representation getResponse = resource.get(RestletUtilMediaType.APPLICATION_RDF_JSON);
if(!resource.getStatus().equals(Status.SUCCESS_OK))
{
throw new PoddClientException("Server returned a non-success status code: "
+ resource.getStatus().toString());
}
final InputStream stream = getResponse.getStream();
if(stream == null)
{
throw new PoddClientException("Did not receive valid response from server");
}
final RDFFormat format =
Rio.getParserFormatForMIMEType(getResponse.getMediaType().getName(), RDFFormat.RDFXML);
final Model model = Rio.parse(stream, "", format);
final PoddUser poddUser = PoddUser.fromModel(model);
return poddUser;
}
catch(final RDFParseException e)
{
throw new PoddClientException("Failed to parse RDF", e);
}
catch(final ResourceException e)
{
throw new PoddClientException("Failed to communicate with PODD Server", e);
}
catch(final IOException e)
{
throw new PoddClientException("Input output exception while parsing RDF", e);
}
}
@Override
public boolean isLoggedIn()
{
return !this.currentCookies.isEmpty();
}
private List<InferredOWLOntologyID> listArtifactsInternal(final boolean published, final boolean unpublished)
throws PoddClientException
{
return OntologyUtils.modelToOntologyIDs(this.listArtifacts(published, unpublished), false, false);
}
@Override
public Model listArtifacts(final boolean published, final boolean unpublished) throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_LIST));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_PUBLISHED, Boolean.toString(published));
resource.addQueryParameter(PoddWebConstants.KEY_UNPUBLISHED, Boolean.toString(unpublished));
try
{
final Representation getResponse = resource.get(RestletUtilMediaType.APPLICATION_RDF_JSON);
if(!resource.getStatus().equals(Status.SUCCESS_OK))
{
throw new PoddClientException("Server returned a non-success status code: "
+ resource.getStatus().toString());
}
final InputStream stream = getResponse.getStream();
if(stream == null)
{
throw new PoddClientException("Did not receive valid response from server");
}
final RDFFormat format =
Rio.getParserFormatForMIMEType(getResponse.getMediaType().getName(), RDFFormat.RDFXML);
return Rio.parse(stream, "", format);
}
catch(final RDFParseException e)
{
throw new PoddClientException("Failed to parse RDF", e);
}
catch(final ResourceException e)
{
throw new PoddClientException("Failed to communicate with PODD Server", e);
}
catch(final IOException e)
{
throw new PoddClientException("Input output exception while parsing RDF", e);
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.client.api.PoddClient#listDataReferenceRepositories()
*/
@Override
public List<String> listDataReferenceRepositories() throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_DATA_REPOSITORY_LIST));
resource.getCookies().addAll(this.currentCookies);
try
{
final Representation getResponse = resource.get(RestletUtilMediaType.APPLICATION_RDF_JSON);
if(!resource.getStatus().equals(Status.SUCCESS_OK))
{
throw new PoddClientException("Server returned a non-success status code: "
+ resource.getStatus().toString());
}
final InputStream stream = getResponse.getStream();
if(stream == null)
{
throw new PoddClientException("Did not receive valid response from server");
}
final RDFFormat format =
Rio.getParserFormatForMIMEType(getResponse.getMediaType().getName(), RDFFormat.RDFXML);
final Model model = Rio.parse(stream, "", format);
// DebugUtils.printContents(model);
final Set<Value> aliases = model.filter(null, PODD.PODD_BASE_HAS_ALIAS, null).objects();
final List<String> aliasResults = new ArrayList<String>(aliases.size());
for(final Value nextAlias : aliases)
{
aliasResults.add(((Literal)nextAlias).getLabel());
}
Collections.sort(aliasResults);
return aliasResults;
}
catch(final RDFParseException e)
{
throw new PoddClientException("Failed to parse RDF", e);
}
catch(final ResourceException e)
{
throw new PoddClientException("Failed to communicate with PODD Server", e);
}
catch(final IOException e)
{
throw new PoddClientException("Input output exception while parsing RDF", e);
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.client.api.PoddClient#listPublishedArtifacts()
*/
@Override
public List<InferredOWLOntologyID> listPublishedArtifacts() throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
return this.listArtifactsInternal(true, false);
}
@Override
public Map<RestletUtilRole, Collection<String>> listRoles(final InferredOWLOntologyID artifactId)
throws PoddClientException
{
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_ROLES));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactId.getOntologyIRI().toString());
this.log.info("cookies: {}", this.currentCookies);
final Representation get = resource.get(MediaType.APPLICATION_RDF_TURTLE);
try
{
return PoddRoles.extractRoleMappingsArtifact(this.parseRdf(get));
}
catch(final IOException e)
{
throw new PoddClientException("Could not parse role details due to an IOException", e);
}
}
@Override
public Map<RestletUtilRole, Collection<URI>> listRoles(final String userIdentifier) throws PoddClientException
{
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_USER_ROLES));
resource.getCookies().addAll(this.currentCookies);
if(userIdentifier != null)
{
resource.addQueryParameter(PoddWebConstants.KEY_USER_IDENTIFIER, userIdentifier);
}
this.log.info("cookies: {}", this.currentCookies);
final Representation get = resource.get(MediaType.APPLICATION_RDF_TURTLE);
try
{
return PoddRoles.extractRoleMappingsUser(this.parseRdf(get));
}
catch(final IOException e)
{
throw new PoddClientException("Could not parse role details due to an IOException", e);
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.client.api.PoddClient#listUnpublishedArtifacts()
*/
@Override
public List<InferredOWLOntologyID> listUnpublishedArtifacts() throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
return this.listArtifactsInternal(false, true);
}
@Override
public List<PoddUser> listUsers() throws PoddClientException
{
// Implement this when the service is available
throw new RuntimeException("TODO: Implement listUsers!");
}
/*
* (non-Javadoc)
*
* @see com.github.podd.client.api.PoddClient#login(java.lang.String, char[])
*/
@Override
public boolean login(final String username, final String password) throws PoddClientException
{
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.DEF_PATH_LOGIN_SUBMIT));
resource.getCookies().addAll(this.currentCookies);
// TODO: when Cookies natively supported by Client Resource, or another method remove this
// Until then, this is necessary to manually attach the cookies after login to the
// redirected address.
// GitHub issue for this: https://github.com/restlet/restlet-framework-java/issues/21
resource.setFollowingRedirects(false);
final Form form = new Form();
form.add("username", username);
form.add("password", password);
final Representation rep = resource.post(form.getWebRepresentation(CharacterSet.UTF_8));
try
{
this.log.info("login result status: {}", resource.getStatus());
if(rep != null)
{
// FIXME: Representation.getText may be implemented badly, so avoid calling it
// this.log.info("login result: {}", rep.getText());
}
else
{
this.log.info("login result was null");
}
// HACK
if(resource.getStatus().equals(Status.REDIRECTION_SEE_OTHER) || resource.getStatus().isSuccess())
{
this.currentCookies = resource.getCookieSettings();
}
this.log.info("cookies: {}", this.currentCookies);
return !this.currentCookies.isEmpty();
}
catch(final Throwable e)
{
this.currentCookies.clear();
this.log.warn("Error with request", e);
throw new PoddClientException(e);
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.client.api.PoddClient#logout()
*/
@Override
public boolean logout() throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.DEF_PATH_LOGOUT));
// add the cookie settings so that the server knows who to logout
resource.getCookies().addAll(this.currentCookies);
// TODO: when Cookies natively supported by Client Resource, or another method remove this
// Until then, this is necessary to manually attach the cookies after login to the
// redirected address.
// GitHub issue for this: https://github.com/restlet/restlet-framework-java/issues/21
resource.setFollowingRedirects(false);
final Representation rep = resource.get();
this.currentCookies = resource.getCookieSettings();
try
{
this.log.info("logout result status: {}", resource.getStatus());
if(rep != null)
{
// FIXME: Representation.getText may be implemented badly, so avoid calling it
// this.log.info("logout result: {}", rep.getText());
}
else
{
this.log.info("logout result was null");
}
this.log.info("cookies: {}", this.currentCookies);
this.currentCookies.clear();
return true;
}
catch(final Throwable e)
{
this.log.warn("Error with request", e);
throw new PoddClientException(e);
}
}
private Model parseRdf(final Representation rep) throws PoddClientException, IOException
{
final RDFFormat format = Rio.getParserFormatForMIMEType(rep.getMediaType().getName());
if(format == null)
{
throw new PoddClientException("Did not understand the format for the RDF response: "
+ rep.getMediaType().getName());
}
try
{
return Rio.parse(rep.getStream(), "", format);
}
catch(RDFParseException | UnsupportedRDFormatException e)
{
throw new PoddClientException("There was an error parsing the artifact", e);
}
}
/**
* @param resource
* @param rdf
* @return
* @throws PoddClientException
* @throws ResourceException
*/
private Representation postRdf(final ClientResource resource, final Model rdf) throws PoddClientException,
ResourceException
{
final StringWriter writer = new StringWriter();
try
{
Rio.write(rdf, writer, RDFFormat.RDFJSON);
}
catch(final RDFHandlerException e)
{
throw new PoddClientException("Could not generate request entity", e);
}
final Representation rep =
new ReaderRepresentation(new StringReader(writer.toString()), RestletUtilMediaType.APPLICATION_RDF_JSON);
final Representation post = resource.post(rep, RestletUtilMediaType.APPLICATION_RDF_JSON);
return post;
}
@Override
public InferredOWLOntologyID publishArtifact(final InferredOWLOntologyID ontologyIRI) throws PoddClientException
{
throw new RuntimeException("TODO: Implement publishArtifact!");
}
@Override
public void removeRole(final String userIdentifier, final RestletUtilRole role, final InferredOWLOntologyID artifact)
throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_USER_ROLES));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_USER_IDENTIFIER, userIdentifier);
resource.addQueryParameter(PoddWebConstants.KEY_DELETE, "true");
final Map<RestletUtilRole, Collection<URI>> mappings = new HashMap<>();
final Collection<URI> artifacts = Arrays.asList(artifact.getOntologyIRI().toOpenRDFURI());
mappings.put(role, artifacts);
final Model model = new LinkedHashModel();
PoddRoles.dumpRoleMappingsUser(mappings, model);
final Representation post = this.postRdf(resource, model);
try
{
final Model parsedStatements = this.parseRdf(post);
if(!parsedStatements.contains(null, SesameRealmConstants.OAS_USERIDENTIFIER,
PODD.VF.createLiteral(userIdentifier)))
{
this.log.warn("Role edit response did not seem to contain the user identifier");
}
}
catch(final IOException e)
{
throw new PoddClientException("Could not parse results due to an IOException", e);
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.client.api.PoddClient#setPoddServerUrl(java.lang.String)
*/
@Override
public void setPoddServerUrl(final String serverUrl)
{
this.serverUrl = serverUrl;
}
@Override
public InferredOWLOntologyID unpublishArtifact(final InferredOWLOntologyID ontologyIRI) throws PoddClientException
{
throw new RuntimeException("TODO: Implement unpublishArtifact");
}
@Override
public InferredOWLOntologyID updateArtifact(final InferredOWLOntologyID ontologyIRI,
final InputStream fullInputStream, final RDFFormat format) throws PoddClientException
{
throw new RuntimeException("TODO: Implement updateArtifact");
}
@Override
public InferredOWLOntologyID uploadNewArtifact(final InputStream input, final RDFFormat format)
throws PoddClientException
{
return this.uploadNewArtifact(input, format, DanglingObjectPolicy.REPORT,
DataReferenceVerificationPolicy.DO_NOT_VERIFY);
}
@Override
public InferredOWLOntologyID uploadNewArtifact(final InputStream input, final RDFFormat format,
final DanglingObjectPolicy danglingObjectPolicy,
final DataReferenceVerificationPolicy dataReferenceVerificationPolicy) throws PoddClientException
{
final InputRepresentation rep = new InputRepresentation(input, MediaType.valueOf(format.getDefaultMIMEType()));
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_UPLOAD));
resource.getCookies().addAll(this.currentCookies);
this.log.info("cookies: {}", this.currentCookies);
resource.addQueryParameter("format", format.getDefaultMIMEType());
if(danglingObjectPolicy == DanglingObjectPolicy.FORCE_CLEAN)
{
resource.addQueryParameter(PoddWebConstants.KEY_EDIT_WITH_FORCE, "true");
}
if(dataReferenceVerificationPolicy == DataReferenceVerificationPolicy.VERIFY)
{
resource.addQueryParameter(PoddWebConstants.KEY_EDIT_VERIFY_FILE_REFERENCES, "true");
}
// Request the results in Turtle to reduce the bandwidth
final Representation post = resource.post(rep, MediaType.APPLICATION_RDF_TURTLE);
try
{
final Model parsedStatements = this.parseRdf(post);
final Collection<InferredOWLOntologyID> result =
OntologyUtils.modelToOntologyIDs(parsedStatements, true, false);
if(!result.isEmpty())
{
return result.iterator().next();
}
throw new PoddClientException("Failed to verify that the artifact was uploaded correctly.");
}
catch(final IOException e)
{
throw new PoddClientException("Could not parse artifact details due to an IOException", e);
}
}
}
| client/restlet/src/main/java/com/github/podd/client/impl/restlet/RestletPoddClientImpl.java | /**
* PODD is an OWL ontology database used for scientific project management
*
* Copyright (C) 2009-2013 The University Of Queensland
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.podd.client.impl.restlet;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.openrdf.model.Literal;
import org.openrdf.model.Model;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.LinkedHashModel;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.Rio;
import org.openrdf.rio.UnsupportedRDFormatException;
import org.restlet.data.CharacterSet;
import org.restlet.data.CookieSetting;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.representation.InputRepresentation;
import org.restlet.representation.ReaderRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;
import org.restlet.util.Series;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.ansell.propertyutil.PropertyUtil;
import com.github.ansell.restletutils.RestletUtilMediaType;
import com.github.ansell.restletutils.RestletUtilRole;
import com.github.ansell.restletutils.SesameRealmConstants;
import com.github.podd.api.DanglingObjectPolicy;
import com.github.podd.api.DataReferenceVerificationPolicy;
import com.github.podd.api.data.DataReference;
import com.github.podd.api.data.DataReferenceConstants;
import com.github.podd.client.api.PoddClient;
import com.github.podd.client.api.PoddClientException;
import com.github.podd.utils.InferredOWLOntologyID;
import com.github.podd.utils.OntologyUtils;
import com.github.podd.utils.PODD;
import com.github.podd.utils.PoddRoles;
import com.github.podd.utils.PoddUser;
import com.github.podd.utils.PoddWebConstants;
/**
* Restlet based PODD Client implementation.
*
* @author Peter Ansell [email protected]
*/
public class RestletPoddClientImpl implements PoddClient
{
public final static String PROPERTY_BUNDLE = "poddclient";
protected final static String TEMP_UUID_PREFIX = "urn:temp:uuid:";
protected final Logger log = LoggerFactory.getLogger(this.getClass());
private volatile String serverUrl = null;
private Series<CookieSetting> currentCookies = new Series<CookieSetting>(CookieSetting.class);
private PropertyUtil props;
/**
* Shortcut to {@link PODD#VF}
*/
protected final static ValueFactory vf = PODD.VF;
private static final String PROP_PODD_SERVER_URL = "podd.serverurl";
public RestletPoddClientImpl()
{
this.props = new PropertyUtil(RestletPoddClientImpl.PROPERTY_BUNDLE);
}
public RestletPoddClientImpl(final String poddServerUrl)
{
this();
this.serverUrl = poddServerUrl;
}
@Override
public void addRole(final String userIdentifier, final RestletUtilRole role, final InferredOWLOntologyID artifact)
throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_USER_ROLES));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_USER_IDENTIFIER, userIdentifier);
final Map<RestletUtilRole, Collection<URI>> mappings = new HashMap<>();
final Collection<URI> artifacts = Arrays.asList(artifact.getOntologyIRI().toOpenRDFURI());
mappings.put(role, artifacts);
final Model model = new LinkedHashModel();
PoddRoles.dumpRoleMappingsUser(mappings, model);
final Representation post = this.postRdf(resource, model);
try
{
final Model parsedStatements = this.parseRdf(post);
if(!parsedStatements.contains(null, SesameRealmConstants.OAS_USERIDENTIFIER,
PODD.VF.createLiteral(userIdentifier)))
{
this.log.warn("Role edit response did not seem to contain the user identifier");
}
}
catch(final IOException e)
{
throw new PoddClientException("Could not parse results due to an IOException", e);
}
}
@Override
public InferredOWLOntologyID appendArtifact(final InferredOWLOntologyID ontologyIRI,
final InputStream partialInputStream, final RDFFormat format) throws PoddClientException
{
return this.appendArtifact(ontologyIRI, partialInputStream, format, DanglingObjectPolicy.REPORT,
DataReferenceVerificationPolicy.DO_NOT_VERIFY);
}
@Override
public InferredOWLOntologyID appendArtifact(final InferredOWLOntologyID artifactID,
final InputStream partialInputStream, final RDFFormat format,
final DanglingObjectPolicy danglingObjectPolicy,
final DataReferenceVerificationPolicy dataReferenceVerificationPolicy) throws PoddClientException
{
final InputRepresentation rep =
new InputRepresentation(partialInputStream, MediaType.valueOf(format.getDefaultMIMEType()));
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_EDIT));
resource.getCookies().addAll(this.currentCookies);
this.log.info("cookies: {}", this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_EDIT_WITH_REPLACE, Boolean.toString(false));
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactID.getOntologyIRI().toString());
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_VERSION_IDENTIFIER, artifactID.getVersionIRI()
.toString());
if(danglingObjectPolicy == DanglingObjectPolicy.FORCE_CLEAN)
{
resource.addQueryParameter(PoddWebConstants.KEY_EDIT_WITH_FORCE, "true");
}
if(dataReferenceVerificationPolicy == DataReferenceVerificationPolicy.VERIFY)
{
resource.addQueryParameter(PoddWebConstants.KEY_EDIT_VERIFY_FILE_REFERENCES, "true");
}
resource.addQueryParameter("format", format.getDefaultMIMEType());
// Request the results in Turtle to reduce the bandwidth
final Representation post = resource.post(rep, MediaType.APPLICATION_RDF_TURTLE);
try
{
final Model parsedStatements = this.parseRdf(post);
final Collection<InferredOWLOntologyID> result =
OntologyUtils.modelToOntologyIDs(parsedStatements, true, false);
if(!result.isEmpty())
{
return result.iterator().next();
}
throw new PoddClientException("Failed to verify that the artifact was uploaded correctly.");
}
catch(final IOException e)
{
throw new PoddClientException("Could not parse artifact details due to an IOException", e);
}
}
@Override
public InferredOWLOntologyID attachDataReference(final DataReference ref) throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_ATTACH_DATA_REF));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, ref.getArtifactID().getOntologyIRI()
.toString());
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_VERSION_IDENTIFIER, ref.getArtifactID()
.getVersionIRI().toString());
resource.addQueryParameter(DataReferenceConstants.KEY_OBJECT_URI, ref.getObjectIri().toString());
final Model model = ref.toRDF();
final Representation post = this.postRdf(resource, model);
try
{
final Model parsedStatements = this.parseRdf(post);
final Collection<InferredOWLOntologyID> result =
OntologyUtils.modelToOntologyIDs(parsedStatements, true, false);
if(!result.isEmpty())
{
return result.iterator().next();
}
throw new PoddClientException("Failed to verify that the file reference was attached correctly.");
}
catch(final IOException e)
{
throw new PoddClientException("Could not parse artifact details due to an IOException", e);
}
}
@Override
public PoddUser createUser(final PoddUser user) throws PoddClientException
{
try
{
final Model model = new LinkedHashModel();
user.toModel(model, true);
final ByteArrayOutputStream output = new ByteArrayOutputStream(4096);
Rio.write(model, output, RDFFormat.RDFJSON);
final InputRepresentation rep =
new InputRepresentation(new ByteArrayInputStream(output.toByteArray()),
MediaType.valueOf(RDFFormat.RDFJSON.getDefaultMIMEType()));
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_USER_ADD));
resource.getCookies().addAll(this.currentCookies);
this.log.info("cookies: {}", this.currentCookies);
resource.addQueryParameter("format", RDFFormat.RDFJSON.getDefaultMIMEType());
// Request the results in Turtle to reduce the bandwidth
final Representation post = resource.post(rep, MediaType.APPLICATION_RDF_TURTLE);
final Model parsedStatements = this.parseRdf(post);
final PoddUser result = PoddUser.fromModel(model);
return result;
}
catch(final IOException | RDFHandlerException | ResourceException e)
{
throw new PoddClientException("Could not parse artifact details due to an exception", e);
}
}
@Override
public boolean deleteArtifact(final InferredOWLOntologyID artifactId) throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_DELETE));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactId.getOntologyIRI().toString());
if(artifactId.getVersionIRI() != null)
{
// FIXME: Versions are not supported in general by PODD, but they are important for
// verifying the state of the client to allow for early failure in cases where the
// client is out of date.
resource.addQueryParameter("versionUri", artifactId.getVersionIRI().toString());
}
resource.delete();
if(resource.getStatus().isSuccess())
{
return true;
}
else
{
throw new PoddClientException("Failed to successfully delete artifact: "
+ artifactId.getOntologyIRI().toString());
}
}
@Override
public Model doSPARQL(final String queryString, final InferredOWLOntologyID artifactId) throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_SPARQL));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactId.getOntologyIRI().toString());
// TODO: Parse query to make sure it is syntactically valid before sending query
resource.addQueryParameter(PoddWebConstants.KEY_SPARQLQUERY, queryString);
if(artifactId.getVersionIRI() != null)
{
// FIXME: Versions are not supported in general by PODD, but they are important for
// verifying the state of the client to allow for early failure in cases where the
// client is out of date.
resource.addQueryParameter("versionUri", artifactId.getVersionIRI().toString());
}
// Pass the desired format to the get method of the ClientResource
final Representation get = resource.get(RestletUtilMediaType.APPLICATION_RDF_JSON);
final StringWriter writer = new StringWriter(4096);
try
{
get.write(writer);
return Rio.parse(new StringReader(writer.toString()), "", RDFFormat.RDFJSON);
}
catch(final IOException | RDFParseException | UnsupportedRDFormatException e)
{
throw new PoddClientException("Could not process SPARQL query results", e);
}
}
@Override
public void downloadArtifact(final InferredOWLOntologyID artifactId, final OutputStream outputStream,
final RDFFormat format) throws PoddClientException
{
Objects.requireNonNull(artifactId);
Objects.requireNonNull(outputStream);
Objects.requireNonNull(format);
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_GET_BASE));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactId.getOntologyIRI().toString());
if(artifactId.getVersionIRI() != null)
{
// FIXME: Versions are not supported in general by PODD, but they are important for
// verifying the state of the client to allow for early failure in cases where the
// client is out of date.
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_VERSION_IDENTIFIER, artifactId.getVersionIRI()
.toString());
}
// Pass the desired format to the get method of the ClientResource
final Representation get = resource.get(MediaType.valueOf(format.getDefaultMIMEType()));
try
{
get.write(outputStream);
}
catch(final IOException e)
{
throw new PoddClientException("Could not write downloaded artifact to output stream", e);
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.client.api.PoddClient#getPoddServerUrl()
*/
@Override
public String getPoddServerUrl()
{
String result = this.serverUrl;
if(result == null)
{
synchronized(this)
{
result = this.serverUrl;
if(result == null)
{
this.serverUrl =
this.props.get(RestletPoddClientImpl.PROP_PODD_SERVER_URL, "http://localhost:8080/podd/");
}
result = this.serverUrl;
}
}
return result;
}
public PropertyUtil getProps()
{
return this.props;
}
public void setProps(final PropertyUtil props)
{
this.props = props;
}
/**
* Creates the URL for a given path using the current {@link #getPoddServerUrl()} result, or
* throws an IllegalStateException if the server URL has not been set.
*
* @param path
* The path of the web service to get a full URL for.
* @return The full URL to the given path.
* @throws IllegalStateException
* If {@link #setPoddServerUrl(String)} has not been called with a valid URL before
* this point.
*/
private String getUrl(final String path)
{
if(this.serverUrl == null)
{
throw new IllegalStateException("PODD Server URL has not been set for this client");
}
if(path == null)
{
throw new NullPointerException("Path cannot be null");
}
if(!path.startsWith("/"))
{
return this.serverUrl + "/" + path;
}
else
{
return this.serverUrl + path;
}
}
@Override
public PoddUser getUserDetails(final String userIdentifier) throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_USER_DETAILS));
resource.addQueryParameter(PoddWebConstants.KEY_USER_IDENTIFIER, userIdentifier);
resource.getCookies().addAll(this.currentCookies);
try
{
final Representation getResponse = resource.get(RestletUtilMediaType.APPLICATION_RDF_JSON);
if(!resource.getStatus().equals(Status.SUCCESS_OK))
{
throw new PoddClientException("Server returned a non-success status code: "
+ resource.getStatus().toString());
}
final InputStream stream = getResponse.getStream();
if(stream == null)
{
throw new PoddClientException("Did not receive valid response from server");
}
final RDFFormat format =
Rio.getParserFormatForMIMEType(getResponse.getMediaType().getName(), RDFFormat.RDFXML);
final Model model = Rio.parse(stream, "", format);
final PoddUser poddUser = PoddUser.fromModel(model);
return poddUser;
}
catch(final RDFParseException e)
{
throw new PoddClientException("Failed to parse RDF", e);
}
catch(final ResourceException e)
{
throw new PoddClientException("Failed to communicate with PODD Server", e);
}
catch(final IOException e)
{
throw new PoddClientException("Input output exception while parsing RDF", e);
}
}
@Override
public boolean isLoggedIn()
{
return !this.currentCookies.isEmpty();
}
private List<InferredOWLOntologyID> listArtifactsInternal(final boolean published, final boolean unpublished)
throws PoddClientException
{
return OntologyUtils.modelToOntologyIDs(this.listArtifacts(published, unpublished), false, false);
}
@Override
public Model listArtifacts(final boolean published, final boolean unpublished) throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_LIST));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_PUBLISHED, Boolean.toString(published));
resource.addQueryParameter(PoddWebConstants.KEY_UNPUBLISHED, Boolean.toString(unpublished));
try
{
final Representation getResponse = resource.get(RestletUtilMediaType.APPLICATION_RDF_JSON);
if(!resource.getStatus().equals(Status.SUCCESS_OK))
{
throw new PoddClientException("Server returned a non-success status code: "
+ resource.getStatus().toString());
}
final InputStream stream = getResponse.getStream();
if(stream == null)
{
throw new PoddClientException("Did not receive valid response from server");
}
final RDFFormat format =
Rio.getParserFormatForMIMEType(getResponse.getMediaType().getName(), RDFFormat.RDFXML);
return Rio.parse(stream, "", format);
}
catch(final RDFParseException e)
{
throw new PoddClientException("Failed to parse RDF", e);
}
catch(final ResourceException e)
{
throw new PoddClientException("Failed to communicate with PODD Server", e);
}
catch(final IOException e)
{
throw new PoddClientException("Input output exception while parsing RDF", e);
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.client.api.PoddClient#listDataReferenceRepositories()
*/
@Override
public List<String> listDataReferenceRepositories() throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_DATA_REPOSITORY_LIST));
resource.getCookies().addAll(this.currentCookies);
try
{
final Representation getResponse = resource.get(RestletUtilMediaType.APPLICATION_RDF_JSON);
if(!resource.getStatus().equals(Status.SUCCESS_OK))
{
throw new PoddClientException("Server returned a non-success status code: "
+ resource.getStatus().toString());
}
final InputStream stream = getResponse.getStream();
if(stream == null)
{
throw new PoddClientException("Did not receive valid response from server");
}
final RDFFormat format =
Rio.getParserFormatForMIMEType(getResponse.getMediaType().getName(), RDFFormat.RDFXML);
final Model model = Rio.parse(stream, "", format);
// DebugUtils.printContents(model);
final Set<Value> aliases = model.filter(null, PODD.PODD_BASE_HAS_ALIAS, null).objects();
final List<String> aliasResults = new ArrayList<String>(aliases.size());
for(final Value nextAlias : aliases)
{
aliasResults.add(((Literal)nextAlias).getLabel());
}
Collections.sort(aliasResults);
return aliasResults;
}
catch(final RDFParseException e)
{
throw new PoddClientException("Failed to parse RDF", e);
}
catch(final ResourceException e)
{
throw new PoddClientException("Failed to communicate with PODD Server", e);
}
catch(final IOException e)
{
throw new PoddClientException("Input output exception while parsing RDF", e);
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.client.api.PoddClient#listPublishedArtifacts()
*/
@Override
public List<InferredOWLOntologyID> listPublishedArtifacts() throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
return this.listArtifactsInternal(true, false);
}
@Override
public Map<RestletUtilRole, Collection<String>> listRoles(final InferredOWLOntologyID artifactId)
throws PoddClientException
{
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_ROLES));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_ARTIFACT_IDENTIFIER, artifactId.getOntologyIRI().toString());
this.log.info("cookies: {}", this.currentCookies);
final Representation get = resource.get(MediaType.APPLICATION_RDF_TURTLE);
try
{
return PoddRoles.extractRoleMappingsArtifact(this.parseRdf(get));
}
catch(final IOException e)
{
throw new PoddClientException("Could not parse role details due to an IOException", e);
}
}
@Override
public Map<RestletUtilRole, Collection<URI>> listRoles(final String userIdentifier) throws PoddClientException
{
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_USER_ROLES));
resource.getCookies().addAll(this.currentCookies);
if(userIdentifier != null)
{
resource.addQueryParameter(PoddWebConstants.KEY_USER_IDENTIFIER, userIdentifier);
}
this.log.info("cookies: {}", this.currentCookies);
final Representation get = resource.get(MediaType.APPLICATION_RDF_TURTLE);
try
{
return PoddRoles.extractRoleMappingsUser(this.parseRdf(get));
}
catch(final IOException e)
{
throw new PoddClientException("Could not parse role details due to an IOException", e);
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.client.api.PoddClient#listUnpublishedArtifacts()
*/
@Override
public List<InferredOWLOntologyID> listUnpublishedArtifacts() throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
return this.listArtifactsInternal(false, true);
}
@Override
public List<PoddUser> listUsers() throws PoddClientException
{
// Implement this when the service is available
throw new RuntimeException("TODO: Implement listUsers!");
}
/*
* (non-Javadoc)
*
* @see com.github.podd.client.api.PoddClient#login(java.lang.String, char[])
*/
@Override
public boolean login(final String username, final String password) throws PoddClientException
{
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.DEF_PATH_LOGIN_SUBMIT));
resource.getCookies().addAll(this.currentCookies);
// TODO: when Cookies natively supported by Client Resource, or another method remove this
// Until then, this is necessary to manually attach the cookies after login to the
// redirected address.
// GitHub issue for this: https://github.com/restlet/restlet-framework-java/issues/21
resource.setFollowingRedirects(false);
final Form form = new Form();
form.add("username", username);
form.add("password", password);
final Representation rep = resource.post(form.getWebRepresentation(CharacterSet.UTF_8));
try
{
this.log.info("login result status: {}", resource.getStatus());
if(rep != null)
{
// FIXME: Representation.getText may be implemented badly, so avoid calling it
// this.log.info("login result: {}", rep.getText());
}
else
{
this.log.info("login result was null");
}
// HACK
if(resource.getStatus().equals(Status.REDIRECTION_SEE_OTHER) || resource.getStatus().isSuccess())
{
this.currentCookies = resource.getCookieSettings();
}
this.log.info("cookies: {}", this.currentCookies);
return !this.currentCookies.isEmpty();
}
catch(final Throwable e)
{
this.currentCookies.clear();
this.log.warn("Error with request", e);
throw new PoddClientException(e);
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.client.api.PoddClient#logout()
*/
@Override
public boolean logout() throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.DEF_PATH_LOGOUT));
// add the cookie settings so that the server knows who to logout
resource.getCookies().addAll(this.currentCookies);
// TODO: when Cookies natively supported by Client Resource, or another method remove this
// Until then, this is necessary to manually attach the cookies after login to the
// redirected address.
// GitHub issue for this: https://github.com/restlet/restlet-framework-java/issues/21
resource.setFollowingRedirects(false);
final Representation rep = resource.get();
this.currentCookies = resource.getCookieSettings();
try
{
this.log.info("logout result status: {}", resource.getStatus());
if(rep != null)
{
// FIXME: Representation.getText may be implemented badly, so avoid calling it
// this.log.info("logout result: {}", rep.getText());
}
else
{
this.log.info("logout result was null");
}
this.log.info("cookies: {}", this.currentCookies);
this.currentCookies.clear();
return true;
}
catch(final Throwable e)
{
this.log.warn("Error with request", e);
throw new PoddClientException(e);
}
}
private Model parseRdf(final Representation rep) throws PoddClientException, IOException
{
final RDFFormat format = Rio.getParserFormatForMIMEType(rep.getMediaType().getName());
if(format == null)
{
throw new PoddClientException("Did not understand the format for the RDF response: "
+ rep.getMediaType().getName());
}
try
{
return Rio.parse(rep.getStream(), "", format);
}
catch(RDFParseException | UnsupportedRDFormatException e)
{
throw new PoddClientException("There was an error parsing the artifact", e);
}
}
/**
* @param resource
* @param rdf
* @return
* @throws PoddClientException
* @throws ResourceException
*/
private Representation postRdf(final ClientResource resource, final Model rdf) throws PoddClientException,
ResourceException
{
final StringWriter writer = new StringWriter();
try
{
Rio.write(rdf, writer, RDFFormat.RDFJSON);
}
catch(final RDFHandlerException e)
{
throw new PoddClientException("Could not generate request entity", e);
}
final Representation rep =
new ReaderRepresentation(new StringReader(writer.toString()), RestletUtilMediaType.APPLICATION_RDF_JSON);
final Representation post = resource.post(rep, RestletUtilMediaType.APPLICATION_RDF_JSON);
return post;
}
@Override
public InferredOWLOntologyID publishArtifact(final InferredOWLOntologyID ontologyIRI) throws PoddClientException
{
throw new RuntimeException("TODO: Implement publishArtifact!");
}
@Override
public void removeRole(final String userIdentifier, final RestletUtilRole role, final InferredOWLOntologyID artifact)
throws PoddClientException
{
this.log.info("cookies: {}", this.currentCookies);
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_USER_ROLES));
resource.getCookies().addAll(this.currentCookies);
resource.addQueryParameter(PoddWebConstants.KEY_USER_IDENTIFIER, userIdentifier);
resource.addQueryParameter(PoddWebConstants.KEY_DELETE, "true");
final Map<RestletUtilRole, Collection<URI>> mappings = new HashMap<>();
final Collection<URI> artifacts = Arrays.asList(artifact.getOntologyIRI().toOpenRDFURI());
mappings.put(role, artifacts);
final Model model = new LinkedHashModel();
PoddRoles.dumpRoleMappingsUser(mappings, model);
final Representation post = this.postRdf(resource, model);
try
{
final Model parsedStatements = this.parseRdf(post);
if(!parsedStatements.contains(null, SesameRealmConstants.OAS_USERIDENTIFIER,
PODD.VF.createLiteral(userIdentifier)))
{
this.log.warn("Role edit response did not seem to contain the user identifier");
}
}
catch(final IOException e)
{
throw new PoddClientException("Could not parse results due to an IOException", e);
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.client.api.PoddClient#setPoddServerUrl(java.lang.String)
*/
@Override
public void setPoddServerUrl(final String serverUrl)
{
this.serverUrl = serverUrl;
}
@Override
public InferredOWLOntologyID unpublishArtifact(final InferredOWLOntologyID ontologyIRI) throws PoddClientException
{
throw new RuntimeException("TODO: Implement unpublishArtifact");
}
@Override
public InferredOWLOntologyID updateArtifact(final InferredOWLOntologyID ontologyIRI,
final InputStream fullInputStream, final RDFFormat format) throws PoddClientException
{
throw new RuntimeException("TODO: Implement updateArtifact");
}
@Override
public InferredOWLOntologyID uploadNewArtifact(final InputStream input, final RDFFormat format)
throws PoddClientException
{
return this.uploadNewArtifact(input, format, DanglingObjectPolicy.REPORT,
DataReferenceVerificationPolicy.DO_NOT_VERIFY);
}
@Override
public InferredOWLOntologyID uploadNewArtifact(final InputStream input, final RDFFormat format,
final DanglingObjectPolicy danglingObjectPolicy,
final DataReferenceVerificationPolicy dataReferenceVerificationPolicy) throws PoddClientException
{
final InputRepresentation rep = new InputRepresentation(input, MediaType.valueOf(format.getDefaultMIMEType()));
final ClientResource resource = new ClientResource(this.getUrl(PoddWebConstants.PATH_ARTIFACT_UPLOAD));
resource.getCookies().addAll(this.currentCookies);
this.log.info("cookies: {}", this.currentCookies);
resource.addQueryParameter("format", format.getDefaultMIMEType());
if(danglingObjectPolicy == DanglingObjectPolicy.FORCE_CLEAN)
{
resource.addQueryParameter(PoddWebConstants.KEY_EDIT_WITH_FORCE, "true");
}
if(dataReferenceVerificationPolicy == DataReferenceVerificationPolicy.VERIFY)
{
resource.addQueryParameter(PoddWebConstants.KEY_EDIT_VERIFY_FILE_REFERENCES, "true");
}
// Request the results in Turtle to reduce the bandwidth
final Representation post = resource.post(rep, MediaType.APPLICATION_RDF_TURTLE);
try
{
final Model parsedStatements = this.parseRdf(post);
final Collection<InferredOWLOntologyID> result =
OntologyUtils.modelToOntologyIDs(parsedStatements, true, false);
if(!result.isEmpty())
{
return result.iterator().next();
}
throw new PoddClientException("Failed to verify that the artifact was uploaded correctly.");
}
catch(final IOException e)
{
throw new PoddClientException("Could not parse artifact details due to an IOException", e);
}
}
}
| reorganise static constants in client | client/restlet/src/main/java/com/github/podd/client/impl/restlet/RestletPoddClientImpl.java | reorganise static constants in client | <ide><path>lient/restlet/src/main/java/com/github/podd/client/impl/restlet/RestletPoddClientImpl.java
<ide> */
<ide> public class RestletPoddClientImpl implements PoddClient
<ide> {
<del> public final static String PROPERTY_BUNDLE = "poddclient";
<del>
<del> protected final static String TEMP_UUID_PREFIX = "urn:temp:uuid:";
<del>
<ide> protected final Logger log = LoggerFactory.getLogger(this.getClass());
<ide>
<add> public final static String DEFAULT_PROPERTY_BUNDLE = "poddclient";
<add>
<add> public static final String PROP_PODD_SERVER_URL = "podd.serverurl";
<add>
<add> public static final String DEFAULT_PODD_SERVER_URL = "http://localhost:8080/podd/";
<add>
<add> public final static String TEMP_UUID_PREFIX = "urn:temp:uuid:";
<add>
<add> private Series<CookieSetting> currentCookies = new Series<CookieSetting>(CookieSetting.class);
<add>
<add> private PropertyUtil props;
<add>
<ide> private volatile String serverUrl = null;
<del>
<del> private Series<CookieSetting> currentCookies = new Series<CookieSetting>(CookieSetting.class);
<del>
<del> private PropertyUtil props;
<ide>
<ide> /**
<ide> * Shortcut to {@link PODD#VF}
<ide> */
<ide> protected final static ValueFactory vf = PODD.VF;
<ide>
<del> private static final String PROP_PODD_SERVER_URL = "podd.serverurl";
<del>
<ide> public RestletPoddClientImpl()
<ide> {
<del> this.props = new PropertyUtil(RestletPoddClientImpl.PROPERTY_BUNDLE);
<add> this.props = new PropertyUtil(RestletPoddClientImpl.DEFAULT_PROPERTY_BUNDLE);
<ide> }
<ide>
<ide> public RestletPoddClientImpl(final String poddServerUrl)
<ide> if(result == null)
<ide> {
<ide> this.serverUrl =
<del> this.props.get(RestletPoddClientImpl.PROP_PODD_SERVER_URL, "http://localhost:8080/podd/");
<add> this.props.get(RestletPoddClientImpl.PROP_PODD_SERVER_URL,
<add> RestletPoddClientImpl.DEFAULT_PODD_SERVER_URL);
<ide> }
<ide> result = this.serverUrl;
<ide> } |
|
Java | apache-2.0 | 9eb4ef0aba8863f1ae468d2a88a27858863359b9 | 0 | cherryhill/collectionspace-application | package org.collectionspace.chain.csp.persistence.file;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.security.Security;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.commons.io.IOUtils;
import org.collectionspace.chain.controller.ChainServlet;
import org.collectionspace.chain.csp.persistence.file.FileStorage;
import org.collectionspace.chain.csp.persistence.file.StubJSONStore;
import org.collectionspace.chain.csp.persistence.services.connection.RequestMethod;
import org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument;
import org.collectionspace.chain.csp.persistence.services.connection.ServicesConnection;
import org.collectionspace.chain.storage.UTF8SafeHttpTester;
import org.collectionspace.chain.uispec.SchemaStore;
import org.collectionspace.chain.uispec.StubSchemaStore;
import org.collectionspace.chain.util.json.JSONUtils;
import org.collectionspace.csp.api.core.CSPDependencyException;
import org.collectionspace.csp.api.persistence.ExistException;
import org.collectionspace.csp.api.persistence.UnderlyingStorageException;
import org.collectionspace.csp.api.persistence.UnimplementedException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mortbay.jetty.testing.HttpTester;
import org.mortbay.jetty.testing.ServletTester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestGeneral {
private static final Logger log=LoggerFactory.getLogger(TestGeneral.class);
private final static String testStr = "{\"items\":[{\"value\":\"This is an experimental widget being tested. It will not do what you expect.\"," +
"\"title\":\"\",\"type\":\"caption\"},{\"title\":\"Your file\",\"type\":\"resource\",\"param\":\"file\"}," +
"{\"title\":\"Author\",\"type\":\"text\",\"param\":\"author\"},{\"title\":\"Title\",\"type\":\"text\"," +
"\"param\":\"title\"},{\"title\":\"Type\",\"type\":\"dropdown\",\"values\":[{\"value\":\"1\",\"text\":" +
"\"thesis\"},{\"value\":\"2\",\"text\":\"paper\"},{\"value\":\"3\",\"text\":\"excel-controlled\"}]," +
"\"param\":\"type\"}]}";
private final static String testStr2 = "{\"accessionNumber\":\"123\",\"a\":\"b\\\"\"}";
private final static String testStr3 = "{\"a\":\"b\",\"id\":\"***misc***\",\"objects\":\"***objects***\",\"intake\":\"***intake***\"}";
private final static String testStr4 = "{\"a\":\"b\",\"id\":\"MISC2009.1\",\"objects\":\"OBJ2009.1\",\"intake\":\"IN2009.1\"}";
private final static String testStr5 = "{\"a\":\"b\",\"id\":\"MISC2009.2\",\"objects\":\"OBJ2009.2\",\"intake\":\"IN2009.2\"}";
private final static String testStr6 = "{\"userId\": \"[email protected]\",\"userName\": \"[email protected]\",\"password\": \"testpassword\",\"email\": \"[email protected]\",\"status\": \"inactive\"}";
private final static String testStr7 = "{\"userId\": \"[email protected]\",\"screenName\": \"unittestzzz\",\"password\": \"testpassword\",\"email\": \"[email protected]\",\"status\": \"active\"}";
private final static String testStr8 = "{\"email\": \"[email protected]\", \"debug\" : true }";
private FileStorage store;
private static String tmp=null;
private static synchronized String tmpdir() {
if(tmp==null) {
tmp=System.getProperty("java.io.tmpdir");
}
return tmp;
}
private void rm_r(File in) {
for(File f : in.listFiles()) {
if(f.isDirectory())
rm_r(f);
f.delete();
}
}
@Before public void setup() throws IOException, CSPDependencyException {
File tmp=new File(tmpdir());
File dir=new File(tmp,"ju-cspace");
if(dir.exists())
rm_r(dir);
if(!dir.exists())
dir.mkdir();
store=new FileStorage(dir.toString());
}
@Test public void writeJSONToFile() throws JSONException, ExistException, UnderlyingStorageException, UnimplementedException {
JSONObject jsonObject = new JSONObject(testStr);
store.autocreateJSON("/objects/", jsonObject);
}
@Test public void readJSONFromFile() throws JSONException, ExistException, UnderlyingStorageException, UnimplementedException {
JSONObject jsonObject = new JSONObject(testStr);
String path=store.autocreateJSON("/objects/", jsonObject);
JSONObject resultObj = store.retrieveJSON("/objects/"+path);
JSONObject testObj = new JSONObject(testStr);
assertTrue(JSONUtils.checkJSONEquiv(resultObj,testObj));
}
@Test public void testJSONNotExist() throws JSONException, UnderlyingStorageException, UnimplementedException {
try
{
store.retrieveJSON("nonesuch.json");
assertTrue(false);
}
catch (ExistException onfe) {}
}
@Test public void testJSONUpdate() throws ExistException, JSONException, UnderlyingStorageException, UnimplementedException {
JSONObject jsonObject = new JSONObject(testStr2);
String id1=store.autocreateJSON("/objects/", jsonObject);
jsonObject = new JSONObject(testStr);
store.updateJSON("/objects/"+id1, jsonObject);
JSONObject resultObj = store.retrieveJSON("/objects/"+id1);
JSONObject testObj = new JSONObject(testStr);
assertTrue(JSONUtils.checkJSONEquiv(resultObj,testObj));
}
@Test public void testJSONNoUpdateNonExisting() throws ExistException, JSONException, UnderlyingStorageException, UnimplementedException {
JSONObject jsonObject = new JSONObject(testStr);
try {
store.updateJSON("/objects/json1.test", jsonObject);
assertTrue(false);
} catch(ExistException e) {}
}
private File tmpSchemaFile(String type,boolean sj) {
File sroot=new File(store.getStoreRoot()+"/uispecs");
if(!sroot.exists())
sroot.mkdir();
File schema=new File(store.getStoreRoot()+"/uispecs/"+type);
if(!schema.exists())
schema.mkdir();
return new File(schema,sj?"uispec.json":"test-json-handle.tmp");
}
private void createSchemaFile(String type,boolean sj,boolean alt) throws IOException {
File file=tmpSchemaFile(type,sj);
FileOutputStream out=new FileOutputStream(file);
IOUtils.write(alt?testStr2:testStr,out);
out.close();
}
private void deleteSchemaFile(String type,boolean sj) {
File file=tmpSchemaFile(type,sj);
file.delete();
}
@Test public void testSchemaStore() throws IOException, JSONException {
SchemaStore schema=new StubSchemaStore(store.getStoreRoot());
createSchemaFile("collection-object",false,true);
JSONObject j=schema.getSchema("collection-object/test-json-handle.tmp");
JSONUtils.checkJSONEquiv(testStr2,j.toString());
deleteSchemaFile("collection-object",false);
}
@Test public void testDefaultingSchemaStore() throws IOException, JSONException {
SchemaStore schema=new StubSchemaStore(store.getStoreRoot());
createSchemaFile("collection-object",true,true);
JSONObject j=schema.getSchema("collection-object");
JSONUtils.checkJSONEquiv(testStr2,j.toString());
deleteSchemaFile("collection-object",true);
}
@Test public void testTrailingSlashOkayOnSchema() throws Exception {
SchemaStore schema=new StubSchemaStore(store.getStoreRoot());
createSchemaFile("collection-object",true,true);
JSONObject j=schema.getSchema("collection-object/");
JSONUtils.checkJSONEquiv(testStr2,j.toString());
deleteSchemaFile("collection-object",true);
}
private ServletTester setupJetty() throws Exception {
ServletTester tester=new ServletTester();
tester.setContextPath("/chain");
tester.addServlet(ChainServlet.class, "/*");
tester.addServlet("org.mortbay.jetty.servlet.DefaultServlet", "/");
tester.setAttribute("test-store",store.getStoreRoot());
tester.setAttribute("config-filename","default.xml");
tester.start();
return tester;
}
// XXX refactor
private HttpTester jettyDo(ServletTester tester,String method,String path,String data) throws IOException, Exception {
HttpTester request = new HttpTester();
HttpTester response = new HttpTester();
request.setMethod(method);
request.setHeader("Host","tester");
request.setURI(path);
request.setVersion("HTTP/1.0");
if(data!=null)
request.setContent(data);
response.parse(tester.getResponses(request.generate()));
return response;
}
@Test public void testJettyStartupWorks() throws Exception {
setupJetty();
}
private JSONObject makeRequest(JSONObject fields) throws JSONException {
JSONObject out=new JSONObject();
out.put("fields",fields);
return out;
}
private String makeSimpleRequest(String in) throws JSONException {
return makeRequest(new JSONObject(in)).toString();
}
@Test public void testAutoPost() throws Exception {
deleteSchemaFile("collection-object",false);
ServletTester jetty=setupJetty();
HttpTester out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(testStr2));
assertNotNull(out.getHeader("Location"));
assertTrue(out.getHeader("Location").startsWith("/objects/"));
Integer.parseInt(out.getHeader("Location").substring("/objects/".length()));
}
private String getFields(String in) throws JSONException {
return getFields(new JSONObject(in)).toString();
}
private JSONObject getFields(JSONObject in) throws JSONException {
in=in.getJSONObject("fields");
in.remove("csid");
return in;
}
@Test public void testUserProfiles() throws Exception {
log.info("1");
deleteSchemaFile("collection-object",false);
log.info("2");
ServletTester jetty=setupJetty();
log.info("3");
HttpTester out=jettyDo(jetty,"POST","/chain/users/",makeSimpleRequest(testStr6));
log.info("4");
assertEquals(out.getMethod(),null);
log.info("GET CREATE "+out.getContent());
String id=out.getHeader("Location");
log.info(out.getContent());
assertEquals(201,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
log.info("GET READ "+id+":"+out.getContent());
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr6)));
out=jettyDo(jetty,"PUT","/chain"+id,makeSimpleRequest(testStr7));
log.info("PUT "+id+":"+out.getContent());
assertEquals(200,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
log.info("GET READ "+id+":"+out.getContent());
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr7)));
out=jettyDo(jetty,"DELETE","/chain"+id,null);
assertEquals(200,out.getStatus());
log.info("DELETE "+id+":"+out.getContent());
out=jettyDo(jetty,"GET","/chain"+id,null);
assertTrue(out.getStatus()>=400); // XXX should probably be 404
}
@Test public void testPostAndDelete() throws Exception {
deleteSchemaFile("collection-object",false);
ServletTester jetty=setupJetty();
HttpTester out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(testStr2));
assertEquals(out.getMethod(),null);
String id=out.getHeader("Location");
assertEquals(201,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr2)));
out=jettyDo(jetty,"PUT","/chain"+id,makeSimpleRequest(testStr));
assertEquals(200,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr)));
out=jettyDo(jetty,"DELETE","/chain"+id,null);
assertEquals(200,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
assertTrue(out.getStatus()>=400); // XXX should probably be 404
}
@Test public void testMultipleStoreTypes() throws Exception {
deleteSchemaFile("collection-object",false);
ServletTester jetty=setupJetty();
HttpTester out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(testStr2));
assertEquals(out.getMethod(),null);
String id1=out.getHeader("Location");
log.info(out.getContent());
assertEquals(201,out.getStatus());
out=jettyDo(jetty,"POST","/chain/intake/",makeSimpleRequest(testStr));
assertEquals(out.getMethod(),null);
String id2=out.getHeader("Location");
log.info(out.getContent());
assertEquals(201,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id1,null);
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr2)));
out=jettyDo(jetty,"GET","/chain"+id2,null);
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr)));
out=jettyDo(jetty,"DELETE","/chain"+id1,null);
assertEquals(200,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id1,null);
assertTrue(out.getStatus()>=400); // XXX should probably be 404
out=jettyDo(jetty,"GET","/chain"+id2,null);
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr)));
}
@Test public void testServeStatic() throws Exception {
HttpTester out=jettyDo(setupJetty(),"GET","/chain/chain.properties",null);
assertEquals(200,out.getStatus());
assertTrue(out.getContent().contains("cspace.chain.store.dir"));
}
@Test public void testObjectList() throws Exception {
ServletTester jetty=setupJetty();
HttpTester out1=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(testStr2));
HttpTester out2=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(testStr2));
HttpTester out3=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(testStr2));
File storedir=new File(store.getStoreRoot(),"store");
if(!storedir.exists())
storedir.mkdir();
File junk=new File(storedir,"junk");
IOUtils.write("junk",new FileOutputStream(junk));
HttpTester out=jettyDo(jetty,"GET","/chain/objects",null);
assertEquals(200,out.getStatus());
JSONObject result=new JSONObject(out.getContent());
JSONArray items=result.getJSONArray("items");
Set<String> files=new HashSet<String>();
for(int i=0;i<items.length();i++)
files.add("/objects/"+items.getJSONObject(i).getString("csid"));
log.info(out1.getHeader("Location"));
assertTrue(files.contains(out1.getHeader("Location")));
assertTrue(files.contains(out2.getHeader("Location")));
assertTrue(files.contains(out3.getHeader("Location")));
assertEquals(3,files.size());
}
@Test public void testPutReturnsContent() throws Exception {
deleteSchemaFile("collection-object",false);
ServletTester jetty=setupJetty();
HttpTester out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(testStr2));
String id=out.getHeader("Location");
assertEquals(out.getMethod(),null);
log.info(out.getContent());
assertEquals(201,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr2)));
out=jettyDo(jetty,"PUT","/chain"+id,makeSimpleRequest(testStr));
assertEquals(200,out.getStatus());
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(testStr),new JSONObject(getFields(out.getContent()))));
}
@Test public void testTrailingSlashOkayOnList() throws Exception {
ServletTester jetty=setupJetty();
HttpTester out1=jettyDo(jetty,"POST","/chain/objects",makeSimpleRequest(testStr2));
HttpTester out2=jettyDo(jetty,"POST","/chain/objects",makeSimpleRequest(testStr2));
HttpTester out3=jettyDo(jetty,"POST","/chain/objects",makeSimpleRequest(testStr2));
HttpTester out=jettyDo(jetty,"GET","/chain/objects/",null);
assertEquals(200,out.getStatus());
JSONObject result=new JSONObject(out.getContent());
JSONArray items=result.getJSONArray("items");
Set<String> files=new HashSet<String>();
for(int i=0;i<items.length();i++)
files.add("/objects/"+items.getJSONObject(i).getString("csid"));
assertTrue(files.contains(out1.getHeader("Location")));
assertTrue(files.contains(out2.getHeader("Location")));
assertTrue(files.contains(out3.getHeader("Location")));
assertEquals(3,files.size());
}
@Test public void testDirectories() throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException {
JSONObject jsonObject = new JSONObject(testStr);
String id1=store.autocreateJSON("/a", jsonObject);
String id2=store.autocreateJSON("/b", jsonObject);
File d1=new File(store.getStoreRoot());
assertTrue(d1.exists());
File d2=new File(d1,"data");
assertTrue(d2.exists());
File a=new File(d2,"a");
assertTrue(a.exists());
File b=new File(d2,"b");
assertTrue(b.exists());
assertTrue(new File(a,id1+".json").exists());
assertTrue(new File(b,id2+".json").exists());
}
@Test public void testEmail(){
Boolean doIreallyWantToSpam = false; // set to true when you have configured the email addresses
/* please personalises these emails before sending - I don't want your spam. */
String from = "";
String[] recipients = { ""};
String SMTP_HOST_NAME = "localhost";
String SMTP_PORT = "25";
String message = "Hi, Test Message Contents";
String subject = "A test from collectionspace test suite";
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
boolean debug = true;
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
//props.put("mail.smtp.auth", "true");
props.put("mail.smtp.auth", "false");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props);
session.setDebug(debug);
Message msg = new MimeMessage(session);
InternetAddress addressFrom;
try {
addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
if(doIreallyWantToSpam){
Transport.send(msg);
assertTrue(doIreallyWantToSpam);
}
} catch (AddressException e) {
log.info(e.getMessage());
assertTrue(false);
} catch (MessagingException e) {
log.info(e.getMessage());
assertTrue(false);
}
//assertTrue(doIreallyWantToSpam);
}
}
| tomcat-main/src/test/java/org/collectionspace/chain/csp/persistence/file/TestGeneral.java | package org.collectionspace.chain.csp.persistence.file;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.security.Security;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.commons.io.IOUtils;
import org.collectionspace.chain.controller.ChainServlet;
import org.collectionspace.chain.csp.persistence.file.FileStorage;
import org.collectionspace.chain.csp.persistence.file.StubJSONStore;
import org.collectionspace.chain.csp.persistence.services.connection.RequestMethod;
import org.collectionspace.chain.csp.persistence.services.connection.ReturnedDocument;
import org.collectionspace.chain.csp.persistence.services.connection.ServicesConnection;
import org.collectionspace.chain.storage.UTF8SafeHttpTester;
import org.collectionspace.chain.uispec.SchemaStore;
import org.collectionspace.chain.uispec.StubSchemaStore;
import org.collectionspace.chain.util.json.JSONUtils;
import org.collectionspace.csp.api.core.CSPDependencyException;
import org.collectionspace.csp.api.persistence.ExistException;
import org.collectionspace.csp.api.persistence.UnderlyingStorageException;
import org.collectionspace.csp.api.persistence.UnimplementedException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.mortbay.jetty.testing.HttpTester;
import org.mortbay.jetty.testing.ServletTester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestGeneral {
private static final Logger log=LoggerFactory.getLogger(TestGeneral.class);
private final static String testStr = "{\"items\":[{\"value\":\"This is an experimental widget being tested. It will not do what you expect.\"," +
"\"title\":\"\",\"type\":\"caption\"},{\"title\":\"Your file\",\"type\":\"resource\",\"param\":\"file\"}," +
"{\"title\":\"Author\",\"type\":\"text\",\"param\":\"author\"},{\"title\":\"Title\",\"type\":\"text\"," +
"\"param\":\"title\"},{\"title\":\"Type\",\"type\":\"dropdown\",\"values\":[{\"value\":\"1\",\"text\":" +
"\"thesis\"},{\"value\":\"2\",\"text\":\"paper\"},{\"value\":\"3\",\"text\":\"excel-controlled\"}]," +
"\"param\":\"type\"}]}";
private final static String testStr2 = "{\"accessionNumber\":\"123\",\"a\":\"b\\\"\"}";
private final static String testStr3 = "{\"a\":\"b\",\"id\":\"***misc***\",\"objects\":\"***objects***\",\"intake\":\"***intake***\"}";
private final static String testStr4 = "{\"a\":\"b\",\"id\":\"MISC2009.1\",\"objects\":\"OBJ2009.1\",\"intake\":\"IN2009.1\"}";
private final static String testStr5 = "{\"a\":\"b\",\"id\":\"MISC2009.2\",\"objects\":\"OBJ2009.2\",\"intake\":\"IN2009.2\"}";
private final static String testStr6 = "{\"userId\": \"[email protected]\",\"userName\": \"[email protected]\",\"password\": \"testpassword\",\"email\": \"[email protected]\",\"status\": \"inactive\"}";
private final static String testStr7 = "{\"userId\": \"[email protected]\",\"screenName\": \"unittestzzz\",\"password\": \"testpassword\",\"email\": \"[email protected]\",\"status\": \"active\"}";
private final static String testStr8 = "{\"email\": \"[email protected]\", \"debug\" : true }";
private FileStorage store;
private static String tmp=null;
private static synchronized String tmpdir() {
if(tmp==null) {
tmp=System.getProperty("java.io.tmpdir");
}
return tmp;
}
private void rm_r(File in) {
for(File f : in.listFiles()) {
if(f.isDirectory())
rm_r(f);
f.delete();
}
}
@Before public void setup() throws IOException, CSPDependencyException {
File tmp=new File(tmpdir());
File dir=new File(tmp,"ju-cspace");
if(dir.exists())
rm_r(dir);
if(!dir.exists())
dir.mkdir();
store=new FileStorage(dir.toString());
}
@Test public void writeJSONToFile() throws JSONException, ExistException, UnderlyingStorageException, UnimplementedException {
JSONObject jsonObject = new JSONObject(testStr);
store.autocreateJSON("/objects/", jsonObject);
}
@Test public void readJSONFromFile() throws JSONException, ExistException, UnderlyingStorageException, UnimplementedException {
JSONObject jsonObject = new JSONObject(testStr);
String path=store.autocreateJSON("/objects/", jsonObject);
JSONObject resultObj = store.retrieveJSON("/objects/"+path);
JSONObject testObj = new JSONObject(testStr);
assertTrue(JSONUtils.checkJSONEquiv(resultObj,testObj));
}
@Test public void testJSONNotExist() throws JSONException, UnderlyingStorageException, UnimplementedException {
try
{
store.retrieveJSON("nonesuch.json");
assertTrue(false);
}
catch (ExistException onfe) {}
}
@Test public void testJSONUpdate() throws ExistException, JSONException, UnderlyingStorageException, UnimplementedException {
JSONObject jsonObject = new JSONObject(testStr2);
String id1=store.autocreateJSON("/objects/", jsonObject);
jsonObject = new JSONObject(testStr);
store.updateJSON("/objects/"+id1, jsonObject);
JSONObject resultObj = store.retrieveJSON("/objects/"+id1);
JSONObject testObj = new JSONObject(testStr);
assertTrue(JSONUtils.checkJSONEquiv(resultObj,testObj));
}
@Test public void testJSONNoUpdateNonExisting() throws ExistException, JSONException, UnderlyingStorageException, UnimplementedException {
JSONObject jsonObject = new JSONObject(testStr);
try {
store.updateJSON("/objects/json1.test", jsonObject);
assertTrue(false);
} catch(ExistException e) {}
}
private File tmpSchemaFile(String type,boolean sj) {
File sroot=new File(store.getStoreRoot()+"/uispecs");
if(!sroot.exists())
sroot.mkdir();
File schema=new File(store.getStoreRoot()+"/uispecs/"+type);
if(!schema.exists())
schema.mkdir();
return new File(schema,sj?"uispec.json":"test-json-handle.tmp");
}
private void createSchemaFile(String type,boolean sj,boolean alt) throws IOException {
File file=tmpSchemaFile(type,sj);
FileOutputStream out=new FileOutputStream(file);
IOUtils.write(alt?testStr2:testStr,out);
out.close();
}
private void deleteSchemaFile(String type,boolean sj) {
File file=tmpSchemaFile(type,sj);
file.delete();
}
@Test public void testSchemaStore() throws IOException, JSONException {
SchemaStore schema=new StubSchemaStore(store.getStoreRoot());
createSchemaFile("collection-object",false,true);
JSONObject j=schema.getSchema("collection-object/test-json-handle.tmp");
JSONUtils.checkJSONEquiv(testStr2,j.toString());
deleteSchemaFile("collection-object",false);
}
@Test public void testDefaultingSchemaStore() throws IOException, JSONException {
SchemaStore schema=new StubSchemaStore(store.getStoreRoot());
createSchemaFile("collection-object",true,true);
JSONObject j=schema.getSchema("collection-object");
JSONUtils.checkJSONEquiv(testStr2,j.toString());
deleteSchemaFile("collection-object",true);
}
@Test public void testTrailingSlashOkayOnSchema() throws Exception {
SchemaStore schema=new StubSchemaStore(store.getStoreRoot());
createSchemaFile("collection-object",true,true);
JSONObject j=schema.getSchema("collection-object/");
JSONUtils.checkJSONEquiv(testStr2,j.toString());
deleteSchemaFile("collection-object",true);
}
private ServletTester setupJetty() throws Exception {
ServletTester tester=new ServletTester();
tester.setContextPath("/chain");
tester.addServlet(ChainServlet.class, "/*");
tester.addServlet("org.mortbay.jetty.servlet.DefaultServlet", "/");
tester.setAttribute("test-store",store.getStoreRoot());
tester.setAttribute("config-filename","default.xml");
tester.start();
return tester;
}
// XXX refactor
private HttpTester jettyDo(ServletTester tester,String method,String path,String data) throws IOException, Exception {
HttpTester request = new HttpTester();
HttpTester response = new HttpTester();
request.setMethod(method);
request.setHeader("Host","tester");
request.setURI(path);
request.setVersion("HTTP/1.0");
if(data!=null)
request.setContent(data);
response.parse(tester.getResponses(request.generate()));
return response;
}
@Test public void testJettyStartupWorks() throws Exception {
setupJetty();
}
private JSONObject makeRequest(JSONObject fields) throws JSONException {
JSONObject out=new JSONObject();
out.put("fields",fields);
return out;
}
private String makeSimpleRequest(String in) throws JSONException {
return makeRequest(new JSONObject(in)).toString();
}
@Test public void testAutoPost() throws Exception {
deleteSchemaFile("collection-object",false);
ServletTester jetty=setupJetty();
HttpTester out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(testStr2));
assertNotNull(out.getHeader("Location"));
assertTrue(out.getHeader("Location").startsWith("/objects/"));
Integer.parseInt(out.getHeader("Location").substring("/objects/".length()));
}
private String getFields(String in) throws JSONException {
return getFields(new JSONObject(in)).toString();
}
private JSONObject getFields(JSONObject in) throws JSONException {
in=in.getJSONObject("fields");
in.remove("csid");
return in;
}
@Test public void testUserProfiles() throws Exception {
log.info("1");
deleteSchemaFile("collection-object",false);
log.info("2");
ServletTester jetty=setupJetty();
log.info("3");
HttpTester out=jettyDo(jetty,"POST","/chain/users/",makeSimpleRequest(testStr6));
log.info("4");
assertEquals(out.getMethod(),null);
log.info("GET CREATE "+out.getContent());
String id=out.getHeader("Location");
log.info(out.getContent());
assertEquals(201,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
log.info("GET READ "+id+":"+out.getContent());
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr6)));
out=jettyDo(jetty,"PUT","/chain"+id,makeSimpleRequest(testStr7));
log.info("PUT "+id+":"+out.getContent());
assertEquals(200,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
log.info("GET READ "+id+":"+out.getContent());
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr7)));
out=jettyDo(jetty,"DELETE","/chain"+id,null);
assertEquals(200,out.getStatus());
log.info("DELETE "+id+":"+out.getContent());
out=jettyDo(jetty,"GET","/chain"+id,null);
assertTrue(out.getStatus()>=400); // XXX should probably be 404
}
@Test public void testPostAndDelete() throws Exception {
deleteSchemaFile("collection-object",false);
ServletTester jetty=setupJetty();
HttpTester out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(testStr2));
assertEquals(out.getMethod(),null);
String id=out.getHeader("Location");
assertEquals(201,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr2)));
out=jettyDo(jetty,"PUT","/chain"+id,makeSimpleRequest(testStr));
assertEquals(200,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr)));
out=jettyDo(jetty,"DELETE","/chain"+id,null);
assertEquals(200,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
assertTrue(out.getStatus()>=400); // XXX should probably be 404
}
@Test public void testMultipleStoreTypes() throws Exception {
deleteSchemaFile("collection-object",false);
ServletTester jetty=setupJetty();
HttpTester out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(testStr2));
assertEquals(out.getMethod(),null);
String id1=out.getHeader("Location");
log.info(out.getContent());
assertEquals(201,out.getStatus());
out=jettyDo(jetty,"POST","/chain/intake/",makeSimpleRequest(testStr));
assertEquals(out.getMethod(),null);
String id2=out.getHeader("Location");
log.info(out.getContent());
assertEquals(201,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id1,null);
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr2)));
out=jettyDo(jetty,"GET","/chain"+id2,null);
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr)));
out=jettyDo(jetty,"DELETE","/chain"+id1,null);
assertEquals(200,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id1,null);
assertTrue(out.getStatus()>=400); // XXX should probably be 404
out=jettyDo(jetty,"GET","/chain"+id2,null);
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr)));
}
@Test public void testServeStatic() throws Exception {
HttpTester out=jettyDo(setupJetty(),"GET","/chain/chain.properties",null);
assertEquals(200,out.getStatus());
assertTrue(out.getContent().contains("cspace.chain.store.dir"));
}
@Test public void testObjectList() throws Exception {
ServletTester jetty=setupJetty();
HttpTester out1=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(testStr2));
HttpTester out2=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(testStr2));
HttpTester out3=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(testStr2));
File storedir=new File(store.getStoreRoot(),"store");
if(!storedir.exists())
storedir.mkdir();
File junk=new File(storedir,"junk");
IOUtils.write("junk",new FileOutputStream(junk));
HttpTester out=jettyDo(jetty,"GET","/chain/objects",null);
assertEquals(200,out.getStatus());
JSONObject result=new JSONObject(out.getContent());
JSONArray items=result.getJSONArray("items");
Set<String> files=new HashSet<String>();
for(int i=0;i<items.length();i++)
files.add("/objects/"+items.getJSONObject(i).getString("csid"));
log.info(out1.getHeader("Location"));
assertTrue(files.contains(out1.getHeader("Location")));
assertTrue(files.contains(out2.getHeader("Location")));
assertTrue(files.contains(out3.getHeader("Location")));
assertEquals(3,files.size());
}
@Test public void testPutReturnsContent() throws Exception {
deleteSchemaFile("collection-object",false);
ServletTester jetty=setupJetty();
HttpTester out=jettyDo(jetty,"POST","/chain/objects/",makeSimpleRequest(testStr2));
String id=out.getHeader("Location");
assertEquals(out.getMethod(),null);
log.info(out.getContent());
assertEquals(201,out.getStatus());
out=jettyDo(jetty,"GET","/chain"+id,null);
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(getFields(out.getContent())),new JSONObject(testStr2)));
out=jettyDo(jetty,"PUT","/chain"+id,makeSimpleRequest(testStr));
assertEquals(200,out.getStatus());
assertTrue(JSONUtils.checkJSONEquivOrEmptyStringKey(new JSONObject(testStr),new JSONObject(getFields(out.getContent()))));
}
@Test public void testTrailingSlashOkayOnList() throws Exception {
ServletTester jetty=setupJetty();
HttpTester out1=jettyDo(jetty,"POST","/chain/objects",makeSimpleRequest(testStr2));
HttpTester out2=jettyDo(jetty,"POST","/chain/objects",makeSimpleRequest(testStr2));
HttpTester out3=jettyDo(jetty,"POST","/chain/objects",makeSimpleRequest(testStr2));
HttpTester out=jettyDo(jetty,"GET","/chain/objects/",null);
assertEquals(200,out.getStatus());
JSONObject result=new JSONObject(out.getContent());
JSONArray items=result.getJSONArray("items");
Set<String> files=new HashSet<String>();
for(int i=0;i<items.length();i++)
files.add("/objects/"+items.getJSONObject(i).getString("csid"));
assertTrue(files.contains(out1.getHeader("Location")));
assertTrue(files.contains(out2.getHeader("Location")));
assertTrue(files.contains(out3.getHeader("Location")));
assertEquals(3,files.size());
}
@Test public void testDirectories() throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException {
JSONObject jsonObject = new JSONObject(testStr);
String id1=store.autocreateJSON("/a", jsonObject);
String id2=store.autocreateJSON("/b", jsonObject);
File d1=new File(store.getStoreRoot());
assertTrue(d1.exists());
File d2=new File(d1,"data");
assertTrue(d2.exists());
File a=new File(d2,"a");
assertTrue(a.exists());
File b=new File(d2,"b");
assertTrue(b.exists());
assertTrue(new File(a,id1+".json").exists());
assertTrue(new File(b,id2+".json").exists());
}
@Test public void testEmail(){
Boolean doIreallyWantToSpam = false; // set to true when you have configured the email addresses
/* please personalises these emails before sending - I don't want your spam. */
String from = "";
String[] recipients = { ""};
String SMTP_HOST_NAME = "localhost";
String SMTP_PORT = "25";
String message = "Hi, Test Message Contents";
String subject = "A test from collectionspace test suite";
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
boolean debug = true;
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
//props.put("mail.smtp.auth", "true");
props.put("mail.smtp.auth", "false");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props);
session.setDebug(debug);
Message msg = new MimeMessage(session);
InternetAddress addressFrom;
try {
addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
if(doIreallyWantToSpam){
Transport.send(msg);
}
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertTrue(doIreallyWantToSpam);
}
}
| NOJIRA fix test error
| tomcat-main/src/test/java/org/collectionspace/chain/csp/persistence/file/TestGeneral.java | NOJIRA fix test error | <ide><path>omcat-main/src/test/java/org/collectionspace/chain/csp/persistence/file/TestGeneral.java
<ide> msg.setContent(message, "text/plain");
<ide> if(doIreallyWantToSpam){
<ide> Transport.send(msg);
<add> assertTrue(doIreallyWantToSpam);
<ide> }
<ide> } catch (AddressException e) {
<del> // TODO Auto-generated catch block
<del> e.printStackTrace();
<add> log.info(e.getMessage());
<add> assertTrue(false);
<ide> } catch (MessagingException e) {
<del> // TODO Auto-generated catch block
<del> e.printStackTrace();
<add> log.info(e.getMessage());
<add> assertTrue(false);
<ide> }
<del> assertTrue(doIreallyWantToSpam);
<add> //assertTrue(doIreallyWantToSpam);
<ide> }
<ide> } |
|
JavaScript | apache-2.0 | 85700a0c2aa1e49fab26a9764613811874145218 | 0 | Saleslogix/argos-saleslogix,Saleslogix/argos-saleslogix,Saleslogix/argos-saleslogix,Saleslogix/argos-saleslogix | /* Copyright 2017 Infor
*
* 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 declare from 'dojo/_base/declare';
import domGeo from 'dojo/dom-geometry';
import connect from 'dojo/_base/connect';
import AttachmentManager from '../../AttachmentManager';
import Utility from '../../Utility';
import Detail from 'argos/Detail';
import _LegacySDataDetailMixin from 'argos/_LegacySDataDetailMixin';
import getResource from 'argos/I18n';
import ErrorManager from 'argos/ErrorManager';
const resource = getResource('attachmentView');
const dtFormatResource = getResource('attachmentViewDateTimeFormat');
/**
* @class crm.Views.Attachment.ViewAttachment
*
*
* @extends argos.Detail
* @mixins argos.Detail
* @mixins argos._LegacySDataDetailMixin
*
* @requires argos.Detail
* @requires argos._LegacySDataDetailMixin
*
* @requires crm.Format
* @requires crm.AttachmentManager
* @requires crm.Utility
*
*/
const __class = declare('crm.Views.Attachment.ViewAttachment', [Detail, _LegacySDataDetailMixin], {
// Localization
detailsText: resource.detailsText,
descriptionText: resource.descriptionText,
fileNameText: resource.fileNameText,
attachDateText: resource.attachDateText,
fileSizeText: resource.fileSizeText,
userText: resource.userText,
attachmentNotSupportedText: resource.attachmentNotSupportedText,
attachmentDateFormatText: dtFormatResource.attachmentDateFormatText,
attachmentDateFormatText24: dtFormatResource.attachmentDateFormatText24,
downloadingText: resource.downloadingText,
notSupportedText: resource.notSupportedText,
// View Properties
id: 'view_attachment',
editView: '',
security: null,
isTabbed: false,
querySelect: ['description', 'user', 'attachDate', 'fileSize', 'fileName', 'url', 'fileExists', 'remoteStatus', 'dataType'],
resourceKind: 'attachments',
contractName: 'system',
orginalImageSize: {
width: 0,
height: 0,
},
queryInclude: ['$descriptors'],
dataURL: null,
pdfDoc: null,
pdfTotalPages: 0,
pdfCurrentPage: 0,
pdfIsLoading: false,
pdfScale: 1,
notSupportedTemplate: new Simplate([
'<h2>{%= $$.notSupportedText %}</h2>',
]),
widgetTemplate: new Simplate([
'<div id="{%= $.id %}" data-title="{%= $.titleText %}" class="overthrow detail panel {%= $.cls %}" {% if ($.resourceKind) { %}data-resource-kind="{%= $.resourceKind %}"{% } %}>',
'{%! $.loadingTemplate %}',
'<div class="panel-content" data-dojo-attach-point="contentNode"></div>',
'<div class="attachment-viewer-content" data-dojo-attach-point="attachmentViewerNode"></div>',
'</div>',
]),
attachmentLoadingTemplate: new Simplate([
'<div class="list-loading-indicator">{%= $.loadingText %}</div>',
]),
attachmentViewTemplate: new Simplate([
'<div class="attachment-viewer-label" style="white-space:nowrap;">',
'<label>{%= $.description + " (" + $.fileType + ")" %}</label>',
'</div>',
'<div class="attachment-viewer-area">',
'<iframe id="attachment-Iframe" src="{%= $.url %}"></iframe>',
'</div>',
]),
pdfViewTemplate: new Simplate([
'<div class="pdf-controls">',
'<button type="button" class="first-page-button btn-icon">',
'<svg role="presentation" aria-hidden="true" focusable="false" class="icon">',
'<use xlink:href="#icon-first-page"></use>',
'</svg>',
'</button>',
'<button type="button" class="prev-button btn-icon">',
'<svg role="presentation" aria-hidden="true" focusable="false" class="icon">',
'<use xlink:href="#icon-previous-page"></use>',
'</svg>',
'</button>',
'<div class="page-stats"></div>',
'<button type="button" class="zoom-out btn-icon">',
'<svg role="presentation" aria-hidden="true" focusable="false" class="icon">',
'<use xlink:href="#icon-zoom-out"></use>',
'</svg>',
'</button>',
'<button type="button" class="zoom-in btn-icon">',
'<svg role="presentation" aria-hidden="true" focusable="false" class="icon">',
'<use xlink:href="#icon-zoom-in"></use>',
'</svg>',
'</button>',
'<button type="button" class="next-button btn-icon">',
'<svg role="presentation" aria-hidden="true" focusable="false" class="icon">',
'<use xlink:href="#icon-next-page"></use>',
'</svg>',
'</button>',
'<button type="button" class="last-page-button btn-icon">',
'<svg role="presentation" aria-hidden="true" focusable="false" class="icon">',
'<use xlink:href="#icon-last-page"></use>',
'</svg>',
'</button>',
'</div>',
'<div style="overflow-x:auto">',
'<canvas id="pdfViewer">',
'</canvas>',
'</div>',
]),
attachmentViewImageTemplate: new Simplate([
'<div class="attachment-viewer-label" style="white-space:nowrap;">',
'<label>{%= $.description + " (" + $.fileType + ")" %}</label>',
'</div>',
'<div class="attachment-viewer-area">',
'<table>',
'<tr valign="middle">',
'<td id="imagePlaceholder" align="center">',
'</td>',
'</tr>',
'</table>',
'</div>',
]),
attachmentViewNotSupportedTemplate: new Simplate([
'<div class="attachment-viewer-label">',
'<label>{%= $$.attachmentNotSupportedText %}</label>',
'</div>',
'<div class="attachment-viewer-not-supported">',
'<p class="listview-heading"><span>{%: $.description %} </span></p>',
'<p class="micro-text"><span>({%: crm.Format.date($.attachDate, (App.is24HourClock()) ? $$.attachmentDateFormatText24 : $$.attachmentDateFormatText) %}) </span>',
'<span>{%: crm.Format.fileSize($.fileSize) %} </span></p>',
'<p class="micro-text"><span>{%: crm.Utility.getFileExtension($.fileName) %} </span></p>',
'{% if($.user) { %}',
'<p class="micro-text"><span>{%: $.user.$descriptor %}</span></p>',
'{% } %}',
'</div>',
]),
downloadingTemplate: new Simplate([
'<li class="list-loading-indicator"><div>{%= $.downloadingText %}</div></li>',
]),
onTransitionTo: function onTransitionTo() {
const _renderFn = () => {
if (this.pdfDoc) {
this.pdfScale = 1;
this.renderPdfPage(this.pdfCurrentPage);
}
};
this._orientationHandle = connect.subscribe('/app/setOrientation', this, _renderFn);
$(window).on('resize', _renderFn);
},
show: function show(options) {
this.inherited(arguments);
this.attachmentViewerNode.innerHTML = '';
if (!App.supportsFileAPI()) {
$(this.domNode).empty().append(this.notSupportedTemplate.apply({}, this));
return;
}
// If this opened the second time we need to check to see if it is the same attachmnent and let the Process Entry function load the view.
if (this.entry) {
if (options.key === this.entry.$key) {
this._loadAttachmentView(this.entry);
}
}
},
processEntry: function processEntry(entry) {
this.inherited(arguments);
this._loadAttachmentView(entry);
},
createRequest: function createRequest() {
const request = this.inherited(arguments);
request.setQueryArg('_includeFile', 'false');
return request;
},
createEntryForDelete: function createEntryForDelete(e) {
const entry = {
$key: e.$key,
$etag: e.$etag,
$name: e.$name,
};
return entry;
},
createToolLayout: function createToolLayout() {
return this.tools;
},
createLayout: function createLayout() {
return this.tools || (this.tools = []);
},
setSrc: function setSrc(iframe, url) {
$(iframe).attr('src', url);
},
onFirstPageClick: function onFirstPageClick() {
if (this.pdfIsLoading) {
return;
}
this.renderPdfPage(1);
},
onPrevClick: function onPrevClick() {
if (this.pdfIsLoading) {
return;
}
this.renderPdfPage(this.pdfCurrentPage - 1);
},
onNextClick: function onNextClick() {
if (this.pdfIsLoading) {
return;
}
this.renderPdfPage(this.pdfCurrentPage + 1);
},
onLastPageClick: function onLastPageClick() {
if (this.pdfIsLoading) {
return;
}
this.renderPdfPage(this.pdfTotalPages);
},
onZoomOutClick: function onZoomOutClick() {
if (this.pdfIsLoading || this.pdfScale >= 1.5) {
return;
}
this.pdfScale += 0.25;
this.renderPdfPage(this.pdfCurrentPage);
},
onZoomInClick: function onZoomInClick() {
if (this.pdfIsLoading || this.pdfScale <= 0.25) {
return;
}
this.pdfScale -= 0.25;
this.renderPdfPage(this.pdfCurrentPage);
},
renderPdfPage: function renderPdfPage(pageNumber) {
if (pageNumber < 1 || this.pdfDoc === null) {
return;
}
if (pageNumber > this.pdfDoc.numPages) {
return;
}
if (this.pdfIsLoading) {
return;
}
const box = domGeo.getMarginBox(this.domNode);
this.pdfDoc.getPage(pageNumber).then((page) => {
const scale = this.pdfScale;
let viewport = page.getViewport(scale);
const canvas = document.getElementById('pdfViewer');
const context = canvas.getContext('2d');
const desiredWidth = box.w;
viewport = page.getViewport(desiredWidth / viewport.width);
canvas.height = viewport.height;
canvas.width = viewport.width;
const renderContext = {
canvasContext: context,
viewport,
};
this.pdfIsLoading = true;
const renderTask = page.render(renderContext);
renderTask.promise.then(() => {
this.pdfCurrentPage = pageNumber;
this.pdfIsLoading = false;
this.updatePageStats();
}, (reason) => {
this.pdfIsLoading = false;
const fileName = this.entry && this.entry.fileName;
const message = `Failed to render page ${pageNumber} for PDF "${fileName}".`;
console.error(message, reason); // eslint-disable-line
ErrorManager.addSimpleError(message, reason);
});
});
},
updatePageStats: function updatePageStats() {
if (!this.pdfDoc) {
return;
}
const node = $('.page-stats', this.attachmentViewerNode).first();
node.text(`${this.pdfCurrentPage} / ${this.pdfTotalPages}`);
},
loadPdfDocument: function loadPdfDocument(responseInfo) {
if (this.pdfDoc !== null) {
this.pdfDoc.destroy();
this.pdfDoc = null;
}
const dataResponse = Utility.base64ArrayBuffer(responseInfo.response);
const task = window.pdfjsLib.getDocument({ data: atob(dataResponse) });
this.pdfIsLoading = true;
task.promise.then((pdf) => {
this.pdfIsLoading = false;
this.pdfDoc = pdf;
this.pdfCurrentPage = 1;
this.pdfTotalPages = pdf.numPages;
this.renderPdfPage(1);
}, (reason) => {
this.pdfIsLoading = false;
const fileName = this.entry && this.entry.fileName;
const message = `The PDF "${fileName}" failed to load.`;
console.error(message, reason); // eslint-disable-line
ErrorManager.addSimpleError(message, reason);
});
},
_loadAttachmentView: function _loadAttachmentView(entry) {
const am = new AttachmentManager();
let description;
let isFile;
let fileType;
let loaded;
if (!entry.url) {
description = entry.description;
fileType = Utility.getFileExtension(entry.fileName);
isFile = true;
} else {
isFile = false;
description = `${entry.description} (${entry.url})`;
fileType = 'url';
}
const data = {
fileName: entry.fileName,
fileSize: entry.fileSize,
fileType,
url: '',
description,
};
if (isFile) {
fileType = Utility.getFileExtension(entry.fileName);
if (this._isfileTypeAllowed(fileType)) {
if (this._isfileTypeImage(fileType)) {
$(this.attachmentViewerNode).append(this.attachmentViewImageTemplate.apply(data, this));
const tpl = $(this.downloadingTemplate.apply(this));
$(this.attachmentViewerNode).prepend(tpl);
$(this.domNode).addClass('list-loading');
const self = this;
const attachmentid = entry.$key;
// dataurl
am.getAttachmentFile(attachmentid, 'arraybuffer', (responseInfo) => {
const rData = Utility.base64ArrayBuffer(responseInfo.response);
self.dataURL = `data:${responseInfo.contentType};base64,${rData}`;
const image = new Image();
const loadHandler = function loadHandler() {
if (loaded) {
return;
}
self._orginalImageSize = {
width: image.width,
height: image.height,
};
self._sizeImage(self.domNode, image);
$('#imagePlaceholder').empty().append(image);
loaded = true;
};
image.onload = loadHandler;
image.src = self.dataURL;
if (image.complete) {
loadHandler();
}
// Set download text to hidden
$(tpl).addClass('display-none');
});
} else { // View file type in Iframe
const attachmentid = entry.$key;
if (fileType === '.pdf') {
$(this.attachmentViewerNode).append(this.pdfViewTemplate.apply(data, this));
$('.prev-button', this.attachmentViewerNode).on('click', this.onPrevClick.bind(this));
$('.next-button', this.attachmentViewerNode).on('click', this.onNextClick.bind(this));
$('.first-page-button', this.attachmentViewerNode).on('click', this.onFirstPageClick.bind(this));
$('.last-page-button', this.attachmentViewerNode).on('click', this.onLastPageClick.bind(this));
$('.zoom-in', this.attachmentViewerNode).on('click', this.onZoomInClick.bind(this));
$('.zoom-out', this.attachmentViewerNode).on('click', this.onZoomOutClick.bind(this));
am.getAttachmentFile(attachmentid, 'arraybuffer', (responseInfo) => {
this.loadPdfDocument(responseInfo);
});
} else {
$(this.attachmentViewerNode).append(this.attachmentViewTemplate.apply(data, this));
const tpl = $(this.downloadingTemplate.apply(this));
$(this.attachmentViewerNode).prepend(tpl);
$(this.domNode).addClass('list-loading');
am.getAttachmentFile(attachmentid, 'arraybuffer', (responseInfo) => {
const rData = Utility.base64ArrayBuffer(responseInfo.response);
const dataUrl = `data:${responseInfo.contentType};base64,${rData}`;
$(tpl).addClass('display-none');
const iframe = document.getElementById('attachment-Iframe');
iframe.onload = function iframeOnLoad() {
$(tpl).addClass('display-none');
};
$(tpl).addClass('display-none');
this.setSrc(iframe, dataUrl);
});
}
}
} else { // File type not allowed
$(this.attachmentViewerNode).append(this.attachmentViewNotSupportedTemplate.apply(entry, this));
}
} else { // url Attachment
$(this.attachmentViewerNode).append(this.attachmentViewTemplate.apply(data, this));
const url = am.getAttachmenturlByEntity(entry);
$(this.domNode).addClass('list-loading');
const tpl = $(this.downloadingTemplate.apply(this));
$(this.attachmentViewerNode).prepend(tpl);
const iframe = document.getElementById('attachment-Iframe');
iframe.onload = function iframeOnLoad() {
$(tpl).addClass('display-none');
};
this.setSrc(iframe, url);
$(tpl).addClass('display-none');
}
},
_isfileTypeImage: function _isfileTypeImage(fileType) {
const fType = fileType.substr(fileType.lastIndexOf('.') + 1).toLowerCase();
let imageTypes;
if (App.imageFileTypes) {
imageTypes = App.imageFileTypes;
} else {
imageTypes = {
jpg: true,
gif: true,
png: true,
bmp: true,
tif: true,
};
}
if (imageTypes[fType]) {
return true;
}
return false;
},
_isfileTypeAllowed: function _isfileTypeAllowed(fileType) {
const fType = fileType.substr(fileType.lastIndexOf('.') + 1).toLowerCase();
let fileTypes;
if (App.nonViewableFileTypes) {
fileTypes = App.nonViewableFileTypes;
} else {
fileTypes = {
exe: true,
dll: true,
};
}
if (fileTypes[fType]) {
return false;
}
return true;
},
_viewImageOnly: function _viewImageOnly() {
return false;
},
_sizeImage: function _sizeImage(containerNode, image) {
const contentBox = $(containerNode).parent(); // hack to get parent dimensions since child containers occupy 0 height as they are not absolute anymore
const iH = image.height;
const iW = image.width;
let wH = contentBox.height();
let wW = contentBox.width();
let scale = 1;
if (wH > 200) {
wH = wH - 50;
}
if (wW > 200) {
wW = wW - 50;
}
if (wH < 50) {
wH = 100;
}
if (wW < 50) {
wW = 100;
}
// if the image is larger than the window
if (iW > wW && iH > wH) {
// if the window height is lager than the width
if (wH < wW) {
scale = 1 - ((iH - wH) / iH);
} else { // if the window width is lager than the height
scale = 1 - ((iW - wW) / iW);
}
} else if (iW > wW) { // if the image width is lager than the height
scale = 1 - ((iW - wW) / iW);
} else if (iH > wH) { // if the image height is lager than the width
scale = 1 - ((iH - wH) / iH);
} else {
// Image is samller than view
if (wH / iH > wW / iW) {
scale = 1 + ((wH - iH) / wH);
} else {
scale = 1 + ((wW - iW) / wW);
}
}
image.height = 0.90 * scale * iH;
image.width = 0.90 * scale * iW;
},
});
export default __class;
| src/Views/Attachment/ViewAttachment.js | /* Copyright 2017 Infor
*
* 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 declare from 'dojo/_base/declare';
import domGeo from 'dojo/dom-geometry';
import AttachmentManager from '../../AttachmentManager';
import Utility from '../../Utility';
import Detail from 'argos/Detail';
import _LegacySDataDetailMixin from 'argos/_LegacySDataDetailMixin';
import getResource from 'argos/I18n';
import ErrorManager from 'argos/ErrorManager';
const resource = getResource('attachmentView');
const dtFormatResource = getResource('attachmentViewDateTimeFormat');
/**
* @class crm.Views.Attachment.ViewAttachment
*
*
* @extends argos.Detail
* @mixins argos.Detail
* @mixins argos._LegacySDataDetailMixin
*
* @requires argos.Detail
* @requires argos._LegacySDataDetailMixin
*
* @requires crm.Format
* @requires crm.AttachmentManager
* @requires crm.Utility
*
*/
const __class = declare('crm.Views.Attachment.ViewAttachment', [Detail, _LegacySDataDetailMixin], {
// Localization
detailsText: resource.detailsText,
descriptionText: resource.descriptionText,
fileNameText: resource.fileNameText,
attachDateText: resource.attachDateText,
fileSizeText: resource.fileSizeText,
userText: resource.userText,
attachmentNotSupportedText: resource.attachmentNotSupportedText,
attachmentDateFormatText: dtFormatResource.attachmentDateFormatText,
attachmentDateFormatText24: dtFormatResource.attachmentDateFormatText24,
downloadingText: resource.downloadingText,
notSupportedText: resource.notSupportedText,
// View Properties
id: 'view_attachment',
editView: '',
security: null,
isTabbed: false,
querySelect: ['description', 'user', 'attachDate', 'fileSize', 'fileName', 'url', 'fileExists', 'remoteStatus', 'dataType'],
resourceKind: 'attachments',
contractName: 'system',
orginalImageSize: {
width: 0,
height: 0,
},
queryInclude: ['$descriptors'],
dataURL: null,
pdfDoc: null,
pdfTotalPages: 0,
pdfCurrentPage: 0,
pdfIsLoading: false,
notSupportedTemplate: new Simplate([
'<h2>{%= $$.notSupportedText %}</h2>',
]),
widgetTemplate: new Simplate([
'<div id="{%= $.id %}" data-title="{%= $.titleText %}" class="overthrow detail panel {%= $.cls %}" {% if ($.resourceKind) { %}data-resource-kind="{%= $.resourceKind %}"{% } %}>',
'{%! $.loadingTemplate %}',
'<div class="panel-content" data-dojo-attach-point="contentNode"></div>',
'<div class="attachment-viewer-content" data-dojo-attach-point="attachmentViewerNode"></div>',
'</div>',
]),
attachmentLoadingTemplate: new Simplate([
'<div class="list-loading-indicator">{%= $.loadingText %}</div>',
]),
attachmentViewTemplate: new Simplate([
'<div class="attachment-viewer-label" style="white-space:nowrap;">',
'<label>{%= $.description + " (" + $.fileType + ")" %}</label>',
'</div>',
'<div class="attachment-viewer-area">',
'<iframe id="attachment-Iframe" src="{%= $.url %}"></iframe>',
'</div>',
]),
pdfViewTemplate: new Simplate([
'<div class="pdf-controls">',
'<button type="button" class="first-page-button btn-icon">',
'<svg role="presentation" aria-hidden="true" focusable="false" class="icon">',
'<use xlink:href="#icon-first-page"></use>',
'</svg>',
'</button>',
'<button type="button" class="prev-button btn-icon">',
'<svg role="presentation" aria-hidden="true" focusable="false" class="icon">',
'<use xlink:href="#icon-previous-page"></use>',
'</svg>',
'</button>',
'<div class="page-stats"></div>',
'<button type="button" class="next-button btn-icon">',
'<svg role="presentation" aria-hidden="true" focusable="false" class="icon">',
'<use xlink:href="#icon-next-page"></use>',
'</svg>',
'</button>',
'<button type="button" class="last-page-button btn-icon">',
'<svg role="presentation" aria-hidden="true" focusable="false" class="icon">',
'<use xlink:href="#icon-last-page"></use>',
'</svg>',
'</button>',
'</div>',
'<canvas id="pdfViewer">',
'</canvas>',
]),
attachmentViewImageTemplate: new Simplate([
'<div class="attachment-viewer-label" style="white-space:nowrap;">',
'<label>{%= $.description + " (" + $.fileType + ")" %}</label>',
'</div>',
'<div class="attachment-viewer-area">',
'<table>',
'<tr valign="middle">',
'<td id="imagePlaceholder" align="center">',
'</td>',
'</tr>',
'</table>',
'</div>',
]),
attachmentViewNotSupportedTemplate: new Simplate([
'<div class="attachment-viewer-label">',
'<label>{%= $$.attachmentNotSupportedText %}</label>',
'</div>',
'<div class="attachment-viewer-not-supported">',
'<p class="listview-heading"><span>{%: $.description %} </span></p>',
'<p class="micro-text"><span>({%: crm.Format.date($.attachDate, (App.is24HourClock()) ? $$.attachmentDateFormatText24 : $$.attachmentDateFormatText) %}) </span>',
'<span>{%: crm.Format.fileSize($.fileSize) %} </span></p>',
'<p class="micro-text"><span>{%: crm.Utility.getFileExtension($.fileName) %} </span></p>',
'{% if($.user) { %}',
'<p class="micro-text"><span>{%: $.user.$descriptor %}</span></p>',
'{% } %}',
'</div>',
]),
downloadingTemplate: new Simplate([
'<li class="list-loading-indicator"><div>{%= $.downloadingText %}</div></li>',
]),
show: function show(options) {
this.inherited(arguments);
this.attachmentViewerNode.innerHTML = '';
if (!App.supportsFileAPI()) {
$(this.domNode).empty().append(this.notSupportedTemplate.apply({}, this));
return;
}
// If this opened the second time we need to check to see if it is the same attachmnent and let the Process Entry function load the view.
if (this.entry) {
if (options.key === this.entry.$key) {
this._loadAttachmentView(this.entry);
}
}
},
processEntry: function processEntry(entry) {
this.inherited(arguments);
this._loadAttachmentView(entry);
},
createRequest: function createRequest() {
const request = this.inherited(arguments);
request.setQueryArg('_includeFile', 'false');
return request;
},
createEntryForDelete: function createEntryForDelete(e) {
const entry = {
$key: e.$key,
$etag: e.$etag,
$name: e.$name,
};
return entry;
},
createToolLayout: function createToolLayout() {
return this.tools;
},
createLayout: function createLayout() {
return this.tools || (this.tools = []);
},
setSrc: function setSrc(iframe, url) {
$(iframe).attr('src', url);
},
onFirstPageClick: function onFirstPageClick() {
if (this.pdfIsLoading) {
return;
}
this.renderPdfPage(1);
},
onPrevClick: function onPrevClick() {
if (this.pdfIsLoading) {
return;
}
this.renderPdfPage(this.pdfCurrentPage - 1);
},
onNextClick: function onNextClick() {
if (this.pdfIsLoading) {
return;
}
this.renderPdfPage(this.pdfCurrentPage + 1);
},
onLastPageClick: function onLastPageClick() {
if (this.pdfIsLoading) {
return;
}
this.renderPdfPage(this.pdfTotalPages);
},
renderPdfPage: function renderPdfPage(pageNumber) {
if (pageNumber < 1 || this.pdfDoc === null) {
return;
}
if (pageNumber > this.pdfDoc.numPages) {
return;
}
if (this.pdfIsLoading) {
return;
}
const box = domGeo.getMarginBox(this.domNode);
this.pdfDoc.getPage(pageNumber).then((page) => {
const scale = 1;
let viewport = page.getViewport(scale);
const canvas = document.getElementById('pdfViewer');
const context = canvas.getContext('2d');
const desiredWidth = box.w;
viewport = page.getViewport(desiredWidth / viewport.width);
canvas.height = viewport.height;
canvas.width = viewport.width;
const renderContext = {
canvasContext: context,
viewport,
};
this.pdfIsLoading = true;
const renderTask = page.render(renderContext);
renderTask.promise.then(() => {
this.pdfCurrentPage = pageNumber;
this.pdfIsLoading = false;
this.updatePageStats();
}, (reason) => {
this.pdfIsLoading = false;
const fileName = this.entry && this.entry.fileName;
const message = `Failed to render page ${pageNumber} for PDF "${fileName}".`;
console.error(message, reason); // eslint-disable-line
ErrorManager.addSimpleError(message, reason);
});
});
},
updatePageStats: function updatePageStats() {
if (!this.pdfDoc) {
return;
}
const node = $('.page-stats', this.attachmentViewerNode).first();
node.text(`${this.pdfCurrentPage} / ${this.pdfTotalPages}`);
},
loadPdfDocument: function loadPdfDocument(responseInfo) {
if (this.pdfDoc !== null) {
this.pdfDoc.destroy();
this.pdfDoc = null;
}
const dataResponse = Utility.base64ArrayBuffer(responseInfo.response);
const task = window.pdfjsLib.getDocument({ data: atob(dataResponse) });
this.pdfIsLoading = true;
task.promise.then((pdf) => {
this.pdfIsLoading = false;
this.pdfDoc = pdf;
this.pdfCurrentPage = 1;
this.pdfTotalPages = pdf.numPages;
this.renderPdfPage(1);
}, (reason) => {
this.pdfIsLoading = false;
const fileName = this.entry && this.entry.fileName;
const message = `The PDF "${fileName}" failed to load.`;
console.error(message, reason); // eslint-disable-line
ErrorManager.addSimpleError(message, reason);
});
},
_loadAttachmentView: function _loadAttachmentView(entry) {
const am = new AttachmentManager();
let description;
let isFile;
let fileType;
let loaded;
if (!entry.url) {
description = entry.description;
fileType = Utility.getFileExtension(entry.fileName);
isFile = true;
} else {
isFile = false;
description = `${entry.description} (${entry.url})`;
fileType = 'url';
}
const data = {
fileName: entry.fileName,
fileSize: entry.fileSize,
fileType,
url: '',
description,
};
if (isFile) {
fileType = Utility.getFileExtension(entry.fileName);
if (this._isfileTypeAllowed(fileType)) {
if (this._isfileTypeImage(fileType)) {
$(this.attachmentViewerNode).append(this.attachmentViewImageTemplate.apply(data, this));
const tpl = $(this.downloadingTemplate.apply(this));
$(this.attachmentViewerNode).prepend(tpl);
$(this.domNode).addClass('list-loading');
const self = this;
const attachmentid = entry.$key;
// dataurl
am.getAttachmentFile(attachmentid, 'arraybuffer', (responseInfo) => {
const rData = Utility.base64ArrayBuffer(responseInfo.response);
self.dataURL = `data:${responseInfo.contentType};base64,${rData}`;
const image = new Image();
const loadHandler = function loadHandler() {
if (loaded) {
return;
}
self._orginalImageSize = {
width: image.width,
height: image.height,
};
self._sizeImage(self.domNode, image);
$('#imagePlaceholder').empty().append(image);
loaded = true;
};
image.onload = loadHandler;
image.src = self.dataURL;
if (image.complete) {
loadHandler();
}
// Set download text to hidden
$(tpl).addClass('display-none');
});
} else { // View file type in Iframe
const attachmentid = entry.$key;
if (fileType === '.pdf') {
$(this.attachmentViewerNode).append(this.pdfViewTemplate.apply(data, this));
$('.prev-button', this.attachmentViewerNode).on('click', this.onPrevClick.bind(this));
$('.next-button', this.attachmentViewerNode).on('click', this.onNextClick.bind(this));
$('.first-page-button', this.attachmentViewerNode).on('click', this.onFirstPageClick.bind(this));
$('.last-page-button', this.attachmentViewerNode).on('click', this.onLastPageClick.bind(this));
am.getAttachmentFile(attachmentid, 'arraybuffer', (responseInfo) => {
this.loadPdfDocument(responseInfo);
});
} else {
$(this.attachmentViewerNode).append(this.attachmentViewTemplate.apply(data, this));
const tpl = $(this.downloadingTemplate.apply(this));
$(this.attachmentViewerNode).prepend(tpl);
$(this.domNode).addClass('list-loading');
am.getAttachmentFile(attachmentid, 'arraybuffer', (responseInfo) => {
const rData = Utility.base64ArrayBuffer(responseInfo.response);
const dataUrl = `data:${responseInfo.contentType};base64,${rData}`;
$(tpl).addClass('display-none');
const iframe = document.getElementById('attachment-Iframe');
iframe.onload = function iframeOnLoad() {
$(tpl).addClass('display-none');
};
$(tpl).addClass('display-none');
this.setSrc(iframe, dataUrl);
});
}
}
} else { // File type not allowed
$(this.attachmentViewerNode).append(this.attachmentViewNotSupportedTemplate.apply(entry, this));
}
} else { // url Attachment
$(this.attachmentViewerNode).append(this.attachmentViewTemplate.apply(data, this));
const url = am.getAttachmenturlByEntity(entry);
$(this.domNode).addClass('list-loading');
const tpl = $(this.downloadingTemplate.apply(this));
$(this.attachmentViewerNode).prepend(tpl);
const iframe = document.getElementById('attachment-Iframe');
iframe.onload = function iframeOnLoad() {
$(tpl).addClass('display-none');
};
this.setSrc(iframe, url);
$(tpl).addClass('display-none');
}
},
_isfileTypeImage: function _isfileTypeImage(fileType) {
const fType = fileType.substr(fileType.lastIndexOf('.') + 1).toLowerCase();
let imageTypes;
if (App.imageFileTypes) {
imageTypes = App.imageFileTypes;
} else {
imageTypes = {
jpg: true,
gif: true,
png: true,
bmp: true,
tif: true,
};
}
if (imageTypes[fType]) {
return true;
}
return false;
},
_isfileTypeAllowed: function _isfileTypeAllowed(fileType) {
const fType = fileType.substr(fileType.lastIndexOf('.') + 1).toLowerCase();
let fileTypes;
if (App.nonViewableFileTypes) {
fileTypes = App.nonViewableFileTypes;
} else {
fileTypes = {
exe: true,
dll: true,
};
}
if (fileTypes[fType]) {
return false;
}
return true;
},
_viewImageOnly: function _viewImageOnly() {
return false;
},
_sizeImage: function _sizeImage(containerNode, image) {
const contentBox = $(containerNode).parent(); // hack to get parent dimensions since child containers occupy 0 height as they are not absolute anymore
const iH = image.height;
const iW = image.width;
let wH = contentBox.height();
let wW = contentBox.width();
let scale = 1;
if (wH > 200) {
wH = wH - 50;
}
if (wW > 200) {
wW = wW - 50;
}
if (wH < 50) {
wH = 100;
}
if (wW < 50) {
wW = 100;
}
// if the image is larger than the window
if (iW > wW && iH > wH) {
// if the window height is lager than the width
if (wH < wW) {
scale = 1 - ((iH - wH) / iH);
} else { // if the window width is lager than the height
scale = 1 - ((iW - wW) / iW);
}
} else if (iW > wW) { // if the image width is lager than the height
scale = 1 - ((iW - wW) / iW);
} else if (iH > wH) { // if the image height is lager than the width
scale = 1 - ((iH - wH) / iH);
} else {
// Image is samller than view
if (wH / iH > wW / iW) {
scale = 1 + ((wH - iH) / wH);
} else {
scale = 1 + ((wW - iW) / wW);
}
}
image.height = 0.90 * scale * iH;
image.width = 0.90 * scale * iW;
},
});
export default __class;
| INFORCRM-21841; INFORCRM-21839: Added zoom functionality to the PDF viewer, viewer now accounts for orientation shifts and window resizing
| src/Views/Attachment/ViewAttachment.js | INFORCRM-21841; INFORCRM-21839: Added zoom functionality to the PDF viewer, viewer now accounts for orientation shifts and window resizing | <ide><path>rc/Views/Attachment/ViewAttachment.js
<ide>
<ide> import declare from 'dojo/_base/declare';
<ide> import domGeo from 'dojo/dom-geometry';
<add>import connect from 'dojo/_base/connect';
<ide> import AttachmentManager from '../../AttachmentManager';
<ide> import Utility from '../../Utility';
<ide> import Detail from 'argos/Detail';
<ide> pdfTotalPages: 0,
<ide> pdfCurrentPage: 0,
<ide> pdfIsLoading: false,
<add> pdfScale: 1,
<ide> notSupportedTemplate: new Simplate([
<ide> '<h2>{%= $$.notSupportedText %}</h2>',
<ide> ]),
<ide> '</svg>',
<ide> '</button>',
<ide> '<div class="page-stats"></div>',
<add> '<button type="button" class="zoom-out btn-icon">',
<add> '<svg role="presentation" aria-hidden="true" focusable="false" class="icon">',
<add> '<use xlink:href="#icon-zoom-out"></use>',
<add> '</svg>',
<add> '</button>',
<add> '<button type="button" class="zoom-in btn-icon">',
<add> '<svg role="presentation" aria-hidden="true" focusable="false" class="icon">',
<add> '<use xlink:href="#icon-zoom-in"></use>',
<add> '</svg>',
<add> '</button>',
<ide> '<button type="button" class="next-button btn-icon">',
<ide> '<svg role="presentation" aria-hidden="true" focusable="false" class="icon">',
<ide> '<use xlink:href="#icon-next-page"></use>',
<ide> '</svg>',
<ide> '</button>',
<ide> '</div>',
<add> '<div style="overflow-x:auto">',
<ide> '<canvas id="pdfViewer">',
<ide> '</canvas>',
<add> '</div>',
<ide> ]),
<ide> attachmentViewImageTemplate: new Simplate([
<ide> '<div class="attachment-viewer-label" style="white-space:nowrap;">',
<ide> downloadingTemplate: new Simplate([
<ide> '<li class="list-loading-indicator"><div>{%= $.downloadingText %}</div></li>',
<ide> ]),
<add> onTransitionTo: function onTransitionTo() {
<add> const _renderFn = () => {
<add> if (this.pdfDoc) {
<add> this.pdfScale = 1;
<add> this.renderPdfPage(this.pdfCurrentPage);
<add> }
<add> };
<add>
<add> this._orientationHandle = connect.subscribe('/app/setOrientation', this, _renderFn);
<add> $(window).on('resize', _renderFn);
<add> },
<ide> show: function show(options) {
<ide> this.inherited(arguments);
<ide> this.attachmentViewerNode.innerHTML = '';
<ide>
<ide> this.renderPdfPage(this.pdfTotalPages);
<ide> },
<add> onZoomOutClick: function onZoomOutClick() {
<add> if (this.pdfIsLoading || this.pdfScale >= 1.5) {
<add> return;
<add> }
<add> this.pdfScale += 0.25;
<add> this.renderPdfPage(this.pdfCurrentPage);
<add> },
<add> onZoomInClick: function onZoomInClick() {
<add> if (this.pdfIsLoading || this.pdfScale <= 0.25) {
<add> return;
<add> }
<add> this.pdfScale -= 0.25;
<add> this.renderPdfPage(this.pdfCurrentPage);
<add> },
<ide> renderPdfPage: function renderPdfPage(pageNumber) {
<ide> if (pageNumber < 1 || this.pdfDoc === null) {
<ide> return;
<ide>
<ide> const box = domGeo.getMarginBox(this.domNode);
<ide> this.pdfDoc.getPage(pageNumber).then((page) => {
<del> const scale = 1;
<add> const scale = this.pdfScale;
<ide> let viewport = page.getViewport(scale);
<ide> const canvas = document.getElementById('pdfViewer');
<ide> const context = canvas.getContext('2d');
<ide> $('.next-button', this.attachmentViewerNode).on('click', this.onNextClick.bind(this));
<ide> $('.first-page-button', this.attachmentViewerNode).on('click', this.onFirstPageClick.bind(this));
<ide> $('.last-page-button', this.attachmentViewerNode).on('click', this.onLastPageClick.bind(this));
<add> $('.zoom-in', this.attachmentViewerNode).on('click', this.onZoomInClick.bind(this));
<add> $('.zoom-out', this.attachmentViewerNode).on('click', this.onZoomOutClick.bind(this));
<ide> am.getAttachmentFile(attachmentid, 'arraybuffer', (responseInfo) => {
<ide> this.loadPdfDocument(responseInfo);
<ide> }); |
|
JavaScript | mit | 4ab3fd9634d981e24d5cdf0d15c0139112133792 | 0 | prescottprue/react-redux-firebase,prescottprue/react-redux-firebase | import { capitalize } from 'lodash'
import { supportedAuthProviders, actionTypes } from '../constants'
/**
* @description Get correct login method and params order based on provided credentials
* @param {object} firebase - Internal firebase object
* @param {string} providerName - Name of Auth Provider (i.e. google, github, facebook, twitter)
* @param {Array|string} scopes - List of scopes to add to auth provider
* @returns {firebase.auth.AuthCredential} provider - Auth Provider
* @private
*/
function createAuthProvider(firebase, providerName, scopes) {
// TODO: Verify scopes are valid before adding
// TODO: Validate parameter inputs
if (providerName.toLowerCase() === 'microsoft.com') {
const provider = new firebase.auth.OAuthProvider('microsoft.com')
return provider
}
const capitalProviderName = `${capitalize(providerName)}AuthProvider`
// Throw if auth provider does not exist on Firebase instance
if (!firebase.auth[capitalProviderName]) {
throw new Error(
`${providerName} is not a valid auth provider for your firebase instance. If using react-native, use a RN specific auth library.`
)
}
const provider = new firebase.auth[capitalProviderName]()
// Custom Auth Parameters
// TODO: Validate parameter inputs
const { customAuthParameters } = firebase._.config
if (customAuthParameters && customAuthParameters[providerName]) {
provider.setCustomParameters(customAuthParameters[providerName])
}
// Handle providers without scopes
if (
providerName.toLowerCase() === 'twitter' ||
typeof provider.addScope !== 'function'
) {
return provider
}
// TODO: Verify scopes are valid before adding
provider.addScope('email')
if (scopes) {
if (Array.isArray(scopes)) {
scopes.forEach((scope) => {
provider.addScope(scope)
})
}
// Add single scope if it is a string
if (typeof scopes === 'string' || scopes instanceof String) {
provider.addScope(scopes)
}
}
return provider
}
/**
* Get correct login method and params order based on provided
* credentials
* @param {object} firebase - Internal firebase object
* @param {object} credentials - Login credentials
* @param {string} credentials.email - Email to login with (only needed for
* email login)
* @param {string} credentials.password - Password to login with (only needed
* for email login)
* @param {string} credentials.provider - Provider name such as google, twitter
* (only needed for 3rd party provider login)
* @param {string} credentials.type - Popup or redirect (only needed for 3rd
* party provider login)
* @param {string} credentials.token - Custom or provider token
* @param {firebase.auth.AuthCredential} credentials.credential - Custom or
* provider token
* @param {Array|string} credentials.scopes - Scopes to add to provider
* (i.e. email)
* @returns {object} Method and params for calling login
* @private
*/
export function getLoginMethodAndParams(firebase, credentials) {
const {
email,
password,
provider,
type,
token,
scopes,
phoneNumber,
applicationVerifier,
credential
} = credentials
// Credential Auth
if (credential) {
// Attempt to use signInAndRetrieveDataWithCredential if it exists (see #467 for more info)
const credentialAuth = firebase.auth().signInAndRetrieveDataWithCredential
if (credentialAuth) {
return {
method: 'signInAndRetrieveDataWithCredential',
params: [credential]
}
}
return { method: 'signInWithCredential', params: [credential] }
}
// Provider Auth
if (provider) {
// Verify providerName is valid
if (supportedAuthProviders.indexOf(provider.toLowerCase()) === -1) {
throw new Error(`${provider} is not a valid Auth Provider`)
}
if (token) {
throw new Error(
'provider with token no longer supported, use credential parameter instead'
)
}
const authProvider = createAuthProvider(firebase, provider, scopes)
if (type === 'popup') {
return { method: 'signInWithPopup', params: [authProvider] }
}
return { method: 'signInWithRedirect', params: [authProvider] }
}
// Token Auth
if (token) {
// Check for new sign in method (see #484 for more info)
const tokenAuth = firebase.auth().signInAndRetrieveDataWithCustomToken
if (tokenAuth) {
return { method: 'signInAndRetrieveDataWithCustomToken', params: [token] }
}
return { method: 'signInWithCustomToken', params: [token] }
}
// Phone Number Auth
if (phoneNumber) {
if (!applicationVerifier) {
throw new Error(
'Application verifier is required for phone authentication'
)
}
return {
method: 'signInWithPhoneNumber',
params: [phoneNumber, applicationVerifier]
}
}
// Check for new sign in method (see #484 for more info)
// Note: usage of signInAndRetrieveDataWithEmailAndPassword is now a fallback since it is deprecated (see #484 for more info)
if (!firebase.auth().signInWithEmailAndPassword) {
return {
method: 'signInAndRetrieveDataWithEmailAndPassword',
params: [email, password]
}
}
// Email/Password Auth
return { method: 'signInWithEmailAndPassword', params: [email, password] }
}
/**
* Get correct reauthenticate method and params order based on provided
* credentials
* @param {object} firebase - Internal firebase object
* @param {object} credentials - Login credentials
* @param {string} credentials.provider - Provider name such as google, twitter
* (only needed for 3rd party provider login)
* @param {string} credentials.type - Popup or redirect (only needed for 3rd
* party provider login)
* @param {firebase.auth.AuthCredential} credentials.credential - Custom or
* provider token
* @param {Array|string} credentials.scopes - Scopes to add to provider
* (i.e. email)
* @returns {object} Method and params for calling login
* @private
*/
export function getReauthenticateMethodAndParams(firebase, credentials) {
const {
provider,
type,
scopes,
phoneNumber,
applicationVerifier,
credential
} = credentials
// Credential Auth
if (credential) {
// Attempt to use signInAndRetrieveDataWithCredential if it exists (see #467 for more info)
const credentialAuth = firebase.auth()
.reauthenticateAndRetrieveDataWithCredential
if (credentialAuth) {
return {
method: 'reauthenticateAndRetrieveDataWithCredential',
params: [credential]
}
}
return { method: 'reauthenticateWithCredential', params: [credential] }
}
// Provider Auth
if (provider) {
// Verify providerName is valid
if (supportedAuthProviders.indexOf(provider.toLowerCase()) === -1) {
throw new Error(`${provider} is not a valid Auth Provider`)
}
const authProvider = createAuthProvider(firebase, provider, scopes)
if (type === 'popup') {
return { method: 'reauthenticateWithPopup', params: [authProvider] }
}
return { method: 'reauthenticateWithRedirect', params: [authProvider] }
}
// Phone Number Auth
if (!applicationVerifier) {
throw new Error('Application verifier is required for phone authentication')
}
return {
method: 'reauthenticateWithPhoneNumber',
params: [phoneNumber, applicationVerifier]
}
}
/**
* Returns a promise that completes when Firebase Auth is ready in the given
* store using react-redux-firebase.
* @param {object} store - The Redux store on which we want to detect if
* Firebase auth is ready.
* @param {string} [stateName='firebase'] - The attribute name of the
* react-redux-firebase reducer when using multiple combined reducers.
* 'firebase' by default. Set this to `null` to indicate that the
* react-redux-firebase reducer is not in a combined reducer.
* @returns {Promise} Resolves when Firebase auth is ready in the store.
*/
function isAuthReady(store, stateName) {
const state = store.getState()
const firebaseState = stateName ? state[stateName] : state
const firebaseAuthState = firebaseState && firebaseState.auth
if (!firebaseAuthState) {
throw new Error(
`The Firebase auth state could not be found in the store under the attribute '${
stateName ? `${stateName}.` : ''
}auth'. Make sure your react-redux-firebase reducer is correctly set in the store`
)
}
return firebaseState.auth.isLoaded
}
/**
* Returns a promise that completes when Firebase Auth is ready in the given
* store using react-redux-firebase.
* @param {object} store - The Redux store on which we want to detect if
* Firebase auth is ready.
* @param {string} [stateName='firebase'] - The attribute name of the react-redux-firebase
* reducer when using multiple combined reducers. 'firebase' by default. Set
* this to `null` to indicate that the react-redux-firebase reducer is not in a
* combined reducer.
* @returns {Promise} Resolve when Firebase auth is ready in the store.
*/
export function authIsReady(store, stateName = 'firebase') {
return new Promise((resolve) => {
if (isAuthReady(store, stateName)) {
resolve()
} else {
const unsubscribe = store.subscribe(() => {
if (isAuthReady(store, stateName)) {
unsubscribe()
resolve()
}
})
}
})
}
/**
* Function that creates and authIsReady promise
* @param {object} store - The Redux store on which we want to detect if
* Firebase auth is ready.
* @param {object} config - Config options for authIsReady
* @param {string} config.authIsReady - Config options for authIsReady
* @param {string} config.firebaseStateName - Config options for authIsReady
* @returns {Promise} Resolves when Firebase auth is ready in the store.
*/
export function createAuthIsReady(store, config) {
return typeof config.authIsReady === 'function'
? config.authIsReady(store, config)
: authIsReady(store, config.firebaseStateName)
}
/**
* Update profile data on Firebase Real Time Database
* @param {object} firebase - internal firebase object
* @param {object} profileUpdate - Updates to profile object
* @returns {Promise} Resolves with results of profile get
*/
export function updateProfileOnRTDB(firebase, profileUpdate) {
const {
_: { config, authUid }
} = firebase
const profileRef = firebase.database().ref(`${config.userProfile}/${authUid}`)
return profileRef.update(profileUpdate).then(() => profileRef.once('value'))
}
/**
* Update profile data on Firestore by calling set (with merge: true) on
* the profile.
* @param {object} firebase - internal firebase object
* @param {object} profileUpdate - Updates to profile object
* @param {object} options - Options object for configuring how profile
* update occurs
* @param {boolean} [options.useSet=true] - Use set with merge instead of
* update. Setting to `false` uses update (can cause issue if profile document
* does not exist).
* @param {boolean} [options.merge=true] - Whether or not to use merge when
* setting profile
* @returns {Promise} Resolves with results of profile get
*/
export function updateProfileOnFirestore(
firebase,
profileUpdate,
options = {}
) {
const { useSet = true, merge = true } = options
const {
firestore,
_: { config, authUid }
} = firebase
const profileRef = firestore().doc(`${config.userProfile}/${authUid}`)
// Use set with merge (to prevent "No document to update") unless otherwise
// specificed through options
const profileUpdatePromise = useSet
? profileRef.set(profileUpdate, { merge })
: profileRef.update(profileUpdate)
return profileUpdatePromise.then(() => profileRef.get())
}
/**
* Start presence management for a specificed user uid.
* Presence collection contains a list of users that are online currently.
* Sessions collection contains a record of all user sessions.
* This function is called within login functions if enablePresence: true.
* @param {Function} dispatch - Action dispatch function
* @param {object} firebase - Internal firebase object
* @private
*/
export function setupPresence(dispatch, firebase) {
// exit if database does not exist on firebase instance
if (!firebase.database || !firebase.database.ServerValue) {
return
}
const ref = firebase.database().ref()
const {
config: { presence, sessions },
authUid
} = firebase._
const amOnline = ref.child('.info/connected')
const onlineRef = ref
.child(
typeof presence === 'function'
? presence(firebase.auth().currentUser, firebase)
: presence
)
.child(authUid)
let sessionsRef =
typeof sessions === 'function'
? sessions(firebase.auth().currentUser, firebase)
: sessions
if (sessionsRef) {
sessionsRef = ref.child(sessions)
}
amOnline.on('value', (snapShot) => {
if (!snapShot.val()) return
// user is online
if (sessionsRef) {
// add session and set disconnect
dispatch({ type: actionTypes.SESSION_START, payload: authUid })
// add new session to sessions collection
const session = sessionsRef.push({
startedAt: firebase.database.ServerValue.TIMESTAMP,
user: authUid
})
// Support versions of react-native-firebase that do not have setPriority
// on firebase.database.ThenableReference
if (typeof session.setPriority === 'function') {
// set authUid as priority for easy sorting
session.setPriority(authUid)
}
session
.child('endedAt')
.onDisconnect()
.set(firebase.database.ServerValue.TIMESTAMP, () => {
dispatch({ type: actionTypes.SESSION_END })
})
}
// add correct session id to user
// remove from presence list
onlineRef.set(true)
onlineRef.onDisconnect().remove()
})
}
| src/utils/auth.js | import { capitalize } from 'lodash'
import { supportedAuthProviders, actionTypes } from '../constants'
/**
* @description Get correct login method and params order based on provided credentials
* @param {object} firebase - Internal firebase object
* @param {string} providerName - Name of Auth Provider (i.e. google, github, facebook, twitter)
* @param {Array|string} scopes - List of scopes to add to auth provider
* @returns {firebase.auth.AuthCredential} provider - Auth Provider
* @private
*/
function createAuthProvider(firebase, providerName, scopes) {
// TODO: Verify scopes are valid before adding
// TODO: Validate parameter inputs
if (providerName.toLowerCase() === 'microsoft.com') {
const provider = new firebase.auth.OAuthProvider('microsoft.com')
return provider
}
const capitalProviderName = `${capitalize(providerName)}AuthProvider`
// Throw if auth provider does not exist on Firebase instance
if (!firebase.auth[capitalProviderName]) {
throw new Error(
`${providerName} is not a valid auth provider for your firebase instance. If using react-native, use a RN specific auth library.`
)
}
const provider = new firebase.auth[capitalProviderName]()
// Custom Auth Parameters
// TODO: Validate parameter inputs
const { customAuthParameters } = firebase._.config
if (customAuthParameters && customAuthParameters[providerName]) {
provider.setCustomParameters(customAuthParameters[providerName])
}
// Handle providers without scopes
if (
providerName.toLowerCase() === 'twitter' ||
typeof provider.addScope !== 'function'
) {
return provider
}
// TODO: Verify scopes are valid before adding
provider.addScope('email')
if (scopes) {
if (Array.isArray(scopes)) {
scopes.forEach((scope) => {
provider.addScope(scope)
})
}
// Add single scope if it is a string
if (typeof scopes === 'string' || scopes instanceof String) {
provider.addScope(scopes)
}
}
return provider
}
/**
* Get correct login method and params order based on provided
* credentials
* @param {object} firebase - Internal firebase object
* @param {object} credentials - Login credentials
* @param {string} credentials.email - Email to login with (only needed for
* email login)
* @param {string} credentials.password - Password to login with (only needed
* for email login)
* @param {string} credentials.provider - Provider name such as google, twitter
* (only needed for 3rd party provider login)
* @param {string} credentials.type - Popup or redirect (only needed for 3rd
* party provider login)
* @param {string} credentials.token - Custom or provider token
* @param {firebase.auth.AuthCredential} credentials.credential - Custom or
* provider token
* @param {Array|string} credentials.scopes - Scopes to add to provider
* (i.e. email)
* @returns {object} Method and params for calling login
* @private
*/
export function getLoginMethodAndParams(firebase, credentials) {
const {
email,
password,
provider,
type,
token,
scopes,
phoneNumber,
applicationVerifier,
credential
} = credentials
// Credential Auth
if (credential) {
// Attempt to use signInAndRetrieveDataWithCredential if it exists (see #467 for more info)
const credentialAuth = firebase.auth().signInAndRetrieveDataWithCredential
if (credentialAuth) {
return {
method: 'signInAndRetrieveDataWithCredential',
params: [credential]
}
}
return { method: 'signInWithCredential', params: [credential] }
}
// Provider Auth
if (provider) {
// Verify providerName is valid
if (supportedAuthProviders.indexOf(provider.toLowerCase()) === -1) {
throw new Error(`${provider} is not a valid Auth Provider`)
}
if (token) {
throw new Error(
'provider with token no longer supported, use credential parameter instead'
)
}
const authProvider = createAuthProvider(firebase, provider, scopes)
if (type === 'popup') {
return { method: 'signInWithPopup', params: [authProvider] }
}
return { method: 'signInWithRedirect', params: [authProvider] }
}
// Token Auth
if (token) {
// Check for new sign in method (see #484 for more info)
const tokenAuth = firebase.auth().signInAndRetrieveDataWithCustomToken
if (tokenAuth) {
return { method: 'signInAndRetrieveDataWithCustomToken', params: [token] }
}
return { method: 'signInWithCustomToken', params: [token] }
}
// Phone Number Auth
if (phoneNumber) {
if (!applicationVerifier) {
throw new Error(
'Application verifier is required for phone authentication'
)
}
return {
method: 'signInWithPhoneNumber',
params: [phoneNumber, applicationVerifier]
}
}
// Check for new sign in method (see #484 for more info)
// Note: usage of signInAndRetrieveDataWithEmailAndPassword is now a fallback since it is deprecated (see #484 for more info)
if (!firebase.auth().signInWithEmailAndPassword) {
return {
method: 'signInAndRetrieveDataWithEmailAndPassword',
params: [email, password]
}
}
// Email/Password Auth
return { method: 'signInWithEmailAndPassword', params: [email, password] }
}
/**
* Get correct reauthenticate method and params order based on provided
* credentials
* @param {object} firebase - Internal firebase object
* @param {object} credentials - Login credentials
* @param {string} credentials.provider - Provider name such as google, twitter
* (only needed for 3rd party provider login)
* @param {string} credentials.type - Popup or redirect (only needed for 3rd
* party provider login)
* @param {firebase.auth.AuthCredential} credentials.credential - Custom or
* provider token
* @param {Array|string} credentials.scopes - Scopes to add to provider
* (i.e. email)
* @returns {object} Method and params for calling login
* @private
*/
export function getReauthenticateMethodAndParams(firebase, credentials) {
const {
provider,
type,
scopes,
phoneNumber,
applicationVerifier,
credential
} = credentials
// Credential Auth
if (credential) {
// Attempt to use signInAndRetrieveDataWithCredential if it exists (see #467 for more info)
const credentialAuth = firebase.auth()
.reauthenticateAndRetrieveDataWithCredential
if (credentialAuth) {
return {
method: 'reauthenticateAndRetrieveDataWithCredential',
params: [credential]
}
}
return { method: 'reauthenticateWithCredential', params: [credential] }
}
// Provider Auth
if (provider) {
// Verify providerName is valid
if (supportedAuthProviders.indexOf(provider.toLowerCase()) === -1) {
throw new Error(`${provider} is not a valid Auth Provider`)
}
const authProvider = createAuthProvider(firebase, provider, scopes)
if (type === 'popup') {
return { method: 'reauthenticateWithPopup', params: [authProvider] }
}
return { method: 'reauthenticateWithRedirect', params: [authProvider] }
}
// Phone Number Auth
if (!applicationVerifier) {
throw new Error('Application verifier is required for phone authentication')
}
return {
method: 'reauthenticateWithPhoneNumber',
params: [phoneNumber, applicationVerifier]
}
}
/**
* Returns a promise that completes when Firebase Auth is ready in the given
* store using react-redux-firebase.
* @param {object} store - The Redux store on which we want to detect if
* Firebase auth is ready.
* @param {string} [stateName='firebase'] - The attribute name of the
* react-redux-firebase reducer when using multiple combined reducers.
* 'firebase' by default. Set this to `null` to indicate that the
* react-redux-firebase reducer is not in a combined reducer.
* @returns {Promise} Resolves when Firebase auth is ready in the store.
*/
function isAuthReady(store, stateName) {
const state = store.getState()
const firebaseState = stateName ? state[stateName] : state
const firebaseAuthState = firebaseState && firebaseState.auth
if (!firebaseAuthState) {
throw new Error(
`The Firebase auth state could not be found in the store under the attribute '${
stateName ? `${stateName}.` : ''
}auth'. Make sure your react-redux-firebase reducer is correctly set in the store`
)
}
return firebaseState.auth.isLoaded
}
/**
* Returns a promise that completes when Firebase Auth is ready in the given
* store using react-redux-firebase.
* @param {object} store - The Redux store on which we want to detect if
* Firebase auth is ready.
* @param {string} [stateName='firebase'] - The attribute name of the react-redux-firebase
* reducer when using multiple combined reducers. 'firebase' by default. Set
* this to `null` to indicate that the react-redux-firebase reducer is not in a
* combined reducer.
* @returns {Promise} Resolve when Firebase auth is ready in the store.
*/
export function authIsReady(store, stateName = 'firebase') {
return new Promise((resolve) => {
if (isAuthReady(store, stateName)) {
resolve()
} else {
const unsubscribe = store.subscribe(() => {
if (isAuthReady(store, stateName)) {
unsubscribe()
resolve()
}
})
}
})
}
/**
* Function that creates and authIsReady promise
* @param {object} store - The Redux store on which we want to detect if
* Firebase auth is ready.
* @param {object} config - Config options for authIsReady
* @param {string} config.authIsReady - Config options for authIsReady
* @param {string} config.firebaseStateName - Config options for authIsReady
* @returns {Promise} Resolves when Firebase auth is ready in the store.
*/
export function createAuthIsReady(store, config) {
return typeof config.authIsReady === 'function'
? config.authIsReady(store, config)
: authIsReady(store, config.firebaseStateName)
}
/**
* Update profile data on Firebase Real Time Database
* @param {object} firebase - internal firebase object
* @param {object} profileUpdate - Updates to profile object
* @returns {Promise} Resolves with results of profile get
*/
export function updateProfileOnRTDB(firebase, profileUpdate) {
const {
_: { config, authUid }
} = firebase
const profileRef = firebase.database().ref(`${config.userProfile}/${authUid}`)
return profileRef.update(profileUpdate).then(() => profileRef.once('value'))
}
/**
* Update profile data on Firestore by calling set (with merge: true) on
* the profile.
* @param {object} firebase - internal firebase object
* @param {object} profileUpdate - Updates to profile object
* @param {object} options - Options object for configuring how profile
* update occurs
* @param {boolean} [options.useSet=true] - Use set with merge instead of
* update. Setting to `false` uses update (can cause issue of profile document
* does not exist).
* @param {boolean} [options.merge=true] - Whether or not to use merge when
* setting profile
* @returns {Promise} Resolves with results of profile get
*/
export function updateProfileOnFirestore(
firebase,
profileUpdate,
options = {}
) {
const { useSet = true, merge = true } = options
const {
firestore,
_: { config, authUid }
} = firebase
const profileRef = firestore().doc(`${config.userProfile}/${authUid}`)
// Use set with merge (to prevent "No document to update") unless otherwise
// specificed through options
const profileUpdatePromise = useSet
? profileRef.set(profileUpdate, { merge })
: profileRef.update(profileUpdate)
return profileUpdatePromise.then(() => profileRef.get())
}
/**
* Start presence management for a specificed user uid.
* Presence collection contains a list of users that are online currently.
* Sessions collection contains a record of all user sessions.
* This function is called within login functions if enablePresence: true.
* @param {Function} dispatch - Action dispatch function
* @param {object} firebase - Internal firebase object
* @private
*/
export function setupPresence(dispatch, firebase) {
// exit if database does not exist on firebase instance
if (!firebase.database || !firebase.database.ServerValue) {
return
}
const ref = firebase.database().ref()
const {
config: { presence, sessions },
authUid
} = firebase._
const amOnline = ref.child('.info/connected')
const onlineRef = ref
.child(
typeof presence === 'function'
? presence(firebase.auth().currentUser, firebase)
: presence
)
.child(authUid)
let sessionsRef =
typeof sessions === 'function'
? sessions(firebase.auth().currentUser, firebase)
: sessions
if (sessionsRef) {
sessionsRef = ref.child(sessions)
}
amOnline.on('value', (snapShot) => {
if (!snapShot.val()) return
// user is online
if (sessionsRef) {
// add session and set disconnect
dispatch({ type: actionTypes.SESSION_START, payload: authUid })
// add new session to sessions collection
const session = sessionsRef.push({
startedAt: firebase.database.ServerValue.TIMESTAMP,
user: authUid
})
// Support versions of react-native-firebase that do not have setPriority
// on firebase.database.ThenableReference
if (typeof session.setPriority === 'function') {
// set authUid as priority for easy sorting
session.setPriority(authUid)
}
session
.child('endedAt')
.onDisconnect()
.set(firebase.database.ServerValue.TIMESTAMP, () => {
dispatch({ type: actionTypes.SESSION_END })
})
}
// add correct session id to user
// remove from presence list
onlineRef.set(true)
onlineRef.onDisconnect().remove()
})
}
| fix(docs): correct wording of updateProfileOnRTDB param description (#929) - @gregfenton
| src/utils/auth.js | fix(docs): correct wording of updateProfileOnRTDB param description (#929) - @gregfenton | <ide><path>rc/utils/auth.js
<ide> * @param {object} options - Options object for configuring how profile
<ide> * update occurs
<ide> * @param {boolean} [options.useSet=true] - Use set with merge instead of
<del> * update. Setting to `false` uses update (can cause issue of profile document
<add> * update. Setting to `false` uses update (can cause issue if profile document
<ide> * does not exist).
<ide> * @param {boolean} [options.merge=true] - Whether or not to use merge when
<ide> * setting profile |
|
Java | apache-2.0 | 9da816e11e456093bd550a487a3ccfe9ebdc7fa1 | 0 | smrz10/joda-time,smrz10/joda-time,smrz10/joda-time,Guardiola31337/joda-time,smrz10/joda-time,Guardiola31337/joda-time,smrz10/joda-time | package org.joda.time;
import java.util.HashMap;
public class Pool {
private static Pool myInstance;
private HashMap<Integer, Object> instances;
private Pool() {
this.instances = new HashMap<Integer, Object>();
}
public static Pool getInstance() {
if (myInstance == null) {
myInstance = new Pool();
}
return myInstance;
}
private void add(int numeral, Days day) {
instances.put(new Integer(numeral), day);
}
public Object getInstance(int numeral){
Object instance = instances.get(new Integer(numeral));
if (instance == null) {
return null;
}
return instance;
}
public static Days getDays(int numeral) {
Pool pool = Pool.getInstance();
Object result = pool.getInstance(numeral);
if (result == null) {
result = new Days(numeral);
pool.add(numeral, (Days) result);
}
return (Days) result;
}
public static Minutes getMinutes(int numeral) {
Pool pool = Pool.getInstance();
Object result = pool.getInstance(numeral);
if (result == null) {
result = new Minutes(numeral);
pool.add(numeral, (Days) result);
}
return (Days) result;
}
}
| src/main/java/org/joda/time/Pool.java | package org.joda.time;
import java.util.HashMap;
public class Pool {
private static Pool myInstance;
private HashMap<Integer, Object> instances;
private Pool() {
this.instances = new HashMap<Integer, Object>();
}
public static Pool getInstance() {
if (myInstance == null) {
myInstance = new Pool();
}
return myInstance;
}
private void add(int numeral, Days day) {
instances.put(new Integer(numeral), day);
}
public Object getInstance(int numeral){
Object instance = instances.get(new Integer(numeral));
if (instance == null) {
return null;
}
return instance;
}
public static Days getDays(int numeral) {
Pool pool = Pool.getInstance();
Object result = pool.getInstance(numeral);
if (result == null) {
result = new Days(numeral);
pool.add(numeral, (Days) result);
}
return (Days) result;
}
public static Minutes getMinutes(int numeral) {
Pool pool = Pool.getInstance();
Object result = pool.getInstance(numeral);
if (result == null) {
result = new Days(numeral);
pool.add(numeral, (Days) result);
}
return (Days) result;
}
}
| snapshot at Mon Mar 9 12:11:42 CET 2015
| src/main/java/org/joda/time/Pool.java | snapshot at Mon Mar 9 12:11:42 CET 2015 | <ide><path>rc/main/java/org/joda/time/Pool.java
<ide> Object result = pool.getInstance(numeral);
<ide>
<ide> if (result == null) {
<del> result = new Days(numeral);
<add> result = new Minutes(numeral);
<ide> pool.add(numeral, (Days) result);
<ide> }
<ide> |
|
Java | apache-2.0 | 3353af57e4e86bf9be8f19014f1a6813838cf703 | 0 | psiinon/zap-extensions,thc202/zap-extensions,zaproxy/zap-extensions,zaproxy/zap-extensions,kingthorin/zap-extensions,thc202/zap-extensions,zapbot/zap-extensions,denniskniep/zap-extensions,kingthorin/zap-extensions,veggiespam/zap-extensions,thc202/zap-extensions,psiinon/zap-extensions,zapbot/zap-extensions,psiinon/zap-extensions,zapbot/zap-extensions,veggiespam/zap-extensions,kingthorin/zap-extensions,denniskniep/zap-extensions,veggiespam/zap-extensions,psiinon/zap-extensions,denniskniep/zap-extensions,thc202/zap-extensions,secdec/zap-extensions,secdec/zap-extensions,veggiespam/zap-extensions,zapbot/zap-extensions,secdec/zap-extensions,psiinon/zap-extensions,zaproxy/zap-extensions,secdec/zap-extensions,denniskniep/zap-extensions,secdec/zap-extensions,kingthorin/zap-extensions,zaproxy/zap-extensions,zaproxy/zap-extensions,zapbot/zap-extensions,thc202/zap-extensions,zaproxy/zap-extensions,denniskniep/zap-extensions,psiinon/zap-extensions,veggiespam/zap-extensions,denniskniep/zap-extensions,veggiespam/zap-extensions,kingthorin/zap-extensions,secdec/zap-extensions,zapbot/zap-extensions,secdec/zap-extensions,kingthorin/zap-extensions,thc202/zap-extensions | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2012 The ZAP development 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.
*/
package org.zaproxy.zap.extension.pscanrulesAlpha;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.htmlparser.jericho.Source;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.extension.pscan.PassiveScanThread;
import org.zaproxy.zap.extension.pscan.PluginPassiveScanner;
/**
* A class to passively scan response for application Source Code, using source code signatures
* @author [email protected]
*
*/
public class SourceCodeDisclosureScanner extends PluginPassiveScanner {
private PassiveScanThread parent = null;
/**
* a map of a regular expression pattern to the Programming language to which the pattern most likely corresponds
*/
static Map <Pattern, String> languagePatterns = new HashMap <Pattern, String> ();
static {
//PHP
languagePatterns.put(Pattern.compile("<\\?php\\s*.+?;\\s*\\?>", Pattern.MULTILINE | Pattern.DOTALL), "PHP");
//languagePatterns.put(Pattern.compile("phpinfo\\s*\\(\\s*\\)"), "PHP"); //features in "/index.php?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000", which is not a Source Code Disclosure issue.
languagePatterns.put(Pattern.compile("\\$_POST\\s*\\["), "PHP");
languagePatterns.put(Pattern.compile("\\$_GET\\s*\\["), "PHP");
//JSP (Java based)
languagePatterns.put(Pattern.compile("<%@\\s*page\\s+.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<%@\\s*include.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<%@\\s*taglib.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<jsp:directive\\.page.+?>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<jsp:directive\\.include.+?>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<jsp:directive\\.taglib.+?>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
//Servlet (Java based)
languagePatterns.put(Pattern.compile("import\\s+javax\\.servlet\\.http\\.HttpServlet\\s*;"), "Servlet");
languagePatterns.put(Pattern.compile("import\\s+javax\\.servlet\\.http\\.\\*\\s*;"), "Servlet");
languagePatterns.put(Pattern.compile("@WebServlet\\s*\\(\\s*\"/[a-z0-9]+\"\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
languagePatterns.put(Pattern.compile("public\\s+class\\s+[a-z0-9]+\\s+extends\\s+(javax\\.servlet\\.http\\.)?HttpServlet", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
languagePatterns.put(Pattern.compile("public\\s+void\\s+doGet\\s*\\(\\s*HttpServletRequest\\s+[a-z0-9]+\\s*,\\s*HttpServletResponse\\s+[a-z0-9]+\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
languagePatterns.put(Pattern.compile("public\\s+void\\s+doPost\\s*\\(\\s*HttpServletRequest\\s+[a-z0-9]+\\s*,\\s*HttpServletResponse\\s+[a-z0-9]+\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
//Java
languagePatterns.put(Pattern.compile("^package\\s+[a-z0-9.]+;", Pattern.CASE_INSENSITIVE), "Java");
languagePatterns.put(Pattern.compile("^import\\s+[a-z0-9.]+;", Pattern.CASE_INSENSITIVE), "Java");
languagePatterns.put(Pattern.compile("class\\s+[a-z0-9]+\\s*\\{.+\\}", Pattern.MULTILINE | Pattern.DOTALL ), "Java");
languagePatterns.put(Pattern.compile("public\\s+static\\s+void\\s+main\\s*\\(\\s*String\\s+[a-z0-9]+\\s*\\[\\s*\\]\\s*\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL), "Java");
languagePatterns.put(Pattern.compile("public\\s+static\\s+void\\s+main\\s*\\(\\s*String\\s*\\[\\s*\\]\\s*[a-z0-9]+\\s*\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Java");
//ASP
languagePatterns.put(Pattern.compile("On\\s*Error\\s*Resume\\s*Next", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("Server.CreateObject\\s*\\(\\s*\"[a-z0-9.]+\"\\s*\\)", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("Request.QueryString\\s*\\(\\s*\"[a-z0-9]+\"\\s*\\)", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("If\\s*\\(\\s*Err.Number\\s*.+\\)\\s*Then", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("<%@\\s+LANGUAGE\\s*=\\s*\"VBSCRIPT\"\\s*%>", Pattern.CASE_INSENSITIVE), "ASP");
//ASP.NET
languagePatterns.put(Pattern.compile("<%@\\s+Page.*?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<script\\s+runat\\s*=\\s*\"", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Assembly.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Control.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Implements.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%MasterType.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Master.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Page.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%OutputCache.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%PreviousPageType.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Reference.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Register.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@RenderPage\\s*\\(\\s*\".*?\"\\)", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@RenderBody\\s*\\(\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@RenderSection\\s*\\(\\s*\".+?\"\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
//languagePatterns.put(Pattern.compile("@\\{[\\u0000-\\u007F]{5,}?\\}", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET"); //Too many false positives
languagePatterns.put(Pattern.compile("@if\\s*\\(.+?\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("Request\\s*\\[\".+?\"\\]", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@foreach\\s*", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("Database.Open\\s*\\(\\s*\"", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("db.Query\\s*\\(\\s*\"", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@switch\\s*\\(.+?\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("^\\s*<asp:Menu"), "ASP.NET");
languagePatterns.put(Pattern.compile("^\\s*<asp:TreeView"), "ASP.NET");
languagePatterns.put(Pattern.compile("^\\s*<asp:SiteMapPath"), "ASP.NET");
//C#
languagePatterns.put(Pattern.compile("^<%@\\s+Page\\s+Language\\s*=\\s*\"C#\""), "C#");
languagePatterns.put(Pattern.compile("^using\\s+System\\s*;"), "C#");
languagePatterns.put(Pattern.compile("^namespace\\s+[a-z.]+\\s*\\{", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "C#");
languagePatterns.put(Pattern.compile("^static\\s+void\\s+Main\\s*\\(\\s*string\\s*\\[\\s*\\]\\s*[a-z0-9]+\\s*\\)", Pattern.MULTILINE ), "C#");
//generates false positives for JavaScript code, which also uses "var" to declare variables.
//languagePatterns.put(Pattern.compile("var\\s+[a-z]+?\\s*=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL), "C#");
languagePatterns.put(Pattern.compile("@for\\s*\\(\\s*var\\s+", Pattern.MULTILINE | Pattern.DOTALL), "C#");
languagePatterns.put(Pattern.compile("@foreach\\s*\\(\\s*var\\s+", Pattern.MULTILINE | Pattern.DOTALL), "C#");
//VB.NET
languagePatterns.put(Pattern.compile("^Imports\\s+System[a-zA-Z0-9.]*\\s*$"), "VB.NET");
languagePatterns.put(Pattern.compile("^dim\\s+[a-z0-9]+\\s*=", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
languagePatterns.put(Pattern.compile("@for\\s+[a-z0-9]+\\s*=\\s*[0-9]+\\s+to\\s+[0-9]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
languagePatterns.put(Pattern.compile("@for\\s+each\\s+[a-z0-9]+\\s+in\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
languagePatterns.put(Pattern.compile("@Select\\s+Case", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
languagePatterns.put(Pattern.compile("end\\s+select", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
//SQL (ie, generic Structured Query Language, not "Microsoft SQL Server", which some incorrectly refer to as just "SQL")
languagePatterns.put(Pattern.compile("select\\s+.+?\\s+from\\s+[a-z0-9.]+\\s+where\\s+", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("select\\s+@@[a-z]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("insert\\s+into\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("insert\\s+[a-z0-9._]+\\s+\\(.+?\\)\\s+values\\s*\\(.+?\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("insert\\s+[a-z0-9._]+\\s+values\\s*\\(.+?\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("insert\\s+[a-z0-9._]+\\s+select\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("update\\s+[a-z0-9._]+\\s+set\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("update\\s+[a-z0-9._]+\\s+[a-z0-9_]+\\s+set\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language"); //allow a table alias
languagePatterns.put(Pattern.compile("delete\\s+from\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
//causes false positives on normal JavaScript: delete B.fn;
//languagePatterns.put(Pattern.compile("delete\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("truncate\\s+table\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("create\\s+database\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("create\\s+table\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("create\\s+view\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("create\\s+index\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("create\\s+procedure\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("create\\s+function\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("drop\\s+database\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("drop\\s+table\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("drop\\s+view\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("drop\\s+index\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("drop\\s+procedure\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("drop\\s+function\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("grant\\s+[a-z]+\\s+on\\s+[a-z0-9._]+\\s+to\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("revoke\\s+[a-z]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
//Perl
languagePatterns.put(Pattern.compile("^#!/usr/bin/perl"), "Perl");
languagePatterns.put(Pattern.compile("^use\\s+strict\\s*;\\s*$"), "Perl");
languagePatterns.put(Pattern.compile("^use\\s+warnings\\s*;\\s*$"), "Perl");
languagePatterns.put(Pattern.compile("^use\\s+[A-Za-z:]+\\s*;\\s*$"), "Perl");
languagePatterns.put(Pattern.compile("foreach\\s+my\\s+\\$[a-z0-9]+\\s*\\(", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
//languagePatterns.put(Pattern.compile("next unless"), "Perl");
languagePatterns.put(Pattern.compile("^\\s*my\\s+\\$[a-z0-9]+\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("^\\s*my\\s+%[a-z0-9]+\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("^\\s*my\\s+@[a-z0-9]+\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("@[a-z0-9]+\\s+[a-z0-9]+\\s*=\\s*\\(", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("\\$#[a-z0-9]{4,}", Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("\\$[a-z0-9]+\\s*\\{'[a-z0-9]+'\\}\\s*=\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("die\\s+\".*?\\$!.*?\""), "Perl");
//Objective C (probably an iPhone app)
languagePatterns.put(Pattern.compile("^#\\s+import\\s+<[a-zA-Z0-9/.]+>"), "Objective C");
languagePatterns.put(Pattern.compile("^#\\s+import\\s+\"[a-zA-Z0-9/.]+\""), "Objective C");
languagePatterns.put(Pattern.compile("^\\[+[a-zA-Z0-9 :]\\]"), "Objective C");
languagePatterns.put(Pattern.compile("@interface\\s*[a-zA-Z0-9]+\\s*:\\s*[a-zA-Z0-9]+\\s*\\{"), "Objective C");
languagePatterns.put(Pattern.compile("\\+\\s*\\(\\s*[a-z]+\\s*\\)"), "Objective C");
languagePatterns.put(Pattern.compile("\\-\\s*\\(\\s*[a-z]+\\s*\\)"), "Objective C");
languagePatterns.put(Pattern.compile("@implementation\\s+[a-z]"), "Objective C");
languagePatterns.put(Pattern.compile("@interface\\s+[a-zA-Z0-9]+\\s*:\\s*[a-zA-Z0-9]+\\s*<[a-zA-Z0-9]+>"), "Objective C");
languagePatterns.put(Pattern.compile("@protocol\\s+[a-zA-Z0-9]+"), "Objective C");
//languagePatterns.put(Pattern.compile("@public"), "Objective C"); //prone to false positives
//languagePatterns.put(Pattern.compile("@private"), "Objective C"); //prone to false positives
//languagePatterns.put(Pattern.compile("@property"), "Objective C"); //prone to false positives
languagePatterns.put(Pattern.compile("@end\\s*$"), "Objective C"); //anchor to $ to reduce false positives in C++ code comments.
languagePatterns.put(Pattern.compile("@synthesize"), "Objective C");
//C
//do not anchor the start pf the # lines with ^. This causes the match to fail. Why??
languagePatterns.put(Pattern.compile("#include\\s+<[a-zA-Z0-9/]+\\.h>"), "C");
languagePatterns.put(Pattern.compile("#include\\s+\"[a-zA-Z0-9/]+\\.h\""), "C");
languagePatterns.put(Pattern.compile("#define\\s+.+?$"), "C");
languagePatterns.put(Pattern.compile("#ifndef\\s+.+?$"), "C");
languagePatterns.put(Pattern.compile("#endif\\s*$"), "C");
languagePatterns.put(Pattern.compile("\\s*char\\s*\\*\\*\\s*[a-zA-Z0-9_]+\\s*;"), "C");
//C++
languagePatterns.put(Pattern.compile("#include\\s+<iostream\\.h>"), "C++");
languagePatterns.put(Pattern.compile("^[a-z0-9]+::[a-z0-9]+\\s*\\(\\s*\\).*?\\{.+?\\}", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "C++"); //constructor
languagePatterns.put(Pattern.compile("(std::)?cout\\s*<<\\s*\".+?\"\\s*;"), "C++");
//Shell Script
languagePatterns.put(Pattern.compile("^#!/bin/[a-z]*sh"), "Shell Script");
//Python
languagePatterns.put(Pattern.compile("#!/usr/bin/python.*$"), "Python");
languagePatterns.put(Pattern.compile("#!/usr/bin/env\\s+python"), "Python");
languagePatterns.put(Pattern.compile("^\\s*def\\s+[a-z0-9]+\\s*\\(\\s*[a-z0-9]+\\s*\\)\\s*:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("\\s*for\\s+[a-z0-9]+\\s+in\\s+[a-z0-9]+:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("^\\s*try\\s*:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("^\\s*except\\s*:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("^\\s*def\\s+main\\s*\\(\\s*\\)\\s*:", Pattern.CASE_INSENSITIVE), "Python");
//Ruby
languagePatterns.put(Pattern.compile("^\\s*require\\s+\".+?\"\\s*$", Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("^\\s*describe\\s+[a-z0-9:]+\\s+do", Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("^\\s*class\\s+[a-z0-9]+\\s+<\\s*[a-z0-9:]+", Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("^\\s*def\\s+[a-z0-9]+\\s*.+?^\\s*end\\s*$", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("@@active\\s*=\\s*", Pattern.CASE_INSENSITIVE), "Ruby");
//Cold Fusion
languagePatterns.put(Pattern.compile("<cfoutput"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfset"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfexecute"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfexit"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfcomponent"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cffunction"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfreturn"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfargument"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfscript"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfloop"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfquery"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfqueryparam"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfdump"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfloop"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfif"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfelseif"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfelse"), "Cold Fusion");
languagePatterns.put(Pattern.compile("writeOutput\\s*\\("), "Cold Fusion");
languagePatterns.put(Pattern.compile("component\\s*\\{"), "Cold Fusion");
//Visual FoxPro / ActiveVFP
languagePatterns.put(Pattern.compile("oRequest\\.querystring\\s*\\(\\s*\"[a-z0-9]+\"\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("define\\s+class\\s+[a-z0-9]+\\s+as\\s+[a-z0-9]+", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("for\\s+[a-z0-9]+\\s*=\\s*[0-9]+\\s+to\\s+[0-9]+.+?\\s+endfor", Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("do\\s+while\\s+.+?\\s+enddo", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("if\\s+.+?\\s+endif", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("do\\s+case\\s+case\\s+.+?\\s+endcase", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("for\\s+each\\s+.+?\\s+endfor", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
//languagePatterns.put(Pattern.compile("oRequest"),"ActiveVFP"); //prone to false positives
//languagePatterns.put(Pattern.compile("oResponse"),"ActiveVFP"); //prone to false positives
//languagePatterns.put(Pattern.compile("oSession"),"ActiveVFP"); //prone to false positives
//Pascal
languagePatterns.put(Pattern.compile("^program\\s+[a-z0-9]+;.*?begin.+?end", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Pascal");
//Latex (yes, this is a programming language)
languagePatterns.put(Pattern.compile("\\documentclass\\s*\\{[a-z]+\\}", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Latex");
languagePatterns.put(Pattern.compile("\\begin\\s*\\{[a-z]+\\}", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Latex");
languagePatterns.put(Pattern.compile("\\end\\s*\\{[a-z]+\\}", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Latex");
//TODO: consider sorting the patterns by decreasing pattern length, so more specific patterns are tried before more general patterns
}
/**
* Prefix for internationalized messages used by this rule
*/
private static final String MESSAGE_PREFIX = "pscanalpha.sourcecodedisclosure.";
/**
* construct the class, and register for i18n
*/
public SourceCodeDisclosureScanner() {
super();
PscanUtils.registerI18N();
}
/**
* gets the name of the scanner
* @return
*/
@Override
public String getName() {
return Constant.messages.getString(MESSAGE_PREFIX + "name");
}
/**
* scans the HTTP request sent (in fact, does nothing)
* @param msg
* @param id
*/
@Override
public void scanHttpRequestSend(HttpMessage msg, int id) {
// do nothing
}
/**
* scans the HTTP response for Source Code signatures
* @param msg
* @param id
* @param source unused
*/
@Override
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {
//get the body contents as a String, so we can match against it
String responsebody = new String (msg.getResponseBody().getBytes());
//try each of the patterns in turn against the response.
//we deliberately do not assume that only status 200 responses will contain source code.
String evidence = null;
String programminglanguage = null;
Iterator<Pattern> patternIterator = languagePatterns.keySet().iterator();
while (patternIterator.hasNext()) {
Pattern languagePattern = patternIterator.next();
programminglanguage = languagePatterns.get(languagePattern);
Matcher matcher = languagePattern.matcher(responsebody);
if (matcher.find()) {
evidence = matcher.group();
break; //use the first match
}
}
if (evidence!=null && evidence.length() > 0) {
//we found something
Alert alert = new Alert(getId(), Alert.RISK_HIGH, Alert.WARNING, getName() + " - "+ programminglanguage );
alert.setDetail(
getDescription() + " - "+ programminglanguage,
msg.getRequestHeader().getURI().toString(),
"", //param
"", //attack
getExtraInfo(msg, evidence), //other info
getSolution(),
getReference(),
evidence,
540, //Information Exposure Through Source Code
34, //Predictable Resource Location (TODO: is this really the case here?)
msg);
parent.raiseAlert(id, alert);
}
}
/**
* sets the parent
* @param parent
*/
@Override
public void setParent(PassiveScanThread parent) {
this.parent = parent;
}
/**
* get the id of the scanner
* @return
*/
private int getId() {
return 10099;
}
/**
* get the description of the alert
* @return
*/
private String getDescription() {
return Constant.messages.getString(MESSAGE_PREFIX + "desc");
}
/**
* get the solution for the alert
* @return
*/
private String getSolution() {
return Constant.messages.getString(MESSAGE_PREFIX + "soln");
}
/**
* gets references for the alert
* @return
*/
private String getReference() {
return Constant.messages.getString(MESSAGE_PREFIX + "refs");
}
/**
* gets extra information associated with the alert
* @param msg
* @param arg0
* @return
*/
private String getExtraInfo(HttpMessage msg, String arg0) {
return Constant.messages.getString(MESSAGE_PREFIX + "extrainfo", arg0);
}
}
| src/org/zaproxy/zap/extension/pscanrulesAlpha/SourceCodeDisclosureScanner.java | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2012 The ZAP development 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.
*/
package org.zaproxy.zap.extension.pscanrulesAlpha;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.htmlparser.jericho.Source;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.extension.pscan.PassiveScanThread;
import org.zaproxy.zap.extension.pscan.PluginPassiveScanner;
/**
* A class to passively scan response for application Source Code, using source code signatures
* @author [email protected]
*
*/
public class SourceCodeDisclosureScanner extends PluginPassiveScanner {
private PassiveScanThread parent = null;
/**
* a map of a regular expression pattern to the Programming language to which the pattern most likely corresponds
*/
static Map <Pattern, String> languagePatterns = new HashMap <Pattern, String> ();
static {
//PHP
languagePatterns.put(Pattern.compile("<\\?php\\s*.+?;\\s*\\?>", Pattern.MULTILINE | Pattern.DOTALL), "PHP");
languagePatterns.put(Pattern.compile("phpinfo\\s*\\(\\s*\\)"), "PHP");
languagePatterns.put(Pattern.compile("\\$_POST\\s*\\["), "PHP");
languagePatterns.put(Pattern.compile("\\$_GET\\s*\\["), "PHP");
//JSP (Java based)
languagePatterns.put(Pattern.compile("<%@\\s*page\\s+.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<%@\\s*include.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<%@\\s*taglib.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<jsp:directive\\.page.+?>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<jsp:directive\\.include.+?>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
languagePatterns.put(Pattern.compile("<jsp:directive\\.taglib.+?>", Pattern.MULTILINE | Pattern.DOTALL), "JSP");
//Servlet (Java based)
languagePatterns.put(Pattern.compile("import\\s+javax\\.servlet\\.http\\.HttpServlet\\s*;"), "Servlet");
languagePatterns.put(Pattern.compile("import\\s+javax\\.servlet\\.http\\.\\*\\s*;"), "Servlet");
languagePatterns.put(Pattern.compile("@WebServlet\\s*\\(\\s*\"/[a-z0-9]+\"\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
languagePatterns.put(Pattern.compile("public\\s+class\\s+[a-z0-9]+\\s+extends\\s+(javax\\.servlet\\.http\\.)?HttpServlet", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
languagePatterns.put(Pattern.compile("public\\s+void\\s+doGet\\s*\\(\\s*HttpServletRequest\\s+[a-z0-9]+\\s*,\\s*HttpServletResponse\\s+[a-z0-9]+\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
languagePatterns.put(Pattern.compile("public\\s+void\\s+doPost\\s*\\(\\s*HttpServletRequest\\s+[a-z0-9]+\\s*,\\s*HttpServletResponse\\s+[a-z0-9]+\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Servlet");
//Java
languagePatterns.put(Pattern.compile("^package\\s+[a-z0-9.]+;", Pattern.CASE_INSENSITIVE), "Java");
languagePatterns.put(Pattern.compile("^import\\s+[a-z0-9.]+;", Pattern.CASE_INSENSITIVE), "Java");
languagePatterns.put(Pattern.compile("class\\s+[a-z0-9]+\\s*\\{.+\\}", Pattern.MULTILINE | Pattern.DOTALL ), "Java");
languagePatterns.put(Pattern.compile("public\\s+static\\s+void\\s+main\\s*\\(\\s*String\\s+[a-z0-9]+\\s*\\[\\s*\\]\\s*\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL), "Java");
languagePatterns.put(Pattern.compile("public\\s+static\\s+void\\s+main\\s*\\(\\s*String\\s*\\[\\s*\\]\\s*[a-z0-9]+\\s*\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Java");
//ASP
languagePatterns.put(Pattern.compile("On\\s*Error\\s*Resume\\s*Next", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("Server.CreateObject\\s*\\(\\s*\"[a-z0-9.]+\"\\s*\\)", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("Request.QueryString\\s*\\(\\s*\"[a-z0-9]+\"\\s*\\)", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("If\\s*\\(\\s*Err.Number\\s*.+\\)\\s*Then", Pattern.CASE_INSENSITIVE), "ASP");
languagePatterns.put(Pattern.compile("<%@\\s+LANGUAGE\\s*=\\s*\"VBSCRIPT\"\\s*%>", Pattern.CASE_INSENSITIVE), "ASP");
//ASP.NET
languagePatterns.put(Pattern.compile("<%@\\s+Page.*?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<script\\s+runat\\s*=\\s*\"", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Assembly.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Control.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Implements.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%MasterType.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Master.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Page.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%OutputCache.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%PreviousPageType.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Reference.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("<%Register.+?%>", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@RenderPage\\s*\\(\\s*\".*?\"\\)", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@RenderBody\\s*\\(\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@RenderSection\\s*\\(\\s*\".+?\"\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
//languagePatterns.put(Pattern.compile("@\\{[\\u0000-\\u007F]{5,}?\\}", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET"); //Too many false positives
languagePatterns.put(Pattern.compile("@if\\s*\\(.+?\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("Request\\s*\\[\".+?\"\\]", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@foreach\\s*", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("Database.Open\\s*\\(\\s*\"", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("db.Query\\s*\\(\\s*\"", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("@switch\\s*\\(.+?\\)\\s*\\{", Pattern.MULTILINE | Pattern.DOTALL), "ASP.NET");
languagePatterns.put(Pattern.compile("^\\s*<asp:Menu"), "ASP.NET");
languagePatterns.put(Pattern.compile("^\\s*<asp:TreeView"), "ASP.NET");
languagePatterns.put(Pattern.compile("^\\s*<asp:SiteMapPath"), "ASP.NET");
//C#
languagePatterns.put(Pattern.compile("^<%@\\s+Page\\s+Language\\s*=\\s*\"C#\""), "C#");
languagePatterns.put(Pattern.compile("^using\\s+System\\s*;"), "C#");
languagePatterns.put(Pattern.compile("^namespace\\s+[a-z.]+\\s*\\{", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "C#");
languagePatterns.put(Pattern.compile("^static\\s+void\\s+Main\\s*\\(\\s*string\\s*\\[\\s*\\]\\s*[a-z0-9]+\\s*\\)", Pattern.MULTILINE ), "C#");
//generates false positives for JavaScript code, which also uses "var" to declare variables.
//languagePatterns.put(Pattern.compile("var\\s+[a-z]+?\\s*=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL), "C#");
languagePatterns.put(Pattern.compile("@for\\s*\\(\\s*var\\s+", Pattern.MULTILINE | Pattern.DOTALL), "C#");
languagePatterns.put(Pattern.compile("@foreach\\s*\\(\\s*var\\s+", Pattern.MULTILINE | Pattern.DOTALL), "C#");
//VB.NET
languagePatterns.put(Pattern.compile("^Imports\\s+System[a-zA-Z0-9.]*\\s*$"), "VB.NET");
languagePatterns.put(Pattern.compile("^dim\\s+[a-z0-9]+\\s*=", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
languagePatterns.put(Pattern.compile("@for\\s+[a-z0-9]+\\s*=\\s*[0-9]+\\s+to\\s+[0-9]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
languagePatterns.put(Pattern.compile("@for\\s+each\\s+[a-z0-9]+\\s+in\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
languagePatterns.put(Pattern.compile("@Select\\s+Case", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
languagePatterns.put(Pattern.compile("end\\s+select", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "VB.NET");
//SQL (ie, generic Structured Query Language, not "Microsoft SQL Server", which some incorrectly refer to as just "SQL")
languagePatterns.put(Pattern.compile("select\\s+.+?\\s+from\\s+[a-z0-9.]+\\s+where\\s+", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("select\\s+@@[a-z]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("insert\\s+into\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("insert\\s+[a-z0-9._]+\\s+\\(.+?\\)\\s+values\\s*\\(.+?\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("insert\\s+[a-z0-9._]+\\s+values\\s*\\(.+?\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("insert\\s+[a-z0-9._]+\\s+select\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("update\\s+[a-z0-9._]+\\s+set\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("update\\s+[a-z0-9._]+\\s+[a-z0-9_]+\\s+set\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language"); //allow a table alias
languagePatterns.put(Pattern.compile("delete\\s+from\\s+[a-z0-9._]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
//causes false positives on normal JavaScript: delete B.fn;
//languagePatterns.put(Pattern.compile("delete\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("truncate\\s+table\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("create\\s+database\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("create\\s+table\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("create\\s+view\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("create\\s+index\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("create\\s+procedure\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("create\\s+function\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("drop\\s+database\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("drop\\s+table\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("drop\\s+view\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("drop\\s+index\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("drop\\s+procedure\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("drop\\s+function\\s+[a-z0-9.]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("grant\\s+[a-z]+\\s+on\\s+[a-z0-9._]+\\s+to\\s+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
languagePatterns.put(Pattern.compile("revoke\\s+[a-z]+", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Structured Query Language");
//Perl
languagePatterns.put(Pattern.compile("^#!/usr/bin/perl"), "Perl");
languagePatterns.put(Pattern.compile("^use\\s+strict\\s*;\\s*$"), "Perl");
languagePatterns.put(Pattern.compile("^use\\s+warnings\\s*;\\s*$"), "Perl");
languagePatterns.put(Pattern.compile("^use\\s+[A-Za-z:]+\\s*;\\s*$"), "Perl");
languagePatterns.put(Pattern.compile("foreach\\s+my\\s+\\$[a-z0-9]+\\s*\\(", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
//languagePatterns.put(Pattern.compile("next unless"), "Perl");
languagePatterns.put(Pattern.compile("^\\s*my\\s+\\$[a-z0-9]+\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("^\\s*my\\s+%[a-z0-9]+\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("^\\s*my\\s+@[a-z0-9]+\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("@[a-z0-9]+\\s+[a-z0-9]+\\s*=\\s*\\(", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("\\$#[a-z0-9]{4,}", Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("\\$[a-z0-9]+\\s*\\{'[a-z0-9]+'\\}\\s*=\\s*", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Perl");
languagePatterns.put(Pattern.compile("die\\s+\".*?\\$!.*?\""), "Perl");
//Objective C (probably an iPhone app)
languagePatterns.put(Pattern.compile("^#\\s+import\\s+<[a-zA-Z0-9/.]+>"), "Objective C");
languagePatterns.put(Pattern.compile("^#\\s+import\\s+\"[a-zA-Z0-9/.]+\""), "Objective C");
languagePatterns.put(Pattern.compile("^\\[+[a-zA-Z0-9 :]\\]"), "Objective C");
languagePatterns.put(Pattern.compile("@interface\\s*[a-zA-Z0-9]+\\s*:\\s*[a-zA-Z0-9]+\\s*\\{"), "Objective C");
languagePatterns.put(Pattern.compile("\\+\\s*\\(\\s*[a-z]+\\s*\\)"), "Objective C");
languagePatterns.put(Pattern.compile("\\-\\s*\\(\\s*[a-z]+\\s*\\)"), "Objective C");
languagePatterns.put(Pattern.compile("@implementation\\s+[a-z]"), "Objective C");
languagePatterns.put(Pattern.compile("@interface\\s+[a-zA-Z0-9]+\\s*:\\s*[a-zA-Z0-9]+\\s*<[a-zA-Z0-9]+>"), "Objective C");
languagePatterns.put(Pattern.compile("@protocol\\s+[a-zA-Z0-9]+"), "Objective C");
//languagePatterns.put(Pattern.compile("@public"), "Objective C"); //prone to false positives
//languagePatterns.put(Pattern.compile("@private"), "Objective C"); //prone to false positives
//languagePatterns.put(Pattern.compile("@property"), "Objective C"); //prone to false positives
languagePatterns.put(Pattern.compile("@end\\s*$"), "Objective C"); //anchor to $ to reduce false positives in C++ code comments.
languagePatterns.put(Pattern.compile("@synthesize"), "Objective C");
//C
//do not anchor the start pf the # lines with ^. This causes the match to fail. Why??
languagePatterns.put(Pattern.compile("#include\\s+<[a-zA-Z0-9/]+\\.h>"), "C");
languagePatterns.put(Pattern.compile("#include\\s+\"[a-zA-Z0-9/]+\\.h\""), "C");
languagePatterns.put(Pattern.compile("#define\\s+.+?$"), "C");
languagePatterns.put(Pattern.compile("#ifndef\\s+.+?$"), "C");
languagePatterns.put(Pattern.compile("#endif\\s*$"), "C");
languagePatterns.put(Pattern.compile("\\s*char\\s*\\*\\*\\s*[a-zA-Z0-9_]+\\s*;"), "C");
//C++
languagePatterns.put(Pattern.compile("#include\\s+<iostream\\.h>"), "C++");
languagePatterns.put(Pattern.compile("^[a-z0-9]+::[a-z0-9]+\\s*\\(\\s*\\).*?\\{.+?\\}", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "C++"); //constructor
languagePatterns.put(Pattern.compile("(std::)?cout\\s*<<\\s*\".+?\"\\s*;"), "C++");
//Shell Script
languagePatterns.put(Pattern.compile("^#!/bin/[a-z]*sh"), "Shell Script");
//Python
languagePatterns.put(Pattern.compile("#!/usr/bin/python.*$"), "Python");
languagePatterns.put(Pattern.compile("#!/usr/bin/env\\s+python"), "Python");
languagePatterns.put(Pattern.compile("^\\s*def\\s+[a-z0-9]+\\s*\\(\\s*[a-z0-9]+\\s*\\)\\s*:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("\\s*for\\s+[a-z0-9]+\\s+in\\s+[a-z0-9]+:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("^\\s*try\\s*:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("^\\s*except\\s*:", Pattern.CASE_INSENSITIVE), "Python");
languagePatterns.put(Pattern.compile("^\\s*def\\s+main\\s*\\(\\s*\\)\\s*:", Pattern.CASE_INSENSITIVE), "Python");
//Ruby
languagePatterns.put(Pattern.compile("^\\s*require\\s+\".+?\"\\s*$", Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("^\\s*describe\\s+[a-z0-9:]+\\s+do", Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("^\\s*class\\s+[a-z0-9]+\\s+<\\s*[a-z0-9:]+", Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("^\\s*def\\s+[a-z0-9]+\\s*.+?^\\s*end\\s*$", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Ruby");
languagePatterns.put(Pattern.compile("@@active\\s*=\\s*", Pattern.CASE_INSENSITIVE), "Ruby");
//Cold Fusion
languagePatterns.put(Pattern.compile("<cfoutput"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfset"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfexecute"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfexit"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfcomponent"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cffunction"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfreturn"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfargument"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfscript"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfloop"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfquery"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfqueryparam"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfdump"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfloop"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfif"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfelseif"), "Cold Fusion");
languagePatterns.put(Pattern.compile("<cfelse"), "Cold Fusion");
languagePatterns.put(Pattern.compile("writeOutput\\s*\\("), "Cold Fusion");
languagePatterns.put(Pattern.compile("component\\s*\\{"), "Cold Fusion");
//Visual FoxPro / ActiveVFP
languagePatterns.put(Pattern.compile("oRequest\\.querystring\\s*\\(\\s*\"[a-z0-9]+\"\\s*\\)", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("define\\s+class\\s+[a-z0-9]+\\s+as\\s+[a-z0-9]+", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("for\\s+[a-z0-9]+\\s*=\\s*[0-9]+\\s+to\\s+[0-9]+.+?\\s+endfor", Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("do\\s+while\\s+.+?\\s+enddo", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("if\\s+.+?\\s+endif", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("do\\s+case\\s+case\\s+.+?\\s+endcase", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
languagePatterns.put(Pattern.compile("for\\s+each\\s+.+?\\s+endfor", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE),"ActiveVFP");
//languagePatterns.put(Pattern.compile("oRequest"),"ActiveVFP"); //prone to false positives
//languagePatterns.put(Pattern.compile("oResponse"),"ActiveVFP"); //prone to false positives
//languagePatterns.put(Pattern.compile("oSession"),"ActiveVFP"); //prone to false positives
//Pascal
languagePatterns.put(Pattern.compile("^program\\s+[a-z0-9]+;.*?begin.+?end", Pattern.MULTILINE | Pattern.DOTALL | Pattern.CASE_INSENSITIVE), "Pascal");
//Latex (yes, this is a programming language)
languagePatterns.put(Pattern.compile("\\documentclass\\s*\\{[a-z]+\\}", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Latex");
languagePatterns.put(Pattern.compile("\\begin\\s*\\{[a-z]+\\}", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Latex");
languagePatterns.put(Pattern.compile("\\end\\s*\\{[a-z]+\\}", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE), "Latex");
//TODO: consider sorting the patterns by decreasing pattern length, so more specific patterns are tried before more general patterns
}
/**
* Prefix for internationalized messages used by this rule
*/
private static final String MESSAGE_PREFIX = "pscanalpha.sourcecodedisclosure.";
/**
* construct the class, and register for i18n
*/
public SourceCodeDisclosureScanner() {
super();
PscanUtils.registerI18N();
}
/**
* gets the name of the scanner
* @return
*/
@Override
public String getName() {
return Constant.messages.getString(MESSAGE_PREFIX + "name");
}
/**
* scans the HTTP request sent (in fact, does nothing)
* @param msg
* @param id
*/
@Override
public void scanHttpRequestSend(HttpMessage msg, int id) {
// do nothing
}
/**
* scans the HTTP response for Source Code signatures
* @param msg
* @param id
* @param source unused
*/
@Override
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {
//get the body contents as a String, so we can match against it
String responsebody = new String (msg.getResponseBody().getBytes());
//try each of the patterns in turn against the response.
//we deliberately do not assume that only status 200 responses will contain source code.
String evidence = null;
String programminglanguage = null;
Iterator<Pattern> patternIterator = languagePatterns.keySet().iterator();
while (patternIterator.hasNext()) {
Pattern languagePattern = patternIterator.next();
programminglanguage = languagePatterns.get(languagePattern);
Matcher matcher = languagePattern.matcher(responsebody);
if (matcher.find()) {
evidence = matcher.group();
break; //use the first match
}
}
if (evidence!=null && evidence.length() > 0) {
//we found something
Alert alert = new Alert(getId(), Alert.RISK_HIGH, Alert.WARNING, getName() + " - "+ programminglanguage );
alert.setDetail(
getDescription() + " - "+ programminglanguage,
msg.getRequestHeader().getURI().toString(),
"", //param
"", //attack
getExtraInfo(msg, evidence), //other info
getSolution(),
getReference(),
evidence,
540, //Information Exposure Through Source Code
34, //Predictable Resource Location (TODO: is this really the case here?)
msg);
parent.raiseAlert(id, alert);
}
}
/**
* sets the parent
* @param parent
*/
@Override
public void setParent(PassiveScanThread parent) {
this.parent = parent;
}
/**
* get the id of the scanner
* @return
*/
private int getId() {
return 10099;
}
/**
* get the description of the alert
* @return
*/
private String getDescription() {
return Constant.messages.getString(MESSAGE_PREFIX + "desc");
}
/**
* get the solution for the alert
* @return
*/
private String getSolution() {
return Constant.messages.getString(MESSAGE_PREFIX + "soln");
}
/**
* gets references for the alert
* @return
*/
private String getReference() {
return Constant.messages.getString(MESSAGE_PREFIX + "refs");
}
/**
* gets extra information associated with the alert
* @param msg
* @param arg0
* @return
*/
private String getExtraInfo(HttpMessage msg, String arg0) {
return Constant.messages.getString(MESSAGE_PREFIX + "extrainfo", arg0);
}
}
| Remove pattern that causes false positives on PHP. | src/org/zaproxy/zap/extension/pscanrulesAlpha/SourceCodeDisclosureScanner.java | Remove pattern that causes false positives on PHP. | <ide><path>rc/org/zaproxy/zap/extension/pscanrulesAlpha/SourceCodeDisclosureScanner.java
<ide> static {
<ide> //PHP
<ide> languagePatterns.put(Pattern.compile("<\\?php\\s*.+?;\\s*\\?>", Pattern.MULTILINE | Pattern.DOTALL), "PHP");
<del> languagePatterns.put(Pattern.compile("phpinfo\\s*\\(\\s*\\)"), "PHP");
<add> //languagePatterns.put(Pattern.compile("phpinfo\\s*\\(\\s*\\)"), "PHP"); //features in "/index.php?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000", which is not a Source Code Disclosure issue.
<ide> languagePatterns.put(Pattern.compile("\\$_POST\\s*\\["), "PHP");
<ide> languagePatterns.put(Pattern.compile("\\$_GET\\s*\\["), "PHP");
<ide> |
|
Java | mit | error: pathspec 'Java/TopCoder/BritishCoins.java' did not match any file(s) known to git
| 59cf87c172d41d1d8e7a2cd7532e492dc84f657d | 1 | dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey,dvt32/cpp-journey | // https://community.topcoder.com/stat?c=problem_statement&pm=1862
public class BritishCoins {
public static int[] coins(int pence) {
final int PENNIES_IN_SHILLING = 12;
final int SHILLINGS_IN_POUND = 20;
final int PENNIES_IN_POUND = PENNIES_IN_SHILLING * SHILLINGS_IN_POUND;
int pennyCount = 0;
int shillingCount = 0;
int poundCount = 0;
// Get pound count
while (pence >= PENNIES_IN_POUND) {
pence -= PENNIES_IN_POUND;
poundCount++;
}
// Get shilling count
while (pence >= PENNIES_IN_SHILLING) {
pence -= PENNIES_IN_SHILLING;
shillingCount++;
}
// Get penny count (equal to whatever is left in 'pence')
pennyCount = pence;
return new int[] { poundCount, shillingCount, pennyCount };
}
}
| Java/TopCoder/BritishCoins.java | Create BritishCoins.java | Java/TopCoder/BritishCoins.java | Create BritishCoins.java | <ide><path>ava/TopCoder/BritishCoins.java
<add>// https://community.topcoder.com/stat?c=problem_statement&pm=1862
<add>
<add>public class BritishCoins {
<add> public static int[] coins(int pence) {
<add> final int PENNIES_IN_SHILLING = 12;
<add> final int SHILLINGS_IN_POUND = 20;
<add> final int PENNIES_IN_POUND = PENNIES_IN_SHILLING * SHILLINGS_IN_POUND;
<add>
<add> int pennyCount = 0;
<add> int shillingCount = 0;
<add> int poundCount = 0;
<add>
<add> // Get pound count
<add> while (pence >= PENNIES_IN_POUND) {
<add> pence -= PENNIES_IN_POUND;
<add> poundCount++;
<add> }
<add>
<add> // Get shilling count
<add> while (pence >= PENNIES_IN_SHILLING) {
<add> pence -= PENNIES_IN_SHILLING;
<add> shillingCount++;
<add> }
<add>
<add> // Get penny count (equal to whatever is left in 'pence')
<add> pennyCount = pence;
<add>
<add> return new int[] { poundCount, shillingCount, pennyCount };
<add> }
<add>} |
|
Java | apache-2.0 | d68f53119eb1e1f9dbd02eddad58bf55a57ba0a2 | 0 | apache/lenya,apache/lenya,apache/lenya,apache/lenya | /*
* Copyright 1999-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.lenya.cms.cocoon.source;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.Serviceable;
import org.apache.cocoon.Constants;
import org.apache.cocoon.components.ContextHelper;
import org.apache.cocoon.environment.Context;
import org.apache.excalibur.source.Source;
import org.apache.excalibur.source.SourceFactory;
import org.apache.excalibur.source.SourceResolver;
import org.apache.excalibur.source.SourceUtil;
import org.apache.excalibur.source.URIAbsolutizer;
import org.apache.lenya.cms.publication.PageEnvelope;
import org.apache.lenya.cms.publication.PageEnvelopeFactory;
import org.apache.lenya.cms.publication.templating.ExistingSourceResolver;
import org.apache.lenya.cms.publication.templating.PublicationTemplateManager;
/**
* Source factory following the fallback principle.
*
* @version $Id:$
*/
public class FallbackSourceFactory extends AbstractLogEnabled implements SourceFactory,
Serviceable, Contextualizable, URIAbsolutizer {
/**
* Ctor.
*/
public FallbackSourceFactory() {
super();
}
/**
* @see org.apache.excalibur.source.SourceFactory#getSource(java.lang.String, java.util.Map)
*/
public Source getSource(final String location, Map parameters) throws IOException,
MalformedURLException {
String resolvedUri = null;
long startTime = new GregorianCalendar().getTimeInMillis();
// Remove the protocol and the first '//'
final int pos = location.indexOf("://");
if (pos == -1) {
throw new RuntimeException("The location [" + location
+ "] does not contain the string '://'");
}
final String path = location.substring(pos + 3);
if (path.length() == 0) {
throw new RuntimeException("The path after the protocol must not be empty!");
}
if (getLogger().isDebugEnabled()) {
getLogger().debug("Location: [" + location + "]");
getLogger().debug("Path: [" + path + "]");
}
PublicationTemplateManager templateManager = null;
SourceResolver sourceResolver = null;
Source source;
try {
templateManager = (PublicationTemplateManager) this.manager
.lookup(PublicationTemplateManager.ROLE);
Map objectModel = ContextHelper.getObjectModel(this.context);
PageEnvelope envelope = PageEnvelopeFactory.getInstance().getPageEnvelope(objectModel);
templateManager.setup(envelope.getPublication());
ExistingSourceResolver resolver = new ExistingSourceResolver();
templateManager.visit(path, resolver);
resolvedUri = resolver.getURI();
if (getLogger().isDebugEnabled()) {
getLogger().debug("Resolved URI: [" + resolvedUri + "]");
}
if (resolvedUri == null) {
final String contextUri = "context://" + location.substring("fallback://".length());
resolvedUri = contextUri;
}
sourceResolver = (SourceResolver) this.manager.lookup(SourceResolver.ROLE);
source = sourceResolver.resolveURI(resolvedUri);
} catch (Exception e) {
throw new RuntimeException("Resolving path [" + location + "] failed: ", e);
} finally {
if (templateManager != null) {
this.manager.release(templateManager);
}
if (sourceResolver != null) {
this.manager.release(sourceResolver);
}
}
if (getLogger().isDebugEnabled()) {
long endTime = new GregorianCalendar().getTimeInMillis();
long time = endTime - startTime;
getLogger()
.debug(
"Processing time: "
+ new SimpleDateFormat("hh:mm:ss.S").format(new Date(time)));
}
return source;
}
private org.apache.avalon.framework.context.Context context;
/** The environment context */
private Context envContext;
/** The ServiceManager */
private ServiceManager manager;
/**
* @see org.apache.avalon.framework.service.Serviceable#service(org.apache.avalon.framework.service.ServiceManager)
*/
public void service(ServiceManager manager) throws ServiceException {
this.manager = manager;
}
/**
* @see org.apache.avalon.framework.context.Contextualizable#contextualize(org.apache.avalon.framework.context.Context)
*/
public void contextualize(org.apache.avalon.framework.context.Context context)
throws ContextException {
this.envContext = (Context) context.get(Constants.CONTEXT_ENVIRONMENT_CONTEXT);
this.context = context;
}
/**
* @see org.apache.excalibur.source.SourceFactory#release(org.apache.excalibur.source.Source)
*/
public void release(Source source) {
// In fact, this method should never be called as this factory
// returns a source object from a different factory. So that
// factory should release the source
if (null != source) {
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug("Releasing source " + source.getURI());
}
SourceResolver resolver = null;
try {
resolver = (SourceResolver) this.manager.lookup(SourceResolver.ROLE);
resolver.release(source);
} catch (ServiceException ingore) {
} finally {
this.manager.release(resolver);
}
}
}
/**
* @see org.apache.excalibur.source.URIAbsolutizer#absolutize(java.lang.String,
* java.lang.String)
*/
public String absolutize(String baseURI, String location) {
return SourceUtil.absolutize(baseURI, location, true);
}
} | src/java/org/apache/lenya/cms/cocoon/source/FallbackSourceFactory.java | /*
* Copyright 1999-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.lenya.cms.cocoon.source;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.Serviceable;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.cocoon.Constants;
import org.apache.cocoon.components.ContextHelper;
import org.apache.cocoon.environment.Context;
import org.apache.excalibur.source.Source;
import org.apache.excalibur.source.SourceFactory;
import org.apache.excalibur.source.SourceResolver;
import org.apache.excalibur.source.SourceUtil;
import org.apache.excalibur.source.URIAbsolutizer;
import org.apache.lenya.cms.publication.PageEnvelope;
import org.apache.lenya.cms.publication.PageEnvelopeFactory;
import org.apache.lenya.cms.publication.templating.ExistingSourceResolver;
import org.apache.lenya.cms.publication.templating.PublicationTemplateManager;
/**
* Source factory following the fallback principle.
*
* @version $Id:$
*/
public class FallbackSourceFactory extends AbstractLogEnabled implements SourceFactory,
Serviceable, Contextualizable, ThreadSafe, URIAbsolutizer {
/**
* Ctor.
*/
public FallbackSourceFactory() {
super();
}
/**
* @see org.apache.excalibur.source.SourceFactory#getSource(java.lang.String, java.util.Map)
*/
public Source getSource(final String location, Map parameters) throws IOException,
MalformedURLException {
String resolvedUri = null;
long startTime = new GregorianCalendar().getTimeInMillis();
// Remove the protocol and the first '//'
final int pos = location.indexOf("://");
final String path = location.substring(pos + 1);
if (getLogger().isDebugEnabled()) {
getLogger().debug("Location: [" + location + "]");
getLogger().debug("Path: [" + location + "]");
}
SourceResolver sourceResolver = null;
Source source;
try {
PublicationTemplateManager templateManager = (PublicationTemplateManager) this.manager
.lookup(PublicationTemplateManager.ROLE);
Map objectModel = ContextHelper.getObjectModel(this.context);
PageEnvelope envelope = PageEnvelopeFactory.getInstance().getPageEnvelope(objectModel);
templateManager.setup(envelope.getPublication());
ExistingSourceResolver resolver = new ExistingSourceResolver();
templateManager.visit(path, resolver);
resolvedUri = resolver.getURI();
if (getLogger().isDebugEnabled()) {
getLogger().debug("Resolved URI: [" + resolvedUri + "]");
}
if (resolvedUri == null) {
final String contextUri = "context://" + location.substring("fallback://".length());
resolvedUri = contextUri;
}
sourceResolver = (SourceResolver) this.manager.lookup(SourceResolver.ROLE);
source = sourceResolver.resolveURI(resolvedUri);
} catch (Exception e) {
throw new RuntimeException("Resolving path [" + location + "] failed: ", e);
} finally {
if (sourceResolver != null) {
this.manager.release(sourceResolver);
}
}
if (getLogger().isDebugEnabled()) {
long endTime = new GregorianCalendar().getTimeInMillis();
long time = endTime - startTime;
getLogger().debug("Processing time: " + new SimpleDateFormat("hh:mm:ss.S").format(new Date(time)));
}
return source;
}
private org.apache.avalon.framework.context.Context context;
/** The environment context */
private Context envContext;
/** The ServiceManager */
private ServiceManager manager;
/**
* @see org.apache.avalon.framework.service.Serviceable#service(org.apache.avalon.framework.service.ServiceManager)
*/
public void service(ServiceManager manager) throws ServiceException {
this.manager = manager;
}
/**
* @see org.apache.avalon.framework.context.Contextualizable#contextualize(org.apache.avalon.framework.context.Context)
*/
public void contextualize(org.apache.avalon.framework.context.Context context)
throws ContextException {
this.envContext = (Context) context.get(Constants.CONTEXT_ENVIRONMENT_CONTEXT);
this.context = context;
}
/**
* @see org.apache.excalibur.source.SourceFactory#release(org.apache.excalibur.source.Source)
*/
public void release(Source source) {
// In fact, this method should never be called as this factory
// returns a source object from a different factory. So that
// factory should release the source
if (null != source) {
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug("Releasing source " + source.getURI());
}
SourceResolver resolver = null;
try {
resolver = (SourceResolver) this.manager.lookup(SourceResolver.ROLE);
resolver.release(source);
} catch (ServiceException ingore) {
} finally {
this.manager.release(resolver);
}
}
}
/**
* @see org.apache.excalibur.source.URIAbsolutizer#absolutize(java.lang.String,
* java.lang.String)
*/
public String absolutize(String baseURI, String location) {
return SourceUtil.absolutize(baseURI, location, true);
}
} | releasing template manager
git-svn-id: f6f45834fccde298d83fbef5743c9fd7982a26a3@46109 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/lenya/cms/cocoon/source/FallbackSourceFactory.java | releasing template manager | <ide><path>rc/java/org/apache/lenya/cms/cocoon/source/FallbackSourceFactory.java
<ide> import org.apache.avalon.framework.service.ServiceException;
<ide> import org.apache.avalon.framework.service.ServiceManager;
<ide> import org.apache.avalon.framework.service.Serviceable;
<del>import org.apache.avalon.framework.thread.ThreadSafe;
<ide> import org.apache.cocoon.Constants;
<ide> import org.apache.cocoon.components.ContextHelper;
<ide> import org.apache.cocoon.environment.Context;
<ide> * @version $Id:$
<ide> */
<ide> public class FallbackSourceFactory extends AbstractLogEnabled implements SourceFactory,
<del> Serviceable, Contextualizable, ThreadSafe, URIAbsolutizer {
<add> Serviceable, Contextualizable, URIAbsolutizer {
<ide>
<ide> /**
<ide> * Ctor.
<ide> */
<ide> public Source getSource(final String location, Map parameters) throws IOException,
<ide> MalformedURLException {
<add>
<ide> String resolvedUri = null;
<ide>
<ide> long startTime = new GregorianCalendar().getTimeInMillis();
<ide>
<ide> // Remove the protocol and the first '//'
<ide> final int pos = location.indexOf("://");
<del> final String path = location.substring(pos + 1);
<add>
<add> if (pos == -1) {
<add> throw new RuntimeException("The location [" + location
<add> + "] does not contain the string '://'");
<add> }
<add>
<add> final String path = location.substring(pos + 3);
<add>
<add> if (path.length() == 0) {
<add> throw new RuntimeException("The path after the protocol must not be empty!");
<add> }
<ide>
<ide> if (getLogger().isDebugEnabled()) {
<ide> getLogger().debug("Location: [" + location + "]");
<del> getLogger().debug("Path: [" + location + "]");
<add> getLogger().debug("Path: [" + path + "]");
<ide> }
<ide>
<add> PublicationTemplateManager templateManager = null;
<ide> SourceResolver sourceResolver = null;
<ide> Source source;
<ide> try {
<del> PublicationTemplateManager templateManager = (PublicationTemplateManager) this.manager
<add> templateManager = (PublicationTemplateManager) this.manager
<ide> .lookup(PublicationTemplateManager.ROLE);
<ide> Map objectModel = ContextHelper.getObjectModel(this.context);
<ide> PageEnvelope envelope = PageEnvelopeFactory.getInstance().getPageEnvelope(objectModel);
<ide> ExistingSourceResolver resolver = new ExistingSourceResolver();
<ide> templateManager.visit(path, resolver);
<ide> resolvedUri = resolver.getURI();
<del>
<add>
<ide> if (getLogger().isDebugEnabled()) {
<ide> getLogger().debug("Resolved URI: [" + resolvedUri + "]");
<ide> }
<del>
<add>
<ide> if (resolvedUri == null) {
<ide> final String contextUri = "context://" + location.substring("fallback://".length());
<ide> resolvedUri = contextUri;
<ide> }
<del>
<add>
<ide> sourceResolver = (SourceResolver) this.manager.lookup(SourceResolver.ROLE);
<ide> source = sourceResolver.resolveURI(resolvedUri);
<ide>
<ide> } catch (Exception e) {
<ide> throw new RuntimeException("Resolving path [" + location + "] failed: ", e);
<ide> } finally {
<add> if (templateManager != null) {
<add> this.manager.release(templateManager);
<add> }
<ide> if (sourceResolver != null) {
<ide> this.manager.release(sourceResolver);
<ide> }
<ide> if (getLogger().isDebugEnabled()) {
<ide> long endTime = new GregorianCalendar().getTimeInMillis();
<ide> long time = endTime - startTime;
<del> getLogger().debug("Processing time: " + new SimpleDateFormat("hh:mm:ss.S").format(new Date(time)));
<add> getLogger()
<add> .debug(
<add> "Processing time: "
<add> + new SimpleDateFormat("hh:mm:ss.S").format(new Date(time)));
<ide> }
<ide>
<ide> return source; |
|
Java | apache-2.0 | 1a3497e33a9354ddfae82017702fa83b9bffdb1a | 0 | geothomasp/kualico-rice-kc,smith750/rice,cniesen/rice,shahess/rice,sonamuthu/rice-1,bhutchinson/rice,ewestfal/rice,UniversityOfHawaiiORS/rice,kuali/kc-rice,bhutchinson/rice,UniversityOfHawaiiORS/rice,shahess/rice,smith750/rice,UniversityOfHawaiiORS/rice,cniesen/rice,bhutchinson/rice,UniversityOfHawaiiORS/rice,smith750/rice,ewestfal/rice-svn2git-test,ewestfal/rice,shahess/rice,ewestfal/rice-svn2git-test,bhutchinson/rice,ewestfal/rice,smith750/rice,kuali/kc-rice,cniesen/rice,jwillia/kc-rice1,sonamuthu/rice-1,ewestfal/rice-svn2git-test,gathreya/rice-kc,jwillia/kc-rice1,bhutchinson/rice,bsmith83/rice-1,kuali/kc-rice,smith750/rice,sonamuthu/rice-1,geothomasp/kualico-rice-kc,gathreya/rice-kc,bsmith83/rice-1,bsmith83/rice-1,ewestfal/rice,rojlarge/rice-kc,UniversityOfHawaiiORS/rice,shahess/rice,cniesen/rice,jwillia/kc-rice1,geothomasp/kualico-rice-kc,jwillia/kc-rice1,geothomasp/kualico-rice-kc,sonamuthu/rice-1,rojlarge/rice-kc,gathreya/rice-kc,kuali/kc-rice,cniesen/rice,ewestfal/rice-svn2git-test,ewestfal/rice,jwillia/kc-rice1,gathreya/rice-kc,bsmith83/rice-1,gathreya/rice-kc,kuali/kc-rice,rojlarge/rice-kc,shahess/rice,rojlarge/rice-kc,rojlarge/rice-kc,geothomasp/kualico-rice-kc | /**
* Copyright 2005-2012 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.kim.bo.ui;
import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.kuali.rice.core.api.membership.MemberType;
import org.kuali.rice.kim.api.KimConstants;
import org.kuali.rice.kim.api.group.Group;
import org.kuali.rice.kim.api.identity.principal.Principal;
import org.kuali.rice.kim.api.role.Role;
import org.kuali.rice.kim.api.services.KimApiServiceLocator;
import org.springframework.util.AutoPopulatingList;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This is a description of what this class does - shyu don't forget to fill this in.
*
* @author Kuali Rice Team ([email protected])
*
*/
@IdClass(KimDocumentRoleMemberId.class)
@Entity
@Table(name="KRIM_PND_ROLE_MBR_MT")
public class KimDocumentRoleMember extends KimDocumentBoActivatableToFromEditableBase {
private static final long serialVersionUID = -2463865643038170979L;
@Id
@GeneratedValue(generator="KRIM_ROLE_MBR_ID_S")
@GenericGenerator(name="KRIM_ROLE_MBR_ID_S",strategy="org.kuali.rice.core.jpa.spring.RiceNumericStringSequenceStyleGenerator",parameters={
@Parameter(name="sequence_name",value="KRIM_ROLE_MBR_ID_S"),
@Parameter(name="value_column",value="id")
})
@Column(name="ROLE_MBR_ID")
protected String roleMemberId;
@Column(name="ROLE_ID")
protected String roleId;
@Column(name="MBR_ID")
protected String memberId;
//TODO: remove the default
@Column(name="MBR_TYP_CD")
protected String memberTypeCode = KimConstants.KimGroupMemberTypes.PRINCIPAL_MEMBER_TYPE.getCode();
@Transient
protected String memberName;
@Transient
protected String memberNamespaceCode;
protected String memberFullName;
@OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
@JoinColumns({
@JoinColumn(name="ROLE_MBR_ID", insertable = false, updatable = false),
@JoinColumn(name="FDOC_NBR", insertable = false, updatable = false)
})
protected List <KimDocumentRoleQualifier> qualifiers = new AutoPopulatingList(KimDocumentRoleQualifier.class);
@Transient
protected String qualifiersToDisplay;
@OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
@JoinColumns({
@JoinColumn(name="ROLE_MBR_ID", insertable = false, updatable = false),
@JoinColumn(name="FDOC_NBR", insertable = false, updatable = false)
})
private List<KimDocumentRoleResponsibilityAction> roleRspActions;
public KimDocumentRoleMember() {
qualifiers = new ArrayList <KimDocumentRoleQualifier>();
roleRspActions = new ArrayList <KimDocumentRoleResponsibilityAction>();
}
public int getNumberOfQualifiers(){
return qualifiers==null?0:qualifiers.size();
}
/**
* @return the memberId
*/
public String getMemberId() {
return this.memberId;
}
/**
* @param memberId the memberId to set
*/
public void setMemberId(String memberId) {
this.memberId = memberId;
}
public String getRoleMemberId() {
return this.roleMemberId;
}
public void setRoleMemberId(String roleMemberId) {
this.roleMemberId = roleMemberId;
}
public String getRoleId() {
return this.roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public KimDocumentRoleQualifier getQualifier(String kimAttributeDefnId) {
for(KimDocumentRoleQualifier qualifier:qualifiers){
if(qualifier.getKimAttrDefnId().equals(kimAttributeDefnId)) {
return qualifier;
}
}
return null;
}
public List<KimDocumentRoleQualifier> getQualifiers() {
return this.qualifiers;
}
public void setQualifiers(List<KimDocumentRoleQualifier> qualifiers) {
this.qualifiers = qualifiers;
}
/**
* @return the memberTypeCode
*/
public String getMemberTypeCode() {
return this.memberTypeCode;
}
/**
* @param memberTypeCode the memberTypeCode to set
*/
public void setMemberTypeCode(String memberTypeCode) {
this.memberTypeCode = memberTypeCode;
}
/**
* @return the memberName
*/
public String getMemberName() {
if ( memberName == null ) {
populateDerivedValues();
}
return memberName;
}
/**
* @param memberName the memberName to set
*/
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public List<KimDocumentRoleResponsibilityAction> getRoleRspActions() {
return this.roleRspActions;
}
public void setRoleRspActions(
List<KimDocumentRoleResponsibilityAction> roleRspActions) {
this.roleRspActions = roleRspActions;
}
/**
* @return the memberNamespaceCode
*/
public String getMemberNamespaceCode() {
if ( memberNamespaceCode == null ) {
populateDerivedValues();
}
return memberNamespaceCode;
}
/**
* @param memberNamespaceCode the memberNamespaceCode to set
*/
public void setMemberNamespaceCode(String memberNamespaceCode) {
this.memberNamespaceCode = memberNamespaceCode;
}
protected void populateDerivedValues() {
if(MemberType.PRINCIPAL.getCode().equals(getMemberTypeCode())){
if(!StringUtils.isEmpty(getMemberId())){
Principal principalInfo = KimApiServiceLocator.getIdentityService().getPrincipal(getMemberId());
if (principalInfo != null) {
setMemberName(principalInfo.getPrincipalName());
}
}
} else if(MemberType.GROUP.getCode().equals(getMemberTypeCode())){
Group groupInfo = KimApiServiceLocator.getGroupService().getGroup(getMemberId());
if (groupInfo != null) {
setMemberName(groupInfo.getName());
setMemberNamespaceCode(groupInfo.getNamespaceCode());
}
} else if(MemberType.ROLE.getCode().equals(getMemberTypeCode())){
Role role = KimApiServiceLocator.getRoleService().getRole(getMemberId());
setMemberName(role.getName());
setMemberNamespaceCode(role.getNamespaceCode());
}
}
public boolean isRole(){
return getMemberTypeCode()!=null && getMemberTypeCode().equals(MemberType.ROLE.getCode());
}
public boolean isGroup(){
return getMemberTypeCode()!=null && getMemberTypeCode().equals(MemberType.GROUP.getCode());
}
public boolean isPrincipal(){
return getMemberTypeCode()!=null && getMemberTypeCode().equals(MemberType.PRINCIPAL.getCode());
}
public Map<String, String> getQualifierAsMap() {
Map<String, String> m = new HashMap<String, String>();
for ( KimDocumentRoleQualifier data : getQualifiers() ) {
if (data.getKimAttribute() == null){
data.refreshReferenceObject("kimAttribute");
}
if (data.getKimAttribute() != null){
m.put( data.getKimAttribute().getAttributeName(), data.getAttrVal() );
}
}
return m;
}
/**
* @return the qualifiersToDisplay
*/
public String getQualifiersToDisplay() {
return this.qualifiersToDisplay;
}
/**
* @param qualifiersToDisplay the qualifiersToDisplay to set
*/
public void setQualifiersToDisplay(String qualifiersToDisplay) {
this.qualifiersToDisplay = qualifiersToDisplay;
}
/**
* @return the memberFullName
*/
public String getMemberFullName() {
return this.memberFullName;
}
/**
* @param memberFullName the memberFullName to set
*/
public void setMemberFullName(String memberFullName) {
this.memberFullName = memberFullName;
}
}
| impl/src/main/java/org/kuali/rice/kim/bo/ui/KimDocumentRoleMember.java | /**
* Copyright 2005-2012 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.kim.bo.ui;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.kuali.rice.core.api.membership.MemberType;
import org.kuali.rice.kim.api.KimConstants;
import org.kuali.rice.kim.api.group.Group;
import org.kuali.rice.kim.api.identity.principal.Principal;
import org.kuali.rice.kim.api.role.Role;
import org.kuali.rice.kim.api.services.KimApiServiceLocator;
import org.springframework.util.AutoPopulatingList;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This is a description of what this class does - shyu don't forget to fill this in.
*
* @author Kuali Rice Team ([email protected])
*
*/
@IdClass(KimDocumentRoleMemberId.class)
@Entity
@Table(name="KRIM_PND_ROLE_MBR_MT")
public class KimDocumentRoleMember extends KimDocumentBoActivatableToFromEditableBase {
private static final long serialVersionUID = -2463865643038170979L;
@Id
@GeneratedValue(generator="KRIM_ROLE_MBR_ID_S")
@GenericGenerator(name="KRIM_ROLE_MBR_ID_S",strategy="org.kuali.rice.core.jpa.spring.RiceNumericStringSequenceStyleGenerator",parameters={
@Parameter(name="sequence_name",value="KRIM_ROLE_MBR_ID_S"),
@Parameter(name="value_column",value="id")
})
@Column(name="ROLE_MBR_ID")
protected String roleMemberId;
@Column(name="ROLE_ID")
protected String roleId;
@Column(name="MBR_ID")
protected String memberId;
//TODO: remove the default
@Column(name="MBR_TYP_CD")
protected String memberTypeCode = KimConstants.KimGroupMemberTypes.PRINCIPAL_MEMBER_TYPE.getCode();
@Transient
protected String memberName;
@Transient
protected String memberNamespaceCode;
protected String memberFullName;
@OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
@JoinColumns({
@JoinColumn(name="ROLE_MBR_ID", insertable = false, updatable = false),
@JoinColumn(name="FDOC_NBR", insertable = false, updatable = false)
})
protected List <KimDocumentRoleQualifier> qualifiers = new AutoPopulatingList(KimDocumentRoleQualifier.class);
@Transient
protected String qualifiersToDisplay;
@OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
@JoinColumns({
@JoinColumn(name="ROLE_MBR_ID", insertable = false, updatable = false),
@JoinColumn(name="FDOC_NBR", insertable = false, updatable = false)
})
private List<KimDocumentRoleResponsibilityAction> roleRspActions;
public KimDocumentRoleMember() {
qualifiers = new ArrayList <KimDocumentRoleQualifier>();
roleRspActions = new ArrayList <KimDocumentRoleResponsibilityAction>();
}
public int getNumberOfQualifiers(){
return qualifiers==null?0:qualifiers.size();
}
/**
* @return the memberId
*/
public String getMemberId() {
return this.memberId;
}
/**
* @param memberId the memberId to set
*/
public void setMemberId(String memberId) {
this.memberId = memberId;
}
public String getRoleMemberId() {
return this.roleMemberId;
}
public void setRoleMemberId(String roleMemberId) {
this.roleMemberId = roleMemberId;
}
public String getRoleId() {
return this.roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public KimDocumentRoleQualifier getQualifier(String kimAttributeDefnId) {
for(KimDocumentRoleQualifier qualifier:qualifiers){
if(qualifier.getKimAttrDefnId().equals(kimAttributeDefnId)) {
return qualifier;
}
}
return null;
}
public List<KimDocumentRoleQualifier> getQualifiers() {
return this.qualifiers;
}
public void setQualifiers(List<KimDocumentRoleQualifier> qualifiers) {
this.qualifiers = qualifiers;
}
/**
* @return the memberTypeCode
*/
public String getMemberTypeCode() {
return this.memberTypeCode;
}
/**
* @param memberTypeCode the memberTypeCode to set
*/
public void setMemberTypeCode(String memberTypeCode) {
this.memberTypeCode = memberTypeCode;
}
/**
* @return the memberName
*/
public String getMemberName() {
if ( memberName == null ) {
populateDerivedValues();
}
return memberName;
}
/**
* @param memberName the memberName to set
*/
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public List<KimDocumentRoleResponsibilityAction> getRoleRspActions() {
return this.roleRspActions;
}
public void setRoleRspActions(
List<KimDocumentRoleResponsibilityAction> roleRspActions) {
this.roleRspActions = roleRspActions;
}
/**
* @return the memberNamespaceCode
*/
public String getMemberNamespaceCode() {
if ( memberNamespaceCode == null ) {
populateDerivedValues();
}
return memberNamespaceCode;
}
/**
* @param memberNamespaceCode the memberNamespaceCode to set
*/
public void setMemberNamespaceCode(String memberNamespaceCode) {
this.memberNamespaceCode = memberNamespaceCode;
}
protected void populateDerivedValues() {
if(MemberType.PRINCIPAL.getCode().equals(getMemberTypeCode())){
Principal principalInfo = KimApiServiceLocator.getIdentityService().getPrincipal(getMemberId());
if (principalInfo != null) {
setMemberName(principalInfo.getPrincipalName());
}
} else if(MemberType.GROUP.getCode().equals(getMemberTypeCode())){
Group groupInfo = KimApiServiceLocator.getGroupService().getGroup(getMemberId());
if (groupInfo != null) {
setMemberName(groupInfo.getName());
setMemberNamespaceCode(groupInfo.getNamespaceCode());
}
} else if(MemberType.ROLE.getCode().equals(getMemberTypeCode())){
Role role = KimApiServiceLocator.getRoleService().getRole(getMemberId());
setMemberName(role.getName());
setMemberNamespaceCode(role.getNamespaceCode());
}
}
public boolean isRole(){
return getMemberTypeCode()!=null && getMemberTypeCode().equals(MemberType.ROLE.getCode());
}
public boolean isGroup(){
return getMemberTypeCode()!=null && getMemberTypeCode().equals(MemberType.GROUP.getCode());
}
public boolean isPrincipal(){
return getMemberTypeCode()!=null && getMemberTypeCode().equals(MemberType.PRINCIPAL.getCode());
}
public Map<String, String> getQualifierAsMap() {
Map<String, String> m = new HashMap<String, String>();
for ( KimDocumentRoleQualifier data : getQualifiers() ) {
if (data.getKimAttribute() == null){
data.refreshReferenceObject("kimAttribute");
}
if (data.getKimAttribute() != null){
m.put( data.getKimAttribute().getAttributeName(), data.getAttrVal() );
}
}
return m;
}
/**
* @return the qualifiersToDisplay
*/
public String getQualifiersToDisplay() {
return this.qualifiersToDisplay;
}
/**
* @param qualifiersToDisplay the qualifiersToDisplay to set
*/
public void setQualifiersToDisplay(String qualifiersToDisplay) {
this.qualifiersToDisplay = qualifiersToDisplay;
}
/**
* @return the memberFullName
*/
public String getMemberFullName() {
return this.memberFullName;
}
/**
* @param memberFullName the memberFullName to set
*/
public void setMemberFullName(String memberFullName) {
this.memberFullName = memberFullName;
}
}
| KULRICE-7092 Role add member functionality failed if member id was not populated.
| impl/src/main/java/org/kuali/rice/kim/bo/ui/KimDocumentRoleMember.java | KULRICE-7092 Role add member functionality failed if member id was not populated. | <ide><path>mpl/src/main/java/org/kuali/rice/kim/bo/ui/KimDocumentRoleMember.java
<ide> */
<ide> package org.kuali.rice.kim.bo.ui;
<ide>
<add>import org.apache.commons.lang.StringUtils;
<ide> import org.hibernate.annotations.GenericGenerator;
<ide> import org.hibernate.annotations.Parameter;
<ide> import org.kuali.rice.core.api.membership.MemberType;
<ide>
<ide> protected void populateDerivedValues() {
<ide> if(MemberType.PRINCIPAL.getCode().equals(getMemberTypeCode())){
<del> Principal principalInfo = KimApiServiceLocator.getIdentityService().getPrincipal(getMemberId());
<del> if (principalInfo != null) {
<del> setMemberName(principalInfo.getPrincipalName());
<del> }
<add> if(!StringUtils.isEmpty(getMemberId())){
<add> Principal principalInfo = KimApiServiceLocator.getIdentityService().getPrincipal(getMemberId());
<add> if (principalInfo != null) {
<add> setMemberName(principalInfo.getPrincipalName());
<add> }
<add> }
<ide> } else if(MemberType.GROUP.getCode().equals(getMemberTypeCode())){
<ide> Group groupInfo = KimApiServiceLocator.getGroupService().getGroup(getMemberId());
<ide> if (groupInfo != null) { |
|
Java | apache-2.0 | db6cb554c3a2454f6d905265765c8861ec4123d7 | 0 | dhirajsb/fabric8,PhilHardwick/fabric8,sobkowiak/fabric8,jludvice/fabric8,ffang/fuse-1,chirino/fabric8v2,jimmidyson/fabric8,mwringe/fabric8,christian-posta/fabric8,jludvice/fabric8,dhirajsb/fuse,jonathanchristison/fabric8,dhirajsb/fuse,punkhorn/fabric8,gashcrumb/fabric8,chirino/fuse,rnc/fabric8,joelschuster/fuse,avano/fabric8,EricWittmann/fabric8,avano/fabric8,aslakknutsen/fabric8,dejanb/fuse,KurtStam/fabric8,opensourceconsultant/fuse,chirino/fabric8v2,tadayosi/fuse,punkhorn/fuse,jimmidyson/fabric8,jimmidyson/fabric8,zmhassan/fabric8,janstey/fuse,joelschuster/fuse,mwringe/fabric8,sobkowiak/fabric8,KurtStam/fabric8,EricWittmann/fabric8,janstey/fuse-1,cunningt/fuse,migue/fabric8,chirino/fabric8v2,gashcrumb/fabric8,KurtStam/fabric8,rmarting/fuse,janstey/fuse-1,janstey/fuse,rajdavies/fabric8,jludvice/fabric8,chirino/fabric8,PhilHardwick/fabric8,hekonsek/fabric8,jboss-fuse/fuse,dhirajsb/fabric8,sobkowiak/fuse,rhuss/fabric8,rajdavies/fabric8,sobkowiak/fabric8,cunningt/fuse,sobkowiak/fabric8,jboss-fuse/fuse,chirino/fabric8,rmarting/fuse,jimmidyson/fabric8,punkhorn/fabric8,chirino/fuse,hekonsek/fabric8,rajdavies/fabric8,janstey/fuse,hekonsek/fabric8,joelschuster/fuse,punkhorn/fabric8,zmhassan/fabric8,EricWittmann/fabric8,jboss-fuse/fuse,rnc/fabric8,rnc/fabric8,punkhorn/fuse,dejanb/fuse,opensourceconsultant/fuse,PhilHardwick/fabric8,jonathanchristison/fabric8,chirino/fabric8,janstey/fabric8,gashcrumb/fabric8,jludvice/fabric8,rhuss/fabric8,dejanb/fuse,punkhorn/fabric8,tadayosi/fuse,sobkowiak/fuse,hekonsek/fabric8,janstey/fabric8,christian-posta/fabric8,dhirajsb/fabric8,christian-posta/fabric8,ffang/fuse-1,janstey/fuse,jonathanchristison/fabric8,mwringe/fabric8,rhuss/fabric8,zmhassan/fabric8,ffang/fuse-1,migue/fabric8,chirino/fabric8,KurtStam/fabric8,rajdavies/fabric8,rhuss/fabric8,rmarting/fuse,aslakknutsen/fabric8,zmhassan/fabric8,jimmidyson/fabric8,christian-posta/fabric8,janstey/fuse-1,mwringe/fabric8,avano/fabric8,opensourceconsultant/fuse,gashcrumb/fabric8,EricWittmann/fabric8,jonathanchristison/fabric8,PhilHardwick/fabric8,rnc/fabric8,migue/fabric8,migue/fabric8,rnc/fabric8,avano/fabric8,dhirajsb/fabric8,hekonsek/fabric8,chirino/fabric8v2,janstey/fabric8,aslakknutsen/fabric8 |
/**
* 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.fusesource.fabric.zookeeper.curator;
import static org.apache.felix.scr.annotations.ReferenceCardinality.OPTIONAL_MULTIPLE;
import static org.apache.felix.scr.annotations.ReferencePolicy.DYNAMIC;
import static org.fusesource.fabric.zookeeper.curator.Constants.CONNECTION_TIMEOUT;
import static org.fusesource.fabric.zookeeper.curator.Constants.DEFAULT_CONNECTION_TIMEOUT_MS;
import static org.fusesource.fabric.zookeeper.curator.Constants.DEFAULT_RETRY_INTERVAL;
import static org.fusesource.fabric.zookeeper.curator.Constants.DEFAULT_SESSION_TIMEOUT_MS;
import static org.fusesource.fabric.zookeeper.curator.Constants.MAX_RETRIES_LIMIT;
import static org.fusesource.fabric.zookeeper.curator.Constants.RETRY_POLICY_INTERVAL_MS;
import static org.fusesource.fabric.zookeeper.curator.Constants.RETRY_POLICY_MAX_RETRIES;
import static org.fusesource.fabric.zookeeper.curator.Constants.SESSION_TIMEOUT;
import static org.fusesource.fabric.zookeeper.curator.Constants.ZOOKEEPER_PASSWORD;
import static org.fusesource.fabric.zookeeper.curator.Constants.ZOOKEEPER_URL;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.curator.RetryPolicy;
import org.apache.curator.ensemble.EnsembleProvider;
import org.apache.curator.ensemble.fixed.FixedEnsembleProvider;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.ACLProvider;
import org.apache.curator.framework.imps.CuratorFrameworkImpl;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.framework.state.ConnectionStateManager;
import org.apache.curator.retry.RetryNTimes;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Reference;
import org.fusesource.fabric.api.Constants;
import org.fusesource.fabric.api.jcip.ThreadSafe;
import org.fusesource.fabric.api.scr.AbstractComponent;
import org.fusesource.fabric.api.scr.ValidatingReference;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Strings;
import com.google.common.io.Closeables;
@ThreadSafe
@Component(name = Constants.ZOOKEEPER_CLIENT_PID, description = "Fabric ZooKeeper Client Factory", policy = ConfigurationPolicy.OPTIONAL, immediate = true)
public final class ManagedCuratorFramework extends AbstractComponent {
private static final Logger LOGGER = LoggerFactory.getLogger(ManagedCuratorFramework.class);
@Reference(referenceInterface = ACLProvider.class)
private final ValidatingReference<ACLProvider> aclProvider = new ValidatingReference<ACLProvider>();
@Reference(referenceInterface = ConnectionStateListener.class, bind = "bindConnectionStateListener", unbind = "unbindConnectionStateListener", cardinality = OPTIONAL_MULTIPLE, policy = DYNAMIC)
private final List<ConnectionStateListener> connectionStateListeners = new CopyOnWriteArrayList<ConnectionStateListener>();
// private final DynamicEnsembleProvider ensembleProvider = new DynamicEnsembleProvider();
private BundleContext bundleContext;
// private CuratorFramework curatorFramework;
// private ServiceRegistration<CuratorFramework> registration;
// private Map<String, ?> oldConfiguration;
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private AtomicReference<State> state = new AtomicReference<State>();
class State implements ConnectionStateListener, Runnable {
final Map<String, ?> configuration;
final AtomicBoolean closed = new AtomicBoolean();
ServiceRegistration<CuratorFramework> registration;
CuratorFramework curator;
State(Map<String, ?> configuration) {
this.configuration = configuration;
}
@Override
public void run() {
if (curator != null) {
curator.getZookeeperClient().stop();
}
if (registration != null) {
registration.unregister();
registration = null;
}
try {
Closeables.close(curator, true);
} catch (IOException e) {
// Should not happen
}
curator = null;
if (!closed.get()) {
curator = buildCuratorFramework(configuration);
curator.getConnectionStateListenable().addListener(this, executor);
if (curator.getZookeeperClient().isConnected()) {
stateChanged(curator, ConnectionState.CONNECTED);
}
}
}
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState) {
if (newState == ConnectionState.CONNECTED) {
if (registration == null) {
registration = bundleContext.registerService(CuratorFramework.class, curator, null);
}
}
for (ConnectionStateListener listener : connectionStateListeners) {
listener.stateChanged(client, newState);
}
if (newState == ConnectionState.LOST) {
run();
}
}
public void close() {
closed.set(true);
try {
executor.submit(this).get();
} catch (Exception e) {
LOGGER.warn("Error while closing curator", e);
}
}
}
@Activate
void activate(BundleContext bundleContext, Map<String, ?> configuration) throws ConfigurationException {
this.bundleContext = bundleContext;
String zookeeperURL = getZookeeperURL(configuration);
if (!Strings.isNullOrEmpty(zookeeperURL)) {
State next = new State(configuration);
if (state.compareAndSet(null, next)) {
executor.submit(next);
}
}
activateComponent();
}
@Modified
void modified(Map<String, ?> configuration) throws ConfigurationException {
String zookeeperURL = getZookeeperURL(configuration);
if (!Strings.isNullOrEmpty(zookeeperURL)) {
State prev = state.get();
Map<String, ?> oldConfiguration = prev != null ? prev.configuration : null;
if (isRestartRequired(oldConfiguration, configuration)) {
State next = new State(configuration);
if (state.compareAndSet(prev, next)) {
executor.submit(next);
if (prev != null) {
prev.close();
}
} else {
next.close();
}
}
}
}
@Deactivate
void deactivate() throws IOException {
deactivateComponent();
State prev = state.getAndSet(null);
if (prev != null) {
prev.close();
}
executor.shutdownNow();
}
private String getZookeeperURL(Map<String, ?> configuration) {
String zookeeperURL = null;
if (configuration != null) {
zookeeperURL = (String) configuration.get(ZOOKEEPER_URL);
zookeeperURL = Strings.isNullOrEmpty(zookeeperURL) ? System.getProperty(ZOOKEEPER_URL) : zookeeperURL;
}
return zookeeperURL;
}
/**
* Builds a {@link org.apache.curator.framework.CuratorFramework} from the specified {@link java.util.Map<String, ?>}.
*/
private synchronized CuratorFramework buildCuratorFramework(Map<String, ?> properties) {
String connectionString = readString(properties, ZOOKEEPER_URL, System.getProperty(ZOOKEEPER_URL, ""));
int sessionTimeoutMs = readInt(properties, SESSION_TIMEOUT, DEFAULT_SESSION_TIMEOUT_MS);
int connectionTimeoutMs = readInt(properties, CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT_MS);
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
.ensembleProvider(new FixedEnsembleProvider(connectionString))
.connectionTimeoutMs(connectionTimeoutMs)
.sessionTimeoutMs(sessionTimeoutMs)
.retryPolicy(buildRetryPolicy(properties));
if (isAuthorizationConfigured(properties)) {
String scheme = "digest";
String password = readString(properties, ZOOKEEPER_PASSWORD, System.getProperty(ZOOKEEPER_PASSWORD, ""));
byte[] auth = ("fabric:" + password).getBytes();
builder = builder.authorization(scheme, auth).aclProvider(aclProvider.get());
}
CuratorFramework framework = builder.build();
for (ConnectionStateListener listener : connectionStateListeners) {
framework.getConnectionStateListenable().addListener(listener);
}
framework.start();
return framework;
}
/**
* Builds an {@link org.apache.curator.retry.ExponentialBackoffRetry} from the {@link java.util.Map<String, ?>}.
*/
private RetryPolicy buildRetryPolicy(Map<String, ?> properties) {
int maxRetries = readInt(properties, RETRY_POLICY_MAX_RETRIES, MAX_RETRIES_LIMIT);
int intervalMs = readInt(properties, RETRY_POLICY_INTERVAL_MS, DEFAULT_RETRY_INTERVAL);
return new RetryNTimes(maxRetries, intervalMs);
}
/**
* Returns true if configuration contains authorization configuration.
*/
private boolean isAuthorizationConfigured(Map<String, ?> properties) {
return ((properties != null
&& !Strings.isNullOrEmpty((String) properties.get(ZOOKEEPER_PASSWORD))
|| (!Strings.isNullOrEmpty(System.getProperty(ZOOKEEPER_PASSWORD)))));
}
/**
* Returns true if configuration contains authorization configuration.
*/
private boolean isRestartRequired(Map<String, ?> oldProperties, Map<String, ?> properties) {
if (!propertyEquals(oldProperties, properties, ZOOKEEPER_URL)) {
return true;
} else if (!propertyEquals(oldProperties, properties, ZOOKEEPER_PASSWORD)) {
return true;
} else if (!propertyEquals(oldProperties, properties, CONNECTION_TIMEOUT)) {
return true;
} else if (!propertyEquals(oldProperties, properties, SESSION_TIMEOUT)) {
return true;
} else if (!propertyEquals(oldProperties, properties, RETRY_POLICY_MAX_RETRIES)) {
return true;
} else if (!propertyEquals(oldProperties, properties, RETRY_POLICY_INTERVAL_MS)) {
return true;
} else {
return false;
}
}
private boolean propertyEquals(Map<String, ?> left, Map<String, ?> right, String name) {
if (left == null || right == null || left.get(name) == null || right.get(name) == null) {
return (left == null || left.get(name) == null) && (right == null || right.get(name) == null);
} else {
return left.get(name).equals(right.get(name));
}
}
/**
* Reads an String value from the specified configuration.
*
* @param props The source props.
* @param key The key of the property to read.
* @param defaultValue The default value.
* @return The value read or the defaultValue if any error occurs.
*/
private static String readString(Map<String, ?> props, String key, String defaultValue) {
try {
Object obj = props.get(key);
if (obj instanceof String) {
return (String) obj;
} else {
return defaultValue;
}
} catch (Exception e) {
return defaultValue;
}
}
/**
* Reads an int value from the specified configuration.
*
* @param props The source props.
* @param key The key of the property to read.
* @param defaultValue The default value.
* @return The value read or the defaultValue if any error occurs.
*/
private static int readInt(Map<String, ?> props, String key, int defaultValue) {
try {
Object obj = props.get(key);
if (obj instanceof Number) {
return ((Number) obj).intValue();
} else if (obj instanceof String) {
return Integer.parseInt((String) obj);
} else {
return defaultValue;
}
} catch (Exception e) {
return defaultValue;
}
}
void bindConnectionStateListener(ConnectionStateListener connectionStateListener) {
connectionStateListeners.add(connectionStateListener);
State curr = state.get();
CuratorFramework curator = curr != null ? curr.curator : null;
if (curator != null && curator.getZookeeperClient().isConnected()) {
connectionStateListener.stateChanged(curator, ConnectionState.CONNECTED);
}
}
void unbindConnectionStateListener(ConnectionStateListener connectionStateListener) {
connectionStateListeners.remove(connectionStateListener);
}
void bindAclProvider(ACLProvider aclProvider) {
this.aclProvider.bind(aclProvider);
}
void unbindAclProvider(ACLProvider aclProvider) {
this.aclProvider.unbind(aclProvider);
}
} | fabric/fabric-zookeeper/src/main/java/org/fusesource/fabric/zookeeper/curator/ManagedCuratorFramework.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.fusesource.fabric.zookeeper.curator;
import static org.apache.felix.scr.annotations.ReferenceCardinality.OPTIONAL_MULTIPLE;
import static org.apache.felix.scr.annotations.ReferencePolicy.DYNAMIC;
import static org.fusesource.fabric.zookeeper.curator.Constants.CONNECTION_TIMEOUT;
import static org.fusesource.fabric.zookeeper.curator.Constants.DEFAULT_CONNECTION_TIMEOUT_MS;
import static org.fusesource.fabric.zookeeper.curator.Constants.DEFAULT_RETRY_INTERVAL;
import static org.fusesource.fabric.zookeeper.curator.Constants.DEFAULT_SESSION_TIMEOUT_MS;
import static org.fusesource.fabric.zookeeper.curator.Constants.MAX_RETRIES_LIMIT;
import static org.fusesource.fabric.zookeeper.curator.Constants.RETRY_POLICY_INTERVAL_MS;
import static org.fusesource.fabric.zookeeper.curator.Constants.RETRY_POLICY_MAX_RETRIES;
import static org.fusesource.fabric.zookeeper.curator.Constants.SESSION_TIMEOUT;
import static org.fusesource.fabric.zookeeper.curator.Constants.ZOOKEEPER_PASSWORD;
import static org.fusesource.fabric.zookeeper.curator.Constants.ZOOKEEPER_URL;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.curator.RetryPolicy;
import org.apache.curator.ensemble.EnsembleProvider;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.ACLProvider;
import org.apache.curator.framework.imps.CuratorFrameworkImpl;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.framework.state.ConnectionStateManager;
import org.apache.curator.retry.RetryNTimes;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Reference;
import org.fusesource.fabric.api.Constants;
import org.fusesource.fabric.api.jcip.ThreadSafe;
import org.fusesource.fabric.api.scr.AbstractComponent;
import org.fusesource.fabric.api.scr.ValidatingReference;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Strings;
import com.google.common.io.Closeables;
@ThreadSafe
@Component(name = Constants.ZOOKEEPER_CLIENT_PID, description = "Fabric ZooKeeper Client Factory", policy = ConfigurationPolicy.OPTIONAL, immediate = true)
public final class ManagedCuratorFramework extends AbstractComponent {
private static final Logger LOGGER = LoggerFactory.getLogger(ManagedCuratorFramework.class);
@Reference(referenceInterface = ACLProvider.class)
private final ValidatingReference<ACLProvider> aclProvider = new ValidatingReference<ACLProvider>();
@Reference(referenceInterface = ConnectionStateListener.class, bind = "bindConnectionStateListener", unbind = "unbindConnectionStateListener", cardinality = OPTIONAL_MULTIPLE, policy = DYNAMIC)
private final Set<ConnectionStateListener> connectionStateListeners = new HashSet<ConnectionStateListener>();
private final DynamicEnsembleProvider ensembleProvider = new DynamicEnsembleProvider();
private BundleContext bundleContext;
private CuratorFramework curatorFramework;
private ServiceRegistration<CuratorFramework> registration;
private Map<String, ?> oldConfiguration;
@Activate
void activate(BundleContext bundleContext, Map<String, ?> configuration) throws ConfigurationException {
this.bundleContext = bundleContext;
String zookeeperURL = getZookeeperURL(configuration);
if (!Strings.isNullOrEmpty(zookeeperURL)) {
updateService(buildCuratorFramework(configuration));
oldConfiguration = configuration;
}
activateComponent();
}
@Modified
void modified(Map<String, ?> configuration) throws ConfigurationException {
String zookeeperURL = getZookeeperURL(configuration);
if (!Strings.isNullOrEmpty(zookeeperURL)) {
if (isRestartRequired(oldConfiguration, configuration)) {
updateService(buildCuratorFramework(configuration));
} else {
updateEnsemble(configuration);
if (!propertyEquals(oldConfiguration, configuration, ZOOKEEPER_URL)) {
try {
reset((CuratorFrameworkImpl) curatorFramework);
} catch (Exception e) {
LOGGER.error("Failed to update the ensemble url.", e);
}
}
}
oldConfiguration = configuration;
}
}
@Deactivate
void deactivate() throws IOException {
deactivateComponent();
curatorFramework.getZookeeperClient().stop();
if (registration != null) {
registration.unregister();
}
Closeables.close(curatorFramework, true);
}
private String getZookeeperURL(Map<String, ?> configuration) {
String zookeeperURL = null;
if (configuration != null) {
zookeeperURL = (String) configuration.get(ZOOKEEPER_URL);
zookeeperURL = Strings.isNullOrEmpty(zookeeperURL) ? System.getProperty(ZOOKEEPER_URL) : zookeeperURL;
}
return zookeeperURL;
}
/**
* Updates the {@link org.osgi.framework.ServiceRegistration} with the new {@link org.apache.curator.framework.CuratorFramework}.
* Un-registers previously registered services, closes previously created {@link org.apache.curator.framework.CuratorFramework} instances and
* registers the new {@link org.apache.curator.framework.CuratorFramework}.
*/
private void updateService(CuratorFramework framework) {
if (registration != null) {
registration.unregister();
try {
Closeables.close(curatorFramework, true);
} catch (IOException ex) {
//this should not happen as we swallow the exception.
}
registration = null;
}
// Delay the registration of the curator framework until it is connected
ConnectionStateListener listener = new ConnectionStateListener() {
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState) {
if (newState == ConnectionState.CONNECTED) {
// Avoid registering the service while holding a lock
ServiceRegistration<CuratorFramework> oldReg;
ServiceRegistration<CuratorFramework> newReg;
synchronized (ManagedCuratorFramework.this) {
oldReg = registration;
}
if (oldReg == null) {
newReg = bundleContext.registerService(CuratorFramework.class, curatorFramework, null);
synchronized (ManagedCuratorFramework.this) {
oldReg = registration;
if (oldReg == null) {
registration = newReg;
}
}
if (oldReg == null) {
client.getConnectionStateListenable().removeListener(this);
} else {
// Duplicate concurrent registration, so unregister
newReg.unregister();
}
}
}
}
};
framework.getConnectionStateListenable().addListener(listener);
this.curatorFramework = framework;
if (framework.getZookeeperClient().isConnected()) {
listener.stateChanged(framework, ConnectionState.CONNECTED);
}
}
/**
* Force the framework to close the underlying zookeeper client and start a fresh one.
* Thre method is used to enforce updating the ensemble url when neeeded.
*
* @param curator
* @throws NoSuchFieldException
* @throws IllegalAccessException
*/
private void reset(final CuratorFrameworkImpl curator) throws Exception {
Field field = CuratorFrameworkImpl.class.getDeclaredField("connectionStateManager");
field.setAccessible(true);
ConnectionStateManager connectionStateManager = (ConnectionStateManager) field.get(curator);
connectionStateManager.addStateChange(ConnectionState.LOST);
}
/**
* Builds a {@link org.apache.curator.framework.CuratorFramework} from the specified {@link java.util.Map<String, ?>}.
*/
private synchronized CuratorFramework buildCuratorFramework(Map<String, ?> properties) {
String connectionString = readString(properties, ZOOKEEPER_URL, System.getProperty(ZOOKEEPER_URL, ""));
ensembleProvider.update(connectionString);
int sessionTimeoutMs = readInt(properties, SESSION_TIMEOUT, DEFAULT_SESSION_TIMEOUT_MS);
int connectionTimeoutMs = readInt(properties, CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT_MS);
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
.ensembleProvider(ensembleProvider)
.connectionTimeoutMs(connectionTimeoutMs)
.sessionTimeoutMs(sessionTimeoutMs)
.retryPolicy(buildRetryPolicy(properties));
if (isAuthorizationConfigured(properties)) {
String scheme = "digest";
String password = readString(properties, ZOOKEEPER_PASSWORD, System.getProperty(ZOOKEEPER_PASSWORD, ""));
byte[] auth = ("fabric:" + password).getBytes();
builder = builder.authorization(scheme, auth).aclProvider(aclProvider.get());
}
CuratorFramework framework = builder.build();
for (ConnectionStateListener listener : connectionStateListeners) {
framework.getConnectionStateListenable().addListener(listener);
}
framework.start();
return framework;
}
/**
* Updates the {@link EnsembleProvider} with the new connection string.
*/
private void updateEnsemble(Map<String, ?> properties) {
String connectionString = readString(properties, ZOOKEEPER_URL, "");
ensembleProvider.update(connectionString);
}
/**
* Builds an {@link org.apache.curator.retry.ExponentialBackoffRetry} from the {@link java.util.Map<String, ?>}.
*/
private RetryPolicy buildRetryPolicy(Map<String, ?> properties) {
int maxRetries = readInt(properties, RETRY_POLICY_MAX_RETRIES, MAX_RETRIES_LIMIT);
int intervalMs = readInt(properties, RETRY_POLICY_INTERVAL_MS, DEFAULT_RETRY_INTERVAL);
return new RetryNTimes(maxRetries, intervalMs);
}
/**
* Returns true if configuration contains authorization configuration.
*/
private boolean isAuthorizationConfigured(Map<String, ?> properties) {
return ((properties != null
&& !Strings.isNullOrEmpty((String) properties.get(ZOOKEEPER_PASSWORD))
|| (!Strings.isNullOrEmpty(System.getProperty(ZOOKEEPER_PASSWORD)))));
}
/**
* Returns true if configuration contains authorization configuration.
*/
private boolean isRestartRequired(Map<String, ?> oldProperties, Map<String, ?> properties) {
if (oldProperties == null || properties == null) {
return true;
} else if (oldProperties.equals(properties)) {
return false;
} else if (!propertyEquals(oldProperties, properties, ZOOKEEPER_URL)) {
return true;
} else if (!propertyEquals(oldProperties, properties, ZOOKEEPER_PASSWORD)) {
return true;
} else if (!propertyEquals(oldProperties, properties, CONNECTION_TIMEOUT)) {
return true;
} else if (!propertyEquals(oldProperties, properties, SESSION_TIMEOUT)) {
return true;
} else if (!propertyEquals(oldProperties, properties, RETRY_POLICY_MAX_RETRIES)) {
return true;
} else if (!propertyEquals(oldProperties, properties, RETRY_POLICY_INTERVAL_MS)) {
return true;
} else {
return false;
}
}
private boolean propertyEquals(Map<String, ?> left, Map<String, ?> right, String name) {
if (left == null || right == null || left.get(name) == null || right.get(name) == null) {
return (left == null || left.get(name) == null) && (right == null || right.get(name) == null);
} else {
return left.get(name).equals(right.get(name));
}
}
/**
* Reads an String value from the specified configuration.
*
* @param props The source props.
* @param key The key of the property to read.
* @param defaultValue The default value.
* @return The value read or the defaultValue if any error occurs.
*/
private static String readString(Map<String, ?> props, String key, String defaultValue) {
try {
Object obj = props.get(key);
if (obj instanceof String) {
return (String) obj;
} else {
return defaultValue;
}
} catch (Exception e) {
return defaultValue;
}
}
/**
* Reads an int value from the specified configuration.
*
* @param props The source props.
* @param key The key of the property to read.
* @param defaultValue The default value.
* @return The value read or the defaultValue if any error occurs.
*/
private static int readInt(Map<String, ?> props, String key, int defaultValue) {
try {
Object obj = props.get(key);
if (obj instanceof Number) {
return ((Number) obj).intValue();
} else if (obj instanceof String) {
return Integer.parseInt((String) obj);
} else {
return defaultValue;
}
} catch (Exception e) {
return defaultValue;
}
}
void bindConnectionStateListener(ConnectionStateListener connectionStateListener) {
connectionStateListeners.add(connectionStateListener);
if (curatorFramework != null) {
curatorFramework.getConnectionStateListenable().addListener(connectionStateListener);
//We want listeners to receive the connected event upon registration.
if (curatorFramework.getZookeeperClient().isConnected()) {
connectionStateListener.stateChanged(curatorFramework, ConnectionState.CONNECTED);
}
}
}
void unbindConnectionStateListener(ConnectionStateListener connectionStateListener) {
connectionStateListeners.remove(connectionStateListener);
if (curatorFramework != null) {
curatorFramework.getConnectionStateListenable().removeListener(connectionStateListener);
}
}
void bindAclProvider(ACLProvider aclProvider) {
this.aclProvider.bind(aclProvider);
}
void unbindAclProvider(ACLProvider aclProvider) {
this.aclProvider.unbind(aclProvider);
}
} | Fix #257: Unregister the CuratorFramework service whenever the connection is completely lost | fabric/fabric-zookeeper/src/main/java/org/fusesource/fabric/zookeeper/curator/ManagedCuratorFramework.java | Fix #257: Unregister the CuratorFramework service whenever the connection is completely lost | <ide><path>abric/fabric-zookeeper/src/main/java/org/fusesource/fabric/zookeeper/curator/ManagedCuratorFramework.java
<ide> import java.io.IOException;
<ide> import java.lang.reflect.Field;
<ide> import java.util.HashSet;
<add>import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.Set;
<add>import java.util.concurrent.CopyOnWriteArrayList;
<add>import java.util.concurrent.ExecutionException;
<add>import java.util.concurrent.ExecutorService;
<add>import java.util.concurrent.Executors;
<add>import java.util.concurrent.Future;
<add>import java.util.concurrent.atomic.AtomicBoolean;
<add>import java.util.concurrent.atomic.AtomicReference;
<ide>
<ide> import org.apache.curator.RetryPolicy;
<ide> import org.apache.curator.ensemble.EnsembleProvider;
<add>import org.apache.curator.ensemble.fixed.FixedEnsembleProvider;
<ide> import org.apache.curator.framework.CuratorFramework;
<ide> import org.apache.curator.framework.CuratorFrameworkFactory;
<ide> import org.apache.curator.framework.api.ACLProvider;
<ide> @Reference(referenceInterface = ACLProvider.class)
<ide> private final ValidatingReference<ACLProvider> aclProvider = new ValidatingReference<ACLProvider>();
<ide> @Reference(referenceInterface = ConnectionStateListener.class, bind = "bindConnectionStateListener", unbind = "unbindConnectionStateListener", cardinality = OPTIONAL_MULTIPLE, policy = DYNAMIC)
<del> private final Set<ConnectionStateListener> connectionStateListeners = new HashSet<ConnectionStateListener>();
<del>
<del> private final DynamicEnsembleProvider ensembleProvider = new DynamicEnsembleProvider();
<add> private final List<ConnectionStateListener> connectionStateListeners = new CopyOnWriteArrayList<ConnectionStateListener>();
<add>
<add>// private final DynamicEnsembleProvider ensembleProvider = new DynamicEnsembleProvider();
<ide> private BundleContext bundleContext;
<del> private CuratorFramework curatorFramework;
<del> private ServiceRegistration<CuratorFramework> registration;
<del> private Map<String, ?> oldConfiguration;
<add>// private CuratorFramework curatorFramework;
<add>// private ServiceRegistration<CuratorFramework> registration;
<add>// private Map<String, ?> oldConfiguration;
<add> private final ExecutorService executor = Executors.newSingleThreadExecutor();
<add>
<add> private AtomicReference<State> state = new AtomicReference<State>();
<add>
<add> class State implements ConnectionStateListener, Runnable {
<add> final Map<String, ?> configuration;
<add> final AtomicBoolean closed = new AtomicBoolean();
<add> ServiceRegistration<CuratorFramework> registration;
<add> CuratorFramework curator;
<add>
<add> State(Map<String, ?> configuration) {
<add> this.configuration = configuration;
<add> }
<add>
<add> @Override
<add> public void run() {
<add> if (curator != null) {
<add> curator.getZookeeperClient().stop();
<add> }
<add> if (registration != null) {
<add> registration.unregister();
<add> registration = null;
<add> }
<add> try {
<add> Closeables.close(curator, true);
<add> } catch (IOException e) {
<add> // Should not happen
<add> }
<add> curator = null;
<add> if (!closed.get()) {
<add> curator = buildCuratorFramework(configuration);
<add> curator.getConnectionStateListenable().addListener(this, executor);
<add> if (curator.getZookeeperClient().isConnected()) {
<add> stateChanged(curator, ConnectionState.CONNECTED);
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public void stateChanged(CuratorFramework client, ConnectionState newState) {
<add> if (newState == ConnectionState.CONNECTED) {
<add> if (registration == null) {
<add> registration = bundleContext.registerService(CuratorFramework.class, curator, null);
<add> }
<add> }
<add> for (ConnectionStateListener listener : connectionStateListeners) {
<add> listener.stateChanged(client, newState);
<add> }
<add> if (newState == ConnectionState.LOST) {
<add> run();
<add> }
<add> }
<add>
<add> public void close() {
<add> closed.set(true);
<add> try {
<add> executor.submit(this).get();
<add> } catch (Exception e) {
<add> LOGGER.warn("Error while closing curator", e);
<add> }
<add> }
<add>
<add> }
<ide>
<ide> @Activate
<ide> void activate(BundleContext bundleContext, Map<String, ?> configuration) throws ConfigurationException {
<ide> this.bundleContext = bundleContext;
<ide> String zookeeperURL = getZookeeperURL(configuration);
<ide> if (!Strings.isNullOrEmpty(zookeeperURL)) {
<del> updateService(buildCuratorFramework(configuration));
<del> oldConfiguration = configuration;
<add> State next = new State(configuration);
<add> if (state.compareAndSet(null, next)) {
<add> executor.submit(next);
<add> }
<ide> }
<ide> activateComponent();
<ide> }
<ide> void modified(Map<String, ?> configuration) throws ConfigurationException {
<ide> String zookeeperURL = getZookeeperURL(configuration);
<ide> if (!Strings.isNullOrEmpty(zookeeperURL)) {
<add> State prev = state.get();
<add> Map<String, ?> oldConfiguration = prev != null ? prev.configuration : null;
<ide> if (isRestartRequired(oldConfiguration, configuration)) {
<del> updateService(buildCuratorFramework(configuration));
<del> } else {
<del> updateEnsemble(configuration);
<del> if (!propertyEquals(oldConfiguration, configuration, ZOOKEEPER_URL)) {
<del> try {
<del> reset((CuratorFrameworkImpl) curatorFramework);
<del> } catch (Exception e) {
<del> LOGGER.error("Failed to update the ensemble url.", e);
<add> State next = new State(configuration);
<add> if (state.compareAndSet(prev, next)) {
<add> executor.submit(next);
<add> if (prev != null) {
<add> prev.close();
<ide> }
<add> } else {
<add> next.close();
<ide> }
<ide> }
<del> oldConfiguration = configuration;
<ide> }
<ide> }
<ide>
<ide> @Deactivate
<ide> void deactivate() throws IOException {
<ide> deactivateComponent();
<del> curatorFramework.getZookeeperClient().stop();
<del> if (registration != null) {
<del> registration.unregister();
<del> }
<del> Closeables.close(curatorFramework, true);
<add> State prev = state.getAndSet(null);
<add> if (prev != null) {
<add> prev.close();
<add> }
<add> executor.shutdownNow();
<ide> }
<ide>
<ide> private String getZookeeperURL(Map<String, ?> configuration) {
<ide> }
<ide>
<ide> /**
<del> * Updates the {@link org.osgi.framework.ServiceRegistration} with the new {@link org.apache.curator.framework.CuratorFramework}.
<del> * Un-registers previously registered services, closes previously created {@link org.apache.curator.framework.CuratorFramework} instances and
<del> * registers the new {@link org.apache.curator.framework.CuratorFramework}.
<del> */
<del> private void updateService(CuratorFramework framework) {
<del> if (registration != null) {
<del> registration.unregister();
<del> try {
<del> Closeables.close(curatorFramework, true);
<del> } catch (IOException ex) {
<del> //this should not happen as we swallow the exception.
<del> }
<del> registration = null;
<del> }
<del> // Delay the registration of the curator framework until it is connected
<del> ConnectionStateListener listener = new ConnectionStateListener() {
<del> @Override
<del> public void stateChanged(CuratorFramework client, ConnectionState newState) {
<del> if (newState == ConnectionState.CONNECTED) {
<del> // Avoid registering the service while holding a lock
<del> ServiceRegistration<CuratorFramework> oldReg;
<del> ServiceRegistration<CuratorFramework> newReg;
<del> synchronized (ManagedCuratorFramework.this) {
<del> oldReg = registration;
<del> }
<del> if (oldReg == null) {
<del> newReg = bundleContext.registerService(CuratorFramework.class, curatorFramework, null);
<del> synchronized (ManagedCuratorFramework.this) {
<del> oldReg = registration;
<del> if (oldReg == null) {
<del> registration = newReg;
<del> }
<del> }
<del> if (oldReg == null) {
<del> client.getConnectionStateListenable().removeListener(this);
<del> } else {
<del> // Duplicate concurrent registration, so unregister
<del> newReg.unregister();
<del> }
<del> }
<del> }
<del> }
<del> };
<del> framework.getConnectionStateListenable().addListener(listener);
<del> this.curatorFramework = framework;
<del> if (framework.getZookeeperClient().isConnected()) {
<del> listener.stateChanged(framework, ConnectionState.CONNECTED);
<del> }
<del> }
<del>
<del> /**
<del> * Force the framework to close the underlying zookeeper client and start a fresh one.
<del> * Thre method is used to enforce updating the ensemble url when neeeded.
<del> *
<del> * @param curator
<del> * @throws NoSuchFieldException
<del> * @throws IllegalAccessException
<del> */
<del> private void reset(final CuratorFrameworkImpl curator) throws Exception {
<del> Field field = CuratorFrameworkImpl.class.getDeclaredField("connectionStateManager");
<del> field.setAccessible(true);
<del> ConnectionStateManager connectionStateManager = (ConnectionStateManager) field.get(curator);
<del> connectionStateManager.addStateChange(ConnectionState.LOST);
<del> }
<del>
<del> /**
<ide> * Builds a {@link org.apache.curator.framework.CuratorFramework} from the specified {@link java.util.Map<String, ?>}.
<ide> */
<ide> private synchronized CuratorFramework buildCuratorFramework(Map<String, ?> properties) {
<ide> String connectionString = readString(properties, ZOOKEEPER_URL, System.getProperty(ZOOKEEPER_URL, ""));
<del> ensembleProvider.update(connectionString);
<ide> int sessionTimeoutMs = readInt(properties, SESSION_TIMEOUT, DEFAULT_SESSION_TIMEOUT_MS);
<ide> int connectionTimeoutMs = readInt(properties, CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT_MS);
<ide>
<ide> CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
<del> .ensembleProvider(ensembleProvider)
<add> .ensembleProvider(new FixedEnsembleProvider(connectionString))
<ide> .connectionTimeoutMs(connectionTimeoutMs)
<ide> .sessionTimeoutMs(sessionTimeoutMs)
<ide> .retryPolicy(buildRetryPolicy(properties));
<ide> }
<ide>
<ide> /**
<del> * Updates the {@link EnsembleProvider} with the new connection string.
<del> */
<del> private void updateEnsemble(Map<String, ?> properties) {
<del> String connectionString = readString(properties, ZOOKEEPER_URL, "");
<del> ensembleProvider.update(connectionString);
<del> }
<del>
<del> /**
<ide> * Builds an {@link org.apache.curator.retry.ExponentialBackoffRetry} from the {@link java.util.Map<String, ?>}.
<ide> */
<ide> private RetryPolicy buildRetryPolicy(Map<String, ?> properties) {
<ide> * Returns true if configuration contains authorization configuration.
<ide> */
<ide> private boolean isRestartRequired(Map<String, ?> oldProperties, Map<String, ?> properties) {
<del> if (oldProperties == null || properties == null) {
<del> return true;
<del> } else if (oldProperties.equals(properties)) {
<del> return false;
<del> } else if (!propertyEquals(oldProperties, properties, ZOOKEEPER_URL)) {
<add> if (!propertyEquals(oldProperties, properties, ZOOKEEPER_URL)) {
<ide> return true;
<ide> } else if (!propertyEquals(oldProperties, properties, ZOOKEEPER_PASSWORD)) {
<ide> return true;
<ide>
<ide> void bindConnectionStateListener(ConnectionStateListener connectionStateListener) {
<ide> connectionStateListeners.add(connectionStateListener);
<del> if (curatorFramework != null) {
<del> curatorFramework.getConnectionStateListenable().addListener(connectionStateListener);
<del> //We want listeners to receive the connected event upon registration.
<del> if (curatorFramework.getZookeeperClient().isConnected()) {
<del> connectionStateListener.stateChanged(curatorFramework, ConnectionState.CONNECTED);
<del> }
<add> State curr = state.get();
<add> CuratorFramework curator = curr != null ? curr.curator : null;
<add> if (curator != null && curator.getZookeeperClient().isConnected()) {
<add> connectionStateListener.stateChanged(curator, ConnectionState.CONNECTED);
<ide> }
<ide> }
<ide>
<ide> void unbindConnectionStateListener(ConnectionStateListener connectionStateListener) {
<ide> connectionStateListeners.remove(connectionStateListener);
<del> if (curatorFramework != null) {
<del> curatorFramework.getConnectionStateListenable().removeListener(connectionStateListener);
<del> }
<ide> }
<ide>
<ide> void bindAclProvider(ACLProvider aclProvider) { |
|
Java | mit | 2a360982d0c47bd30d75b90fbbfa060142e31fe9 | 0 | URMC/urHL7 | /*
* The MIT License
*
* Copyright (c) 2012 David Morgan, University of Rochester Medical Center
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.urhl7.spark;
import java.io.*;
import org.urhl7.igor.Igor;
import java.util.zip.*;
/**
* A simple HL7 File reader that will use an event driven model that fires on each parsing of a message in the file.
* @author dmorgan
*/
public class SparkFileReader {
private File inputFile;
private String delimiter;
private HL7MessageListener listener;
private int INTERNAL_BUFFER_SIZE = 500;
/**
* The default delimiter between messages. The default value is "\r\n"
*/
public static final String DELIMITER_DEFAULT = "\r\n";
/**
* Creates a new SparkFileReader, reading a file at the provided path, with no listener.
* @param filePath The file to read in
*/
public SparkFileReader(String filePath) {
this(new File(filePath));
}
/**
* Creates a new SparkFileReader pointing at a specific file with no listener.
* @param inputFile The file to read in
*/
public SparkFileReader(File inputFile) {
this(inputFile, null, DELIMITER_DEFAULT);
}
/**
* Creates a new SparkFileReader, reading a file at the provided path, with a specified listener.
* @param filePath The file to read in
* @param listener the listener to use
*/
public SparkFileReader(String filePath, HL7MessageListener listener) {
this(new File(filePath), listener);
}
/**
* Creates a new SparkFileReader pointing at a specific file with a specified listener.
* @param inputFile the file to read in
* @param listener the listener to use
*/
public SparkFileReader(File inputFile, HL7MessageListener listener) {
this(inputFile, listener, DELIMITER_DEFAULT);
}
/**
* Creates a new SparkFileReader, reading a file at the provided path, with no listener using the specified delimiter.
* @param filePath The file to read in
* @param delimiter the delimiter between messages
*/
public SparkFileReader(String filePath, String delimiter) {
this(new File(filePath), delimiter);
}
/**
* Creates a new SparkFileReader pointing at a specific file with no listener using the specified delimiter.
* @param inputFile the file to read in
* @param delimiter the delimiter between messages
*/
public SparkFileReader(File inputFile, String delimiter) {
this(inputFile, null, delimiter);
}
/**
* Creates a new SparkFileReader, reading a file at the provided path, with a listener, and a specified delimiter.
* @param filePath The file to read in
* @param listener the listener to use
* @param delimiter the delimiter between messages
*/
public SparkFileReader(String filePath, HL7MessageListener listener, String delimiter) {
this(new File(filePath));
}
/**
* Create a new SparkFileReader pointing a specific file, with a listener, and a specified delimiter.
* @param inputFile the file to read in
* @param listener the listener to use
* @param delimiter the delimiter between messages
*/
public SparkFileReader(File inputFile, HL7MessageListener listener, String delimiter) {
this.inputFile = inputFile;
this.listener = listener;
this.delimiter = delimiter;
}
/**
* Returns the delimiter that is being searched for between messages in the file.
* @return the delimiter
*/
public String getDelimiter() {
return delimiter;
}
/**
* Sets the delimiter to look for between messages in the file.
* @param delimiter the delimiter to set
*/
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
/**
* Returned the HL7MessageListener that is being triggered for this SparkFileReader.
* @return the listener
*/
public HL7MessageListener getListener() {
return listener;
}
/**
* Sets the listener to use for the handling of messages as they come in to the SparkFileReader.
* @param listener the listener to set
*/
public void setListener(HL7MessageListener listener) {
this.listener = listener;
}
/*
Shamelessly taken from http://stackoverflow.com/questions/30507653/how-to-check-whether-file-is-gzip-or-not-in-java
Thank you kind internet friend
*/
private static boolean isGZipped(File f) {
int magic = 0;
try {
RandomAccessFile raf = new RandomAccessFile(f, "r");
magic = raf.read() & 0xff | ((raf.read() << 8) & 0xff00);
raf.close();
} catch (Throwable e) { }
return magic == GZIPInputStream.GZIP_MAGIC;
}
/**
* Begins parsing the messages in the file specified. This may throw an IOException and must be handled. The parse function reads in the file,
* when it finds a delimiter will attempt to parse the message. This message is then sent to the listener specified.
* @return success of the parsing (if any of the messaceReceived(HL7Structure struct) calls return false, this will as well).
* @throws java.io.IOException
*/
public boolean parse() throws java.io.IOException {
boolean success = true;
//FileReader fr = new FileReader(inputFile);
Reader fr = null;
if( SparkFileReader.isGZipped(inputFile) ){
InputStream fileStream = new FileInputStream(inputFile);
InputStream gzipStream = new GZIPInputStream(fileStream);
Reader decoder = new InputStreamReader(gzipStream);
fr = new BufferedReader(decoder);
} else {
fr = new FileReader(inputFile);
}
char[] buf = new char[getInternalBufferSize()];
StringBuilder sb = new StringBuilder();
String message = "";
int byteIn = fr.read(buf) ;
while(byteIn != -1) {
sb.append(buf, 0, byteIn);
while (sb.indexOf(delimiter) != -1) {
message = sb.substring(0, sb.indexOf(delimiter)).toString();
success = success && listener.messageReceived(Igor.structure(new String(message)));
if (message.length()+delimiter.length() <= sb.length()) {
sb.delete(0, message.length()+delimiter.length());
} else {
sb.delete(0, message.length());
}
}
buf = new char[getInternalBufferSize()];
byteIn = fr.read(buf);
}
//final cleanup.
if (!sb.toString().trim().equals("")) {
message = sb.toString();
success = success && listener.messageReceived(Igor.structure(new String(message)));
}
fr.close();
return success;
}
/**
* Gets the size of the internal buffer being used.
* @return the INTERNAL_BUFFER_SIZE
*/
public int getInternalBufferSize() {
return INTERNAL_BUFFER_SIZE;
}
/**
* Sets the size of the internal buffer being used.
* @param internalBufferSize the INTERNAL_BUFFER_SIZE to set
*/
public void setInternalBufferSize(int internalBufferSize) {
this.INTERNAL_BUFFER_SIZE = internalBufferSize;
}
}
| src/main/java/org/urhl7/spark/SparkFileReader.java | /*
* The MIT License
*
* Copyright (c) 2012 David Morgan, University of Rochester Medical Center
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.urhl7.spark;
import java.io.*;
import org.urhl7.igor.Igor;
/**
* A simple HL7 File reader that will use an event driven model that fires on each parsing of a message in the file.
* @author dmorgan
*/
public class SparkFileReader {
private File inputFile;
private String delimiter;
private HL7MessageListener listener;
private int INTERNAL_BUFFER_SIZE = 500;
/**
* The default delimiter between messages. The default value is "\r\n"
*/
public static final String DELIMITER_DEFAULT = "\r\n";
/**
* Creates a new SparkFileReader, reading a file at the provided path, with no listener.
* @param filePath The file to read in
*/
public SparkFileReader(String filePath) {
this(new File(filePath));
}
/**
* Creates a new SparkFileReader pointing at a specific file with no listener.
* @param inputFile The file to read in
*/
public SparkFileReader(File inputFile) {
this(inputFile, null, DELIMITER_DEFAULT);
}
/**
* Creates a new SparkFileReader, reading a file at the provided path, with a specified listener.
* @param filePath The file to read in
* @param listener the listener to use
*/
public SparkFileReader(String filePath, HL7MessageListener listener) {
this(new File(filePath), listener);
}
/**
* Creates a new SparkFileReader pointing at a specific file with a specified listener.
* @param inputFile the file to read in
* @param listener the listener to use
*/
public SparkFileReader(File inputFile, HL7MessageListener listener) {
this(inputFile, listener, DELIMITER_DEFAULT);
}
/**
* Creates a new SparkFileReader, reading a file at the provided path, with no listener using the specified delimiter.
* @param filePath The file to read in
* @param delimiter the delimiter between messages
*/
public SparkFileReader(String filePath, String delimiter) {
this(new File(filePath), delimiter);
}
/**
* Creates a new SparkFileReader pointing at a specific file with no listener using the specified delimiter.
* @param inputFile the file to read in
* @param delimiter the delimiter between messages
*/
public SparkFileReader(File inputFile, String delimiter) {
this(inputFile, null, delimiter);
}
/**
* Creates a new SparkFileReader, reading a file at the provided path, with a listener, and a specified delimiter.
* @param filePath The file to read in
* @param listener the listener to use
* @param delimiter the delimiter between messages
*/
public SparkFileReader(String filePath, HL7MessageListener listener, String delimiter) {
this(new File(filePath));
}
/**
* Create a new SparkFileReader pointing a specific file, with a listener, and a specified delimiter.
* @param inputFile the file to read in
* @param listener the listener to use
* @param delimiter the delimiter between messages
*/
public SparkFileReader(File inputFile, HL7MessageListener listener, String delimiter) {
this.inputFile = inputFile;
this.listener = listener;
this.delimiter = delimiter;
}
/**
* Returns the delimiter that is being searched for between messages in the file.
* @return the delimiter
*/
public String getDelimiter() {
return delimiter;
}
/**
* Sets the delimiter to look for between messages in the file.
* @param delimiter the delimiter to set
*/
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
/**
* Returned the HL7MessageListener that is being triggered for this SparkFileReader.
* @return the listener
*/
public HL7MessageListener getListener() {
return listener;
}
/**
* Sets the listener to use for the handling of messages as they come in to the SparkFileReader.
* @param listener the listener to set
*/
public void setListener(HL7MessageListener listener) {
this.listener = listener;
}
/**
* Begins pasring the messages in the file specified. This may throw an IOException and must be handled. The parse function reads in the file,
* when it finds a delimiter will attempt to parse the message. This message is then sent to the listener specified.
* @return success of the parsing (if any of the messaceReceived(HL7Structure struct) calls return false, this will as well).
* @throws java.io.IOException
*/
public boolean parse() throws java.io.IOException {
boolean success = true;
FileReader fr = new FileReader(inputFile);
char[] buf = new char[getInternalBufferSize()];
StringBuilder sb = new StringBuilder();
String message = "";
int byteIn = fr.read(buf) ;
while(byteIn != -1) {
sb.append(buf, 0, byteIn);
while (sb.indexOf(delimiter) != -1) {
message = sb.substring(0, sb.indexOf(delimiter)).toString();
success = success && listener.messageReceived(Igor.structure(new String(message)));
if (message.length()+delimiter.length() <= sb.length()) {
sb.delete(0, message.length()+delimiter.length());
} else {
sb.delete(0, message.length());
}
}
buf = new char[getInternalBufferSize()];
byteIn = fr.read(buf);
}
//final cleanup.
if (!sb.toString().trim().equals("")) {
message = sb.toString();
success = success && listener.messageReceived(Igor.structure(new String(message)));
}
fr.close();
return success;
}
/**
* Gets the size of the internal buffer being used.
* @return the INTERNAL_BUFFER_SIZE
*/
public int getInternalBufferSize() {
return INTERNAL_BUFFER_SIZE;
}
/**
* Sets the size of the internal buffer being used.
* @param internalBufferSize the INTERNAL_BUFFER_SIZE to set
*/
public void setInternalBufferSize(int internalBufferSize) {
this.INTERNAL_BUFFER_SIZE = internalBufferSize;
}
}
| Added gzip support in SparkFileReader
| src/main/java/org/urhl7/spark/SparkFileReader.java | Added gzip support in SparkFileReader | <ide><path>rc/main/java/org/urhl7/spark/SparkFileReader.java
<ide>
<ide> import java.io.*;
<ide> import org.urhl7.igor.Igor;
<add>import java.util.zip.*;
<ide>
<ide> /**
<ide> * A simple HL7 File reader that will use an event driven model that fires on each parsing of a message in the file.
<ide> this.listener = listener;
<ide> }
<ide>
<del> /**
<del> * Begins pasring the messages in the file specified. This may throw an IOException and must be handled. The parse function reads in the file,
<add> /*
<add> Shamelessly taken from http://stackoverflow.com/questions/30507653/how-to-check-whether-file-is-gzip-or-not-in-java
<add> Thank you kind internet friend
<add> */
<add> private static boolean isGZipped(File f) {
<add> int magic = 0;
<add> try {
<add> RandomAccessFile raf = new RandomAccessFile(f, "r");
<add> magic = raf.read() & 0xff | ((raf.read() << 8) & 0xff00);
<add> raf.close();
<add> } catch (Throwable e) { }
<add> return magic == GZIPInputStream.GZIP_MAGIC;
<add> }
<add>
<add> /**
<add> * Begins parsing the messages in the file specified. This may throw an IOException and must be handled. The parse function reads in the file,
<ide> * when it finds a delimiter will attempt to parse the message. This message is then sent to the listener specified.
<ide> * @return success of the parsing (if any of the messaceReceived(HL7Structure struct) calls return false, this will as well).
<ide> * @throws java.io.IOException
<ide> */
<ide> public boolean parse() throws java.io.IOException {
<ide> boolean success = true;
<del> FileReader fr = new FileReader(inputFile);
<add> //FileReader fr = new FileReader(inputFile);
<add>
<add> Reader fr = null;
<add>
<add> if( SparkFileReader.isGZipped(inputFile) ){
<add> InputStream fileStream = new FileInputStream(inputFile);
<add> InputStream gzipStream = new GZIPInputStream(fileStream);
<add> Reader decoder = new InputStreamReader(gzipStream);
<add> fr = new BufferedReader(decoder);
<add> } else {
<add> fr = new FileReader(inputFile);
<add> }
<ide>
<ide> char[] buf = new char[getInternalBufferSize()];
<ide> StringBuilder sb = new StringBuilder(); |
|
JavaScript | mit | c1c90ee2a87ad7c8086310c718871bbca05ac343 | 0 | jurrish/hangman_project,jurrish/hangman_project | var questionsArray = [];
var promptArray = [ 'What is the return value of wallOne?',
'What\'s the importance of updateMessage(); ?',
'Which is correct about the following diagram?',
'What is the name of the folder that the stylesheet is saved in?',
'What would the method return if the value of name was changed?',
'Which method converts a number into a string, keeping a specified number of decimals?',
'Which question refers to the html element using the built in document method?',
'What is true about key value pairs?',
'What does total return?',
'which of these returns the largest integer less than or equal to a given number?',
'If hourNow = 14, what will happen?',
'which element id is being updated with .textContent?' ];
var responseArray = [['15', '40', '8', 'area'], ['It updates the variable el', 'It calls the function', 'It is not important', 'It writes text content into the child element'], ['<p> is a child of <div>', '<head> is a grandchild of document', '<html> is a parent of both <head> and <body>', 'all of these are correct'], ['<link>', 'css/', 'index.html', 'it auto links'], ['It would not affect how the method calculates the return value', 'checkAvailability will not run properly', 'the value of Quay will still print out', 'You would have to delete the entire Object to rename it'], ['isNan', 'toFixed', 'toPrecision', 'toExponential'],
['getElementById', 'checkAvailability', 'Hotel(name, rooms, booked)', '.name'], ['a unique identifier with data attached', 'it is frequently used to change methods using jQuery', 'they do not have them in any other programming language', 'a deprecated version of control flow'], ['No one knows', '70', '14', 'Scott\'s age'], ['Math.ceil()', 'Math.floor()', 'Math.round()', 'Math.random'], ['the user will see a welcome text', 'the user will see a good morning text', 'the user will see a good evening text', 'the user will see a good afternoon text'], ['var el', 'cost', 'total', 'document']];
var correctAnswer = ['15', 'It calls the function', 'all of these are correct', 'css/', 'It would not affect how the method calculates the return value', 'toFixed', 'getElementById', 'a unique identifier with data attached', '70', 'Math.floor()', 'the user will see a good afternoon text', 'cost'];
var questionsObject = [];
var answerArray = [];
var questionNames = ['calculate', 'callQuestion', 'childQuestion', 'htmlQuestion', 'methodQuestion', 'methodQuestion2', 'multipleObjects', 'objLitQuestion', 'returnQuestion', 'roundDownQuestion', 'testquestion', 'varQuestion'];
function QuesConstructor(name, path, quest, answer, allQuestions) {
this.name = name;
this.path = path;
questionsArray.push(this);
this.quest = quest;
this.answer = answer;
this.allQuestions = allQuestions;
questionsObject.push(this);
};
function addingQuestions() {
for(var i = 0; i < promptArray.length; i++) {
new QuesConstructor(questionNames[i], 'questions/' + questionNames[i] + '.png', promptArray[i], correctAnswer[i], responseArray[i]);
}
};
addingQuestions();
var canvas = document.getElementById('canvasHangman'),context = canvas.getContext('2d');
var canvasRender = {
gallows: function(){
context.fillStyle = 'black';
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = 'white';
context.lineWidth = 8.4;
context.strokeRect(10, 370, 380, 0);
context.strokeStyle = 'white';
context.lineWidth = 10;
context.strokeRect(350, 89, 0, 280);
context.strokeStyle = 'white';
context.lineWidth = 10;
context.strokeRect(200, 100, 160, 0);
context.strokeStyle = 'white';
context.lineWidth = 7;
context.strokeRect(220,100,0,50);
},
head: function() {
//oval head
var centerX = 60;
var centerY = -50;
var radius = 50;
context.save();
context.translate(canvas.width / 2, canvas.height / 2);
context.scale(.35, .45);
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.restore();
context.fillStyle = 'white';
context.fill();
context.lineWidth = 8;
context.strokeStyle = 'white';
context.stroke();
//left eyes
var eyeX = 150;
var eyeY = -260;
var eyeRadius = 50;
context.save();
context.translate(canvas.width / 2, canvas.height / 2);
context.scale(.07, .09);
context.beginPath();
context.arc(eyeX, eyeY, eyeRadius, 0, 2 * Math.PI, false);
context.restore();
context.fillStyle = 'black';
context.fill();
context.lineWidth = 2;
context.strokeStyle = 'black';
context.stroke();
//right eye
var rightEyeX = 420;
var rightEyeY = -260;
var rightEyeRadius = 50;
context.save();
context.translate(canvas.width / 2, canvas.height / 2);
context.scale(.07, .09);
context.beginPath();
context.arc(rightEyeX, rightEyeY, rightEyeRadius, 0, 2 * Math.PI, false);
context.restore();
context.fillStyle = 'black';
context.fill();
context.lineWidth = 2;
context.strokeStyle = 'black';
context.stroke();
},
torso: function() {
//torso
context.strokeStyle = 'white';
context.lineWidth = 8;
context.strokeRect(221, 205, 0, 79);
},
rightLeg: function() {
//right leg
var xRightLeg = canvas.width / 2.33;
var yRightLeg = canvas.height / 1.16;
var legRadius = 85;
var startAngle = 1.7 * Math.PI;
var endAngle = 0 * Math.PI;
var counterClockwise = false;
context.beginPath();
context.arc(xRightLeg, yRightLeg, legRadius, startAngle, endAngle, counterClockwise);
context.lineWidth = 8;
context.strokeStyle = 'white';
context.stroke();
//right foot
context.strokeStyle = 'white';
context.lineWidth = 8;
context.strokeRect(250, 350, 20, 0);
},
leftLeg: function() {
//legs left leg
var xleftLeg = canvas.width / 1.48;
var yleftLeg = canvas.height / 1.16;
var legRadius = 85;
var startAngle = 1 * Math.PI;
var endAngle = 1.3 * Math.PI;
var counterClockwise = false;
context.beginPath();
context.arc(xleftLeg, yleftLeg, legRadius, startAngle, endAngle, counterClockwise);
context.lineWidth = 8;
context.strokeStyle = 'white';
context.stroke();
//left footer
context.strokeStyle = 'white';
context.lineWidth = 8;
context.strokeRect(170, 350, 20, 0);
},
rightArm: function() {
//right arm
var xRightArm = canvas.width / 2.31;
var yRightArm = canvas.height / 1.4;
var armRadius = 85;
var startArmAngle = 1.7 * Math.PI;
var endArmAngle = -.1 * Math.PI;
var counterArmClockwise = false;
context.beginPath();
context.arc(xRightArm, yRightArm, armRadius, startArmAngle, endArmAngle, counterArmClockwise);
context.lineWidth = 8;
context.strokeStyle = 'white';
context.stroke();
},
leftArm: function() {
//left arm
var xLeftArm = canvas.width / 1.49;
var yLeftArm = canvas.height / 1.4;
var armLeftRadius = 85;
var startLeftArmAngle = 1.1 * Math.PI;
var endLeftArmAngle = 1.3 * Math.PI;
var counterLeftArmClockwise = false;
context.beginPath();
context.arc(xLeftArm, yLeftArm, armLeftRadius, startLeftArmAngle, endLeftArmAngle, counterLeftArmClockwise);
context.lineWidth = 8;
context.strokeStyle = 'white';
context.stroke();
},
gameOver: function(){
//red fill
context.fillStyle = 'red';
context.fillRect(0, 0, canvas.width, canvas.height);
}
};
function displayCorrectAnswers(){
var rightAnswer = document.getElementById('wrongAnswer');
var theAnswerIs = document.getElementById('correctDisplay');
theAnswerIs.textContent = correctAnswer[activeUser.questionsAsked];
rightAnswer.appendChild(theAnswerIs);
};
var radioButtons = document.getElementsByName('answers');
var answerForm = document.getElementById('formId');
var ansEl = document.getElementById('answer');
var ansPTag = document.createElement('p');
var newTest = {
submitButton: document.getElementById('submit'),
won: false,
lost: false,
selection: null,
selectionLabel: null,
winLoseCheck: function() {
if (newTest.lost === true) {
canvasRender.gameOver(); //New Canvas Render Method
submitButton.hidden = true;
console.log('Game is Over - lost = true');
}
if (newTest.won === true) {
submitButton.hidden = true;
console.log('Game is Won - won = true');
}
},
appendingImage : function() {
if (activeUser.questionsAsked === 12) {
ansEl.appendChild(ansPTag).textContent = 'Good Job!';
newTest.won = true;
return;
}
if (activeUser.questionsWrong === 6) {
ansEl.appendChild(ansPTag).textContent = 'Game Over';
newTest.lost = true;
return;
}
var elQuesPic = document.getElementById('img');
var elQuesParent = document.getElementById('test');
var elQuesText = document.getElementById('question');
elQuesPic.src = questionsArray[activeUser.questionsAsked].path;
elQuesText.textContent = promptArray[activeUser.questionsAsked];
elQuesParent.appendChild(elQuesText);
},
displayMultAnswers: function() {
var j = 0;
var radioTestOne = document.getElementById('testOne');
radioTestOne.textContent = responseArray[activeUser.questionsAsked][j++];
var radioTestTwo = document.getElementById('testTwo');
radioTestTwo.textContent = responseArray[activeUser.questionsAsked][j++];
var radioTestThree = document.getElementById('testThree');
radioTestThree.textContent = responseArray[activeUser.questionsAsked][j++];
var radioTestFour = document.getElementById('testFour');
radioTestFour.textContent = responseArray[activeUser.questionsAsked][j];
},
nextQuestion : function() {
activeUser.questionsAsked += 1;
newTest.displayMultAnswers();
newTest.appendingImage();
},
radioCheck: function() {
event.preventDefault();
for (var r = 0; r < radioButtons.length; r++) {
if (radioButtons[r].checked) {
selection = radioButtons[r];
selectionLabel = selection.labels;
console.log(selection);
console.log(selectionLabel);
radioButtons[r].checked = false;
}
};
if (selectionLabel[0].textContent === questionsArray[activeUser.questionsAsked].answer) {
console.log('You got it right!');
newTest.nextQuestion();
} else {
newTest.wrongCounter();
displayCorrectAnswers();
console.log('You got it wrong');
newTest.nextQuestion();
}
},
wrongCounter: function() {
activeUser.questionsWrong += 1;
console.log(activeUser.questionsWrong + ' = quests wrong value');
if(activeUser.questionsWrong === 1){
canvasRender.head();
}
if(activeUser.questionsWrong === 2){
canvasRender.torso();
}
if(activeUser.questionsWrong === 3){
canvasRender.rightLeg();
}
if(activeUser.questionsWrong === 4){
canvasRender.leftLeg();
}
if(activeUser.questionsWrong === 5){
canvasRender.rightArm();
}
if(activeUser.questionsWrong === 6){
canvasRender.leftArm();
}
},
//Something to show the correct answer to a question that is answered wrong.
//Listener event and functionality for back to questions button.
//Update user account array and active user in localStorage.
//Maybe have a reset function at the end of the game to play again.
};
window.onload = function(){
newTest.submitButton.hidden = false;
//get activeUser
activeUser = JSON.parse(localStorage.getItem('activeUser'));
newTest.displayMultAnswers();
newTest.appendingImage();
canvasRender.gallows();
};
answerForm.addEventListener('submit', newTest.radioCheck);
answerForm.addEventListener('submit', newTest.winLoseCheck);
| game_page/game_page.js | var questionsArray = [];
var promptArray = [ 'What is the return value of wallOne?',
'What\'s the importance of updateMessage(); ?',
'Which is correct about the following diagram?',
'What is the name of the folder that the stylesheet is saved in?',
'What would the method return if the value of name was changed?',
'Which method converts a number into a string, keeping a specified number of decimals?',
'Which question refers to the html element using the built in document method?',
'What is true about key value pairs?',
'What does total return?',
'which of these returns the largest integer less than or equal to a given number?',
'If hourNow = 14, what will happen?',
'which element id is being updated with .textContent?' ];
var responseArray = [['15', '40', '8', 'area'], ['It updates the variable el', 'It calls the function', 'It is not important', 'It writes text content into the child element'], ['<p> is a child of <div>', '<head> is a grandchild of document', '<html> is a parent of both <head> and <body>', 'all of these are correct'], ['<link>', 'css/', 'index.html', 'it auto links'], ['It would not affect how the method calculates the return value', 'checkAvailability will not run properly', 'the value of Quay will still print out', 'You would have to delete the entire Object to rename it'], ['isNan', 'toFixed', 'toPrecision', 'toExponential'],
['getElementById', 'checkAvailability', 'Hotel(name, rooms, booked)', '.name'], ['a unique identifier with data attached', 'it is frequently used to change methods using jQuery', 'they do not have them in any other programming language', 'a deprecated version of control flow'], ['No one knows', '70', '14', 'Scott\'s age'], ['Math.ceil()', 'Math.floor()', 'Math.round()', 'Math.random'], ['the user will see a welcome text', 'the user will see a good morning text', 'the user will see a good evening text', 'the user will see a good afternoon text'], ['var el', 'cost', 'total', 'document']];
var correctAnswer = ['15', 'It calls the function', 'all of these are correct', 'css/', 'It would not affect how the method calculates the return value', 'toFixed', 'getElementById', 'a unique identifier with data attached', '70', 'Math.floor()', 'the user will see a good afternoon text', 'cost'];
var questionsObject = [];
var answerArray = [];
var questionNames = ['calculate', 'callQuestion', 'childQuestion', 'htmlQuestion', 'methodQuestion', 'methodQuestion2', 'multipleObjects', 'objLitQuestion', 'returnQuestion', 'roundDownQuestion', 'testquestion', 'varQuestion'];
function QuesConstructor(name, path, quest, answer, allQuestions) {
this.name = name;
this.path = path;
questionsArray.push(this);
this.quest = quest;
this.answer = answer;
this.allQuestions = allQuestions;
questionsObject.push(this);
};
function addingQuestions() {
for(var i = 0; i < promptArray.length; i++) {
new QuesConstructor(questionNames[i], 'questions/' + questionNames[i] + '.png', promptArray[i], correctAnswer[i], responseArray[i]);
}
};
addingQuestions();
var canvas = document.getElementById('canvasHangman'),context = canvas.getContext('2d');
var canvasRender = {
gallows: function(){
context.fillStyle = 'black';
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = 'white';
context.lineWidth = 8.4;
context.strokeRect(10, 370, 380, 0);
context.strokeStyle = 'white';
context.lineWidth = 10;
context.strokeRect(350, 89, 0, 280);
context.strokeStyle = 'white';
context.lineWidth = 10;
context.strokeRect(200, 100, 160, 0);
context.strokeStyle = 'white';
context.lineWidth = 7;
context.strokeRect(220,100,0,50);
},
head: function() {
//oval head
var centerX = 60;
var centerY = -50;
var radius = 50;
context.save();
context.translate(canvas.width / 2, canvas.height / 2);
context.scale(.35, .45);
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.restore();
context.fillStyle = 'white';
context.fill();
context.lineWidth = 8;
context.strokeStyle = 'white';
context.stroke();
//left eyes
var eyeX = 150;
var eyeY = -260;
var eyeRadius = 50;
context.save();
context.translate(canvas.width / 2, canvas.height / 2);
context.scale(.07, .09);
context.beginPath();
context.arc(eyeX, eyeY, eyeRadius, 0, 2 * Math.PI, false);
context.restore();
context.fillStyle = 'black';
context.fill();
context.lineWidth = 2;
context.strokeStyle = 'black';
context.stroke();
//right eye
var rightEyeX = 420;
var rightEyeY = -260;
var rightEyeRadius = 50;
context.save();
context.translate(canvas.width / 2, canvas.height / 2);
context.scale(.07, .09);
context.beginPath();
context.arc(rightEyeX, rightEyeY, rightEyeRadius, 0, 2 * Math.PI, false);
context.restore();
context.fillStyle = 'black';
context.fill();
context.lineWidth = 2;
context.strokeStyle = 'black';
context.stroke();
},
torso: function() {
//torso
context.strokeStyle = 'white';
context.lineWidth = 8;
context.strokeRect(221, 205, 0, 79);
},
rightLeg: function() {
//right leg
var xRightLeg = canvas.width / 2.33;
var yRightLeg = canvas.height / 1.16;
var legRadius = 85;
var startAngle = 1.7 * Math.PI;
var endAngle = 0 * Math.PI;
var counterClockwise = false;
context.beginPath();
context.arc(xRightLeg, yRightLeg, legRadius, startAngle, endAngle, counterClockwise);
context.lineWidth = 8;
context.strokeStyle = 'white';
context.stroke();
//right foot
context.strokeStyle = 'white';
context.lineWidth = 8;
context.strokeRect(250, 350, 20, 0);
},
leftLeg: function() {
//legs left leg
var xleftLeg = canvas.width / 1.48;
var yleftLeg = canvas.height / 1.16;
var legRadius = 85;
var startAngle = 1 * Math.PI;
var endAngle = 1.3 * Math.PI;
var counterClockwise = false;
context.beginPath();
context.arc(xleftLeg, yleftLeg, legRadius, startAngle, endAngle, counterClockwise);
context.lineWidth = 8;
context.strokeStyle = 'white';
context.stroke();
//left footer
context.strokeStyle = 'white';
context.lineWidth = 8;
context.strokeRect(170, 350, 20, 0);
},
rightArm: function() {
//right arm
var xRightArm = canvas.width / 2.31;
var yRightArm = canvas.height / 1.4;
var armRadius = 85;
var startArmAngle = 1.7 * Math.PI;
var endArmAngle = -.1 * Math.PI;
var counterArmClockwise = false;
context.beginPath();
context.arc(xRightArm, yRightArm, armRadius, startArmAngle, endArmAngle, counterArmClockwise);
context.lineWidth = 8;
context.strokeStyle = 'white';
context.stroke();
},
leftArm: function() {
var xLeftArm = canvas.width / 1.49;
var yLeftArm = canvas.height / 1.4;
var armLeftRadius = 85;
var startLeftArmAngle = 1.1 * Math.PI;
var endLeftArmAngle = 1.3 * Math.PI;
var counterLeftArmClockwise = false;
context.beginPath();
context.arc(xLeftArm, yLeftArm, armLeftRadius, startLeftArmAngle, endLeftArmAngle, counterLeftArmClockwise);
context.lineWidth = 8;
context.strokeStyle = 'white';
context.stroke();
},
gameOver: function(){
context.fillStyle = 'red';
context.fillRect(0, 0, canvas.width, canvas.height);
}
};
function displayCorrectAnswers(){
// for(var i = 0; i < correctAnswer.length; i++){
var rightAnswer = document.getElementById('wrongAnswer');
var theAnswerIs = document.getElementById('correctDisplay');
theAnswerIs.textContent = correctAnswer[activeUser.questionsAsked];
rightAnswer.appendChild(theAnswerIs);
// }
};
// displayCorrectAnswers();
var radioButtons = document.getElementsByName('answers');
var answerForm = document.getElementById('formId');
var ansEl = document.getElementById('answer');
var ansPTag = document.createElement('p');
var newTest = {
submitButton: document.getElementById('submit'),
won: false,
lost: false,
selection: null,
selectionLabel: null,
winLoseCheck: function() {
if (newTest.lost === true) {
canvasRender.gameOver();
submitButton.hidden = true;
console.log('Game is Over - lost = true');
}
if (newTest.won === true) {
submitButton.hidden = true;
console.log('Game is Won - won = true');
}
},
appendingImage : function() {
if (activeUser.questionsAsked === 12) {
ansEl.appendChild(ansPTag).textContent = 'Good Job!';
newTest.won = true;
return;
}
if (activeUser.questionsWrong === 6) {
ansEl.appendChild(ansPTag).textContent = 'Game Over';
newTest.lost = true;
return;
}
var elQuesPic = document.getElementById('img');
var elQuesParent = document.getElementById('test');
var elQuesText = document.getElementById('question');
elQuesPic.src = questionsArray[activeUser.questionsAsked].path;
elQuesText.textContent = promptArray[activeUser.questionsAsked];
elQuesParent.appendChild(elQuesText);
},
displayMultAnswers: function() {
var j = 0;
var radioTestOne = document.getElementById('testOne');
radioTestOne.textContent = responseArray[activeUser.questionsAsked][j++];
var radioTestTwo = document.getElementById('testTwo');
radioTestTwo.textContent = responseArray[activeUser.questionsAsked][j++];
var radioTestThree = document.getElementById('testThree');
radioTestThree.textContent = responseArray[activeUser.questionsAsked][j++];
var radioTestFour = document.getElementById('testFour');
radioTestFour.textContent = responseArray[activeUser.questionsAsked][j];
},
nextQuestion : function() {
activeUser.questionsAsked += 1;
newTest.displayMultAnswers();
newTest.appendingImage();
},
radioCheck: function() {
event.preventDefault();
for (var r = 0; r < radioButtons.length; r++) {
if (radioButtons[r].checked) {
selection = radioButtons[r];
selectionLabel = selection.labels;
console.log(selection);
console.log(selectionLabel);
radioButtons[r].checked = false;
}
};
if (selectionLabel[0].textContent === questionsArray[activeUser.questionsAsked].answer) {
console.log('You got it right!');
newTest.nextQuestion();
} else {
newTest.wrongCounter();
displayCorrectAnswers();
console.log('You got it wrong');
newTest.nextQuestion();
}
},
wrongCounter: function() {
activeUser.questionsWrong += 1;
console.log(activeUser.questionsWrong + ' = quests wrong value');
if(activeUser.questionsWrong === 1){
canvasRender.head();
}
if(activeUser.questionsWrong === 2){
canvasRender.torso();
}
if(activeUser.questionsWrong === 3){
canvasRender.rightLeg();
}
if(activeUser.questionsWrong === 4){
canvasRender.leftLeg();
}
if(activeUser.questionsWrong === 5){
canvasRender.rightArm();
}
if(activeUser.questionsWrong === 6){
canvasRender.leftArm();
}
},
//Something to show the correct answer to a question that is answered wrong.
//Listener event and functionality for back to questions button.
//Update user account array and active user in localStorage.
//Maybe have a reset function at the end of the game to play again.
};
window.onload = function(){
newTest.submitButton.hidden = false;
//get activeUser
activeUser = JSON.parse(localStorage.getItem('activeUser'));
newTest.displayMultAnswers();
newTest.appendingImage();
canvasRender.gallows();
};
answerForm.addEventListener('submit', newTest.radioCheck);
answerForm.addEventListener('submit', newTest.winLoseCheck);
| Added a few comments.
| game_page/game_page.js | Added a few comments. | <ide><path>ame_page/game_page.js
<ide> context.stroke();
<ide> },
<ide> leftArm: function() {
<add> //left arm
<ide> var xLeftArm = canvas.width / 1.49;
<ide> var yLeftArm = canvas.height / 1.4;
<ide> var armLeftRadius = 85;
<ide> context.stroke();
<ide> },
<ide> gameOver: function(){
<add> //red fill
<ide> context.fillStyle = 'red';
<ide> context.fillRect(0, 0, canvas.width, canvas.height);
<ide> }
<ide> };
<ide>
<ide> function displayCorrectAnswers(){
<del> // for(var i = 0; i < correctAnswer.length; i++){
<ide> var rightAnswer = document.getElementById('wrongAnswer');
<ide> var theAnswerIs = document.getElementById('correctDisplay');
<ide> theAnswerIs.textContent = correctAnswer[activeUser.questionsAsked];
<ide> rightAnswer.appendChild(theAnswerIs);
<del> // }
<del>};
<del>// displayCorrectAnswers();
<add>};
<ide>
<ide> var radioButtons = document.getElementsByName('answers');
<ide> var answerForm = document.getElementById('formId');
<ide>
<ide> winLoseCheck: function() {
<ide> if (newTest.lost === true) {
<del> canvasRender.gameOver();
<add> canvasRender.gameOver(); //New Canvas Render Method
<ide> submitButton.hidden = true;
<ide> console.log('Game is Over - lost = true');
<ide> } |
|
Java | lgpl-2.1 | 56e449f67f127ddd35962acd92154d3b708b3be8 | 0 | justincc/intermine,kimrutherford/intermine,joshkh/intermine,joshkh/intermine,JoeCarlson/intermine,tomck/intermine,zebrafishmine/intermine,kimrutherford/intermine,elsiklab/intermine,zebrafishmine/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,JoeCarlson/intermine,justincc/intermine,zebrafishmine/intermine,JoeCarlson/intermine,justincc/intermine,tomck/intermine,kimrutherford/intermine,JoeCarlson/intermine,kimrutherford/intermine,zebrafishmine/intermine,justincc/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,tomck/intermine,joshkh/intermine,tomck/intermine,JoeCarlson/intermine,JoeCarlson/intermine,zebrafishmine/intermine,joshkh/intermine,elsiklab/intermine,justincc/intermine,zebrafishmine/intermine,elsiklab/intermine,JoeCarlson/intermine,justincc/intermine,joshkh/intermine,joshkh/intermine,elsiklab/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,kimrutherford/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,JoeCarlson/intermine,JoeCarlson/intermine,elsiklab/intermine,tomck/intermine,joshkh/intermine,elsiklab/intermine,zebrafishmine/intermine,justincc/intermine,joshkh/intermine,tomck/intermine,tomck/intermine,elsiklab/intermine | package org.intermine.webservice.server.widget;
/*
* Copyright (C) 2002-2014 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import org.intermine.web.logic.widget.EnrichmentOptions;
/**
* WidgetsServiceInput is parameter object representing parameters
* for the WidgetsService web service.
*
* This class is read-only, containing only getters.
*
* @author "Xavier Watkins"
* @author Daniela Butano
*
*/
public class WidgetsServiceInput implements EnrichmentOptions
{
protected String widgetId = null;
protected String bagName = null;
protected String populationBagName = null;
protected boolean savePopulation = false;
protected String filter = null;
protected double maxP = 0.05d;
protected String correction = null;
protected String extraAttribute = null;
/**
* Get the name or id of the widget
* @return the widgetName
*/
public String getWidgetId() {
return widgetId;
}
/**
* Get the type of the bag
* @return the bagName
*/
public String getBagName() {
return bagName;
}
/**
* Get the bag's name for reference population
* @return the bagName
*/
public String getPopulationBagName() {
return populationBagName;
}
/** @return whether we should save the population list. **/
public boolean shouldSavePopulation() {
return savePopulation;
}
@Override
public String getFilter() {
return filter;
}
@Override
public double getMaxPValue() {
return maxP;
}
@Override
public String getCorrection() {
return correction;
}
/** @return any other extra attribute **/
public String getExtraAttribute() {
return extraAttribute;
}
@Override
public String getExtraCorrectionCoefficient() {
return extraAttribute;
}
@Override
public String toString() {
return String.format(
"WidgetServiceInput("
+ "widgetId = %s, bagName = %s,"
+ " maxP = %s, correction = %s,"
+ " pop = %s, savePop = %s, filter = %s,"
+ " extra = %s)",
widgetId, bagName,
maxP, correction,
populationBagName, savePopulation, filter,
extraAttribute);
}
/**
* Class to build Inputs for the Widget Service. This class contains all the
* setters.
* @author Alex Kalderimis
*
*/
public static class Builder extends WidgetsServiceInput
{
/**
* Set the widget name or ID
* @param widgetId the widgetId to set
*/
void setWidgetId(String widgetId) {
this.widgetId = widgetId;
}
/**
* Set the bag's name
* @param bagName the bagName to set
*/
void setBagName(String bagName) {
this.bagName = bagName;
}
/**
* Set the bag's name for reference population
* @param populationBagName the bagName to set
*/
public void setPopulationBagName(String populationBagName) {
this.populationBagName = populationBagName;
}
/** @param savePopulation whether we should save the population list. **/
public void setSavePopulation(boolean savePopulation) {
this.savePopulation = savePopulation;
}
/** @param correction the correction algorithm to use. **/
public void setCorrection(String correction) {
this.correction = correction;
}
/** @param maxp The maximum acceptable p-value **/
public void setMaxP(double maxp) {
this.maxP = maxp;
}
/** @param filter the filter for this request **/
public void setFilter(String filter) {
this.filter = filter;
}
/** @param extraAttribute the extra attribute for this request. **/
public void setExtraAttribute(String extraAttribute) {
this.extraAttribute = extraAttribute;
}
}
}
| intermine/web/main/src/org/intermine/webservice/server/widget/WidgetsServiceInput.java | package org.intermine.webservice.server.widget;
/*
* Copyright (C) 2002-2014 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import org.intermine.web.logic.widget.EnrichmentOptions;
/**
* WidgetsServiceInput is parameter object representing parameters
* for the WidgetsService web service.
*
* This class is read-only, containing only getters.
*
* @author "Xavier Watkins"
* @author Daniela Butano
*
*/
public class WidgetsServiceInput implements EnrichmentOptions
{
protected String widgetId = null;
protected String bagName = null;
protected String populationBagName = null;
protected boolean savePopulation = false;
protected String filter = null;
protected double maxP = 0.05d;
protected String correction = null;
protected String extraAttribute = null;
/**
* Get the name or id of the widget
* @return the widgetName
*/
public String getWidgetId() {
return widgetId;
}
/**
* Get the type of the bag
* @return the bagName
*/
public String getBagName() {
return bagName;
}
/**
* Get the bag's name for reference population
* @return the bagName
*/
public String getPopulationBagName() {
return populationBagName;
}
/** @return whether we should save the population list. **/
public boolean shouldSavePopulation() {
return savePopulation;
}
@Override
public String getFilter() {
return filter;
}
@Override
public double getMaxPValue() {
return maxP;
}
@Override
public String getCorrection() {
return correction;
}
/** @return any other extra attribute **/
public String getExtraAttribute() {
return extraAttribute;
}
@Override
public String getExtraCorrectionCoefficient() {
return extraAttribute;
}
/**
* Class to build Inputs for the Widget Service. This class contains all the
* setters.
* @author Alex Kalderimis
*
*/
public static class Builder extends WidgetsServiceInput
{
/**
* Set the widget name or ID
* @param widgetId the widgetId to set
*/
void setWidgetId(String widgetId) {
this.widgetId = widgetId;
}
/**
* Set the bag's name
* @param bagName the bagName to set
*/
void setBagName(String bagName) {
this.bagName = bagName;
}
/**
* Set the bag's name for reference population
* @param populationBagName the bagName to set
*/
public void setPopulationBagName(String populationBagName) {
this.populationBagName = populationBagName;
}
/** @param savePopulation whether we should save the population list. **/
public void setSavePopulation(boolean savePopulation) {
this.savePopulation = savePopulation;
}
/** @param correction the correction algorithm to use. **/
public void setCorrection(String correction) {
this.correction = correction;
}
/** @param maxp The maximum acceptable p-value **/
public void setMaxP(double maxp) {
this.maxP = maxp;
}
/** @param filter the filter for this request **/
public void setFilter(String filter) {
this.filter = filter;
}
/** @param extraAttribute the extra attribute for this request. **/
public void setExtraAttribute(String extraAttribute) {
this.extraAttribute = extraAttribute;
}
}
}
| Added a helpful toString
| intermine/web/main/src/org/intermine/webservice/server/widget/WidgetsServiceInput.java | Added a helpful toString | <ide><path>ntermine/web/main/src/org/intermine/webservice/server/widget/WidgetsServiceInput.java
<ide> return extraAttribute;
<ide> }
<ide>
<add> @Override
<add> public String toString() {
<add> return String.format(
<add> "WidgetServiceInput("
<add> + "widgetId = %s, bagName = %s,"
<add> + " maxP = %s, correction = %s,"
<add> + " pop = %s, savePop = %s, filter = %s,"
<add> + " extra = %s)",
<add> widgetId, bagName,
<add> maxP, correction,
<add> populationBagName, savePopulation, filter,
<add> extraAttribute);
<add> }
<add>
<ide> /**
<ide> * Class to build Inputs for the Widget Service. This class contains all the
<ide> * setters. |
|
Java | apache-2.0 | f3bbdacd0488106a5a3ff74d14aef9c3d231b3c2 | 0 | aosp-mirror/platform_frameworks_support,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,androidx/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,androidx/androidx,androidx/androidx | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v4.widget;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Transformation;
import android.widget.AbsListView;
/**
* The SwipeRefreshLayout should be used whenever the user can refresh the
* contents of a view via a vertical swipe gesture. The activity that
* instantiates this view should add an OnRefreshListener to be notified
* whenever the swipe to refresh gesture is completed. The SwipeRefreshLayout
* will notify the listener each and every time the gesture is completed again;
* the listener is responsible for correctly determining when to actually
* initiate a refresh of its content. If the listener determines there should
* not be a refresh, it must call setRefreshing(false) to cancel any visual
* indication of a refresh. If an activity wishes to show just the progress
* animation, it should call setRefreshing(true). To disable the gesture and
* progress animation, call setEnabled(false) on the view.
* <p>
* This layout should be made the parent of the view that will be refreshed as a
* result of the gesture and can only support one direct child. This view will
* also be made the target of the gesture and will be forced to match both the
* width and the height supplied in this layout. The SwipeRefreshLayout does not
* provide accessibility events; instead, a menu item must be provided to allow
* refresh of the content wherever this gesture is used.
* </p>
*/
public class SwipeRefreshLayout extends ViewGroup {
// Maps to ProgressBar.Large style
public static final int LARGE = MaterialProgressDrawable.LARGE;
// Maps to ProgressBar default style
public static final int DEFAULT = MaterialProgressDrawable.DEFAULT;
private static final String LOG_TAG = SwipeRefreshLayout.class.getSimpleName();
private static final int MAX_ALPHA = 255;
private static final int STARTING_PROGRESS_ALPHA = (int) (.3f * MAX_ALPHA);
private static final int CIRCLE_DIAMETER = 40;
private static final int CIRCLE_DIAMETER_LARGE = 56;
private static final float DECELERATE_INTERPOLATION_FACTOR = 2f;
private static final int INVALID_POINTER = -1;
private static final float DRAG_RATE = .5f;
// Max amount of circle that can be filled by progress during swipe gesture,
// where 1.0 is a full circle
private static final float MAX_PROGRESS_ANGLE = .8f;
private static final int SCALE_DOWN_DURATION = 150;
private static final int ALPHA_ANIMATION_DURATION = 300;
private static final int ANIMATE_TO_TRIGGER_DURATION = 200;
private static final int ANIMATE_TO_START_DURATION = 200;
// Default background for the progress spinner
private static final int CIRCLE_BG_LIGHT = 0xFFFAFAFA;
// Default offset in dips from the top of the view to where the progress spinner should stop
private static final int DEFAULT_CIRCLE_TARGET = 64;
private View mTarget; // the target of the gesture
private OnRefreshListener mListener;
private boolean mRefreshing = false;
private int mTouchSlop;
private float mTotalDragDistance = -1;
private int mMediumAnimationDuration;
private int mCurrentTargetOffsetTop;
// Whether or not the starting offset has been determined.
private boolean mOriginalOffsetCalculated = false;
private float mInitialMotionY;
private boolean mIsBeingDragged;
private int mActivePointerId = INVALID_POINTER;
// Whether this item is scaled up rather than clipped
private boolean mScale;
// Target is returning to its start offset because it was cancelled or a
// refresh was triggered.
private boolean mReturningToStart;
private final DecelerateInterpolator mDecelerateInterpolator;
private static final int[] LAYOUT_ATTRS = new int[] {
android.R.attr.enabled
};
private CircleImageView mCircleView;
protected int mFrom;
protected int mOriginalOffsetTop;
private MaterialProgressDrawable mProgress;
private Animation mScaleAnimation;
private Animation mScaleDownAnimation;
private Animation mAlphaStartAnimation;
private Animation mAlphaMaxAnimation;
private float mSpinnerFinalOffset;
private boolean mNotify;
private int mCircleWidth;
private int mCircleHeight;
// Whether the client has set a custom starting position;
private boolean mUsingCustomStart;
private Animation.AnimationListener mRefreshListener = new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (mRefreshing) {
// Make sure the progress view is fully visible
mProgress.setAlpha(MAX_ALPHA);
mProgress.start();
if (mNotify) {
if (mListener != null) {
mListener.onRefresh();
}
}
} else {
mProgress.stop();
mCircleView.setVisibility(View.GONE);
// Return the circle to its start position
if (mScale) {
setAnimationProgress(0 /* animation complete and view is hidden */);
} else {
setAnimationProgress(1 /* animation complete and view is showing */);
setTargetOffsetTopAndBottom(-mCircleHeight - mCurrentTargetOffsetTop,
true /* requires update */);
mCircleView.setVisibility(View.VISIBLE);
}
}
mCurrentTargetOffsetTop = mCircleView.getTop();
}
};
private void setColorViewAlpha(int targetAlpha) {
mCircleView.getBackground().setAlpha(targetAlpha);
mProgress.setAlpha(targetAlpha);
}
/**
* The refresh indicator starting and resting position is always positioned
* near the top of the refreshing content. This position is a consistent
* location, but can be adjusted in either direction based on whether or not
* there is a toolbar or actionbar present.
*
* @param scale Set to true if there is no view at a higher z-order than
* where the progress spinner is set to appear.
* @param start The offset in pixels from the top of this view at which the
* progress spinner should appear.
* @param end The offset in pixels from the top of this view at which the
* progress spinner should come to rest after a successful swipe
* gesture.
*/
public void setProgressViewOffset(boolean scale, int start, int end) {
mScale = scale;
mCircleView.setVisibility(View.GONE);
mOriginalOffsetTop = mCurrentTargetOffsetTop = start;
mSpinnerFinalOffset = end;
mUsingCustomStart = true;
mCircleView.invalidate();
}
/**
* The refresh indicator resting position is always positioned near the top
* of the refreshing content. This position is a consistent location, but
* can be adjusted in either direction based on whether or not there is a
* toolbar or actionbar present.
*
* @param scale Set to true if there is no view at a higher z-order than
* where the progress spinner is set to appear.
* @param end The offset in pixels from the top of this view at which the
* progress spinner should come to rest after a successful swipe
* gesture.
*/
public void setProgressViewEndTarget(boolean scale, int end) {
mSpinnerFinalOffset = end;
mScale = scale;
mCircleView.invalidate();
}
/**
* One of DEFAULT, or LARGE.
*/
public void setSize(int size) {
if (size != MaterialProgressDrawable.LARGE && size != MaterialProgressDrawable.DEFAULT) {
return;
}
final DisplayMetrics metrics = getResources().getDisplayMetrics();
if (size == MaterialProgressDrawable.LARGE) {
mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER_LARGE * metrics.density);
} else {
mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);
}
// force the bounds of the progress circle inside the circle view to
// update by setting it to null before updating its size and then
// re-setting it
mCircleView.setImageDrawable(null);
mProgress.updateSizes(size);
mCircleView.setImageDrawable(mProgress);
}
/**
* Simple constructor to use when creating a SwipeRefreshLayout from code.
*
* @param context
*/
public SwipeRefreshLayout(Context context) {
this(context, null);
}
/**
* Constructor that is called when inflating SwipeRefreshLayout from XML.
*
* @param context
* @param attrs
*/
public SwipeRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mMediumAnimationDuration = getResources().getInteger(
android.R.integer.config_mediumAnimTime);
setWillNotDraw(false);
mDecelerateInterpolator = new DecelerateInterpolator(DECELERATE_INTERPOLATION_FACTOR);
final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
setEnabled(a.getBoolean(0, true));
a.recycle();
final DisplayMetrics metrics = getResources().getDisplayMetrics();
mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);
mCircleHeight = (int) (CIRCLE_DIAMETER * metrics.density);
createProgressView();
ViewCompat.setChildrenDrawingOrderEnabled(this, true);
// the absolute offset has to take into account that the circle starts at an offset
mSpinnerFinalOffset = DEFAULT_CIRCLE_TARGET * metrics.density;
mTotalDragDistance = mSpinnerFinalOffset;
}
protected int getChildDrawingOrder (int childCount, int i) {
if (getChildAt(i).equals(mCircleView)) {
return childCount - 1;
}
return i;
}
private void createProgressView() {
mCircleView = new CircleImageView(getContext(), CIRCLE_BG_LIGHT, CIRCLE_DIAMETER/2);
mProgress = new MaterialProgressDrawable(getContext(), this);
mProgress.setBackgroundColor(CIRCLE_BG_LIGHT);
mCircleView.setImageDrawable(mProgress);
addView(mCircleView);
}
/**
* Set the listener to be notified when a refresh is triggered via the swipe
* gesture.
*/
public void setOnRefreshListener(OnRefreshListener listener) {
mListener = listener;
}
/**
* Pre API 11, alpha is used to make the progress circle appear instead of scale.
*/
private boolean isAlphaUsedForScale() {
return android.os.Build.VERSION.SDK_INT < 11;
}
/**
* Notify the widget that refresh state has changed. Do not call this when
* refresh is triggered by a swipe gesture.
*
* @param refreshing Whether or not the view should show refresh progress.
*/
public void setRefreshing(boolean refreshing) {
if (refreshing && mRefreshing != refreshing) {
// scale and show
mRefreshing = refreshing;
setTargetOffsetTopAndBottom(
(int) ((mSpinnerFinalOffset + mOriginalOffsetTop) - mCurrentTargetOffsetTop),
true /* requires update */);
mNotify = false;
startScaleUpAnimation(mRefreshListener);
} else {
setRefreshing(refreshing, false /* notify */);
}
}
private void startScaleUpAnimation(AnimationListener listener) {
mCircleView.setVisibility(View.VISIBLE);
if (android.os.Build.VERSION.SDK_INT >= 11) {
// Pre API 11, alpha is used in place of scale up to show the
// progress circle appearing.
// Don't adjust the alpha during appearance otherwise.
mProgress.setAlpha(MAX_ALPHA);
}
mScaleAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
setAnimationProgress(interpolatedTime);
}
};
mScaleAnimation.setDuration(mMediumAnimationDuration);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleAnimation);
}
/**
* Pre API 11, this does an alpha animation.
* @param progress
*/
private void setAnimationProgress(float progress) {
if (isAlphaUsedForScale()) {
setColorViewAlpha((int) (progress * MAX_ALPHA));
} else {
ViewCompat.setScaleX(mCircleView, progress);
ViewCompat.setScaleY(mCircleView, progress);
}
}
private void setRefreshing(boolean refreshing, final boolean notify) {
if (mRefreshing != refreshing) {
mNotify = notify;
ensureTarget();
mRefreshing = refreshing;
if (mRefreshing) {
animateOffsetToCorrectPosition(mCurrentTargetOffsetTop, mRefreshListener);
} else {
startScaleDownAnimation(mRefreshListener);
}
}
}
private void startScaleDownAnimation(Animation.AnimationListener listener) {
mScaleDownAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
setAnimationProgress(1 - interpolatedTime);
}
};
mScaleDownAnimation.setDuration(SCALE_DOWN_DURATION);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleDownAnimation);
}
private void startProgressAlphaStartAnimation() {
mAlphaStartAnimation = startAlphaAnimation(mProgress.getAlpha(), STARTING_PROGRESS_ALPHA);
}
private void startProgressAlphaMaxAnimation() {
mAlphaMaxAnimation = startAlphaAnimation(mProgress.getAlpha(), MAX_ALPHA);
}
private Animation startAlphaAnimation(final int startingAlpha, final int endingAlpha) {
// Pre API 11, alpha is used in place of scale. Don't also use it to
// show the trigger point.
if (mScale && isAlphaUsedForScale()) {
return null;
}
Animation alpha = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
mProgress
.setAlpha((int) (startingAlpha+ ((endingAlpha - startingAlpha)
* interpolatedTime)));
}
};
alpha.setDuration(ALPHA_ANIMATION_DURATION);
// Clear out the previous animation listeners.
mCircleView.setAnimationListener(null);
mCircleView.clearAnimation();
mCircleView.startAnimation(alpha);
return alpha;
}
/**
* Set the background color of the progress spinner disc.
*
* @param colorRes Resource id of the color.
*/
public void setProgressBackgroundColor(int colorRes) {
mCircleView.setBackgroundColor(colorRes);
mProgress.setBackgroundColor(getResources().getColor(colorRes));
}
/**
* @deprecated Use {@link #setColorSchemeResources(int...)}
*/
@Deprecated
public void setColorScheme(int... colors) {
setColorSchemeResources(colors);
}
/**
* Set the color resources used in the progress animation from color resources.
* The first color will also be the color of the bar that grows in response
* to a user swipe gesture.
*
* @param colorResIds
*/
public void setColorSchemeResources(int... colorResIds) {
final Resources res = getResources();
int[] colorRes = new int[colorResIds.length];
for (int i = 0; i < colorResIds.length; i++) {
colorRes[i] = res.getColor(colorResIds[i]);
}
setColorSchemeColors(colorRes);
}
/**
* Set the colors used in the progress animation. The first
* color will also be the color of the bar that grows in response to a user
* swipe gesture.
*
* @param colors
*/
public void setColorSchemeColors(int... colors) {
ensureTarget();
mProgress.setColorSchemeColors(colors);
}
/**
* @return Whether the SwipeRefreshWidget is actively showing refresh
* progress.
*/
public boolean isRefreshing() {
return mRefreshing;
}
private void ensureTarget() {
// Don't bother getting the parent height if the parent hasn't been laid
// out yet.
if (mTarget == null) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (!child.equals(mCircleView)) {
mTarget = child;
break;
}
}
}
}
/**
* Set the distance to trigger a sync in dips
*
* @param distance
*/
public void setDistanceToTriggerSync(int distance) {
mTotalDragDistance = distance;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
final int width = getMeasuredWidth();
final int height = getMeasuredHeight();
if (getChildCount() == 0) {
return;
}
if (mTarget == null) {
ensureTarget();
}
if (mTarget == null) {
return;
}
final View child = mTarget;
final int childLeft = getPaddingLeft();
final int childTop = getPaddingTop();
final int childWidth = width - getPaddingLeft() - getPaddingRight();
final int childHeight = height - getPaddingTop() - getPaddingBottom();
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
int circleWidth = mCircleView.getMeasuredWidth();
int circleHeight = mCircleView.getMeasuredHeight();
mCircleView.layout((width / 2 - circleWidth / 2), mCurrentTargetOffsetTop,
(width / 2 + circleWidth / 2), mCurrentTargetOffsetTop + circleHeight);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mTarget == null) {
ensureTarget();
}
if (mTarget == null) {
return;
}
mTarget.measure(MeasureSpec.makeMeasureSpec(
getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(
getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY));
mCircleView.measure(MeasureSpec.makeMeasureSpec(mCircleWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(mCircleHeight, MeasureSpec.EXACTLY));
if (!mUsingCustomStart && !mOriginalOffsetCalculated) {
mOriginalOffsetCalculated = true;
mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight();
}
}
/**
* @return Whether it is possible for the child view of this layout to
* scroll up. Override this if the child view is a custom view.
*/
public boolean canChildScrollUp() {
if (android.os.Build.VERSION.SDK_INT < 14) {
if (mTarget instanceof AbsListView) {
final AbsListView absListView = (AbsListView) mTarget;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
} else {
return mTarget.getScrollY() > 0;
}
} else {
return ViewCompat.canScrollVertically(mTarget, -1);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
ensureTarget();
final int action = MotionEventCompat.getActionMasked(ev);
if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
mReturningToStart = false;
}
if (!isEnabled() || mReturningToStart || canChildScrollUp() || mRefreshing) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
setTargetOffsetTopAndBottom(mOriginalOffsetTop - mCircleView.getTop(), true);
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsBeingDragged = false;
final float initialMotionY = getMotionEventY(ev, mActivePointerId);
if (initialMotionY == -1) {
return false;
}
mInitialMotionY = initialMotionY;
case MotionEvent.ACTION_MOVE:
if (mActivePointerId == INVALID_POINTER) {
Log.e(LOG_TAG, "Got ACTION_MOVE event but don't have an active pointer id.");
return false;
}
final float y = getMotionEventY(ev, mActivePointerId);
if (y == -1) {
return false;
}
final float yDiff = y - mInitialMotionY;
if (yDiff > mTouchSlop && !mIsBeingDragged) {
mIsBeingDragged = true;
mProgress.setAlpha(STARTING_PROGRESS_ALPHA);
}
break;
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mIsBeingDragged = false;
mActivePointerId = INVALID_POINTER;
break;
}
return mIsBeingDragged;
}
private float getMotionEventY(MotionEvent ev, int activePointerId) {
final int index = MotionEventCompat.findPointerIndex(ev, activePointerId);
if (index < 0) {
return -1;
}
return MotionEventCompat.getY(ev, index);
}
@Override
public void requestDisallowInterceptTouchEvent(boolean b) {
// Nope.
}
private boolean isAnimationRunning(Animation animation) {
return animation != null && animation.hasStarted() && !animation.hasEnded();
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = MotionEventCompat.getActionMasked(ev);
if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
mReturningToStart = false;
}
if (!isEnabled() || mReturningToStart || canChildScrollUp()) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsBeingDragged = false;
break;
case MotionEvent.ACTION_MOVE: {
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
if (pointerIndex < 0) {
Log.e(LOG_TAG, "Got ACTION_MOVE event but have an invalid active pointer id.");
return false;
}
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE;
if (mIsBeingDragged) {
mProgress.showArrow(true);
float originalDragPercent = overscrollTop / mTotalDragDistance;
if (originalDragPercent < 0) {
return false;
}
float dragPercent = Math.min(1f, Math.abs(originalDragPercent));
float adjustedPercent = (float) Math.max(dragPercent - .4, 0) * 5 / 3;
float extraOS = Math.abs(overscrollTop) - mTotalDragDistance;
float slingshotDist = mSpinnerFinalOffset;
float tensionSlingshotPercent = Math.max(0,
Math.min(extraOS, slingshotDist * 2) / slingshotDist);
float tensionPercent = (float) ((tensionSlingshotPercent / 4) - Math.pow(
(tensionSlingshotPercent / 4), 2)) * 2f;
float extraMove = (slingshotDist) * tensionPercent * 2;
int targetY = mOriginalOffsetTop
+ (int) ((slingshotDist * dragPercent) + extraMove);
// where 1.0f is a full circle
if (mCircleView.getVisibility() != View.VISIBLE) {
mCircleView.setVisibility(View.VISIBLE);
}
if (overscrollTop < mTotalDragDistance) {
if (mScale) {
setAnimationProgress(overscrollTop / mTotalDragDistance);
}
if (mProgress.getAlpha() > STARTING_PROGRESS_ALPHA
&& !isAnimationRunning(mAlphaStartAnimation)) {
// Animate the alpha
startProgressAlphaStartAnimation();
}
float strokeStart = (float) (adjustedPercent * .8f);
mProgress.setStartEndTrim(0f, Math.min(MAX_PROGRESS_ANGLE, strokeStart));
mProgress.setArrowScale(Math.min(1f, adjustedPercent));
} else {
if (mProgress.getAlpha() < MAX_ALPHA
&& !isAnimationRunning(mAlphaMaxAnimation)) {
// Animate the alpha
startProgressAlphaMaxAnimation();
}
}
float rotation = (-0.25f + .4f * adjustedPercent + tensionPercent * 2) * .5f;
mProgress.setProgressRotation(rotation);
setTargetOffsetTopAndBottom(targetY - mCurrentTargetOffsetTop,
true /* requires update */);
}
break;
}
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE;
mIsBeingDragged = false;
if (overscrollTop > mTotalDragDistance) {
setRefreshing(true, true /* notify */);
} else {
// cancel refresh
mRefreshing = false;
mProgress.setStartEndTrim(0f, 0f);
animateOffsetToStartPosition(mCurrentTargetOffsetTop, null);
mProgress.showArrow(false);
}
mActivePointerId = INVALID_POINTER;
return false;
}
}
return true;
}
private void animateOffsetToCorrectPosition(int from, AnimationListener listener) {
mFrom = from;
mAnimateToCorrectPosition.reset();
mAnimateToCorrectPosition.setDuration(ANIMATE_TO_TRIGGER_DURATION);
mAnimateToCorrectPosition.setInterpolator(mDecelerateInterpolator);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mAnimateToCorrectPosition);
}
private void animateOffsetToStartPosition(int from, AnimationListener listener) {
mFrom = from;
mAnimateToStartPosition.reset();
mAnimateToStartPosition.setDuration(ANIMATE_TO_START_DURATION);
mAnimateToStartPosition.setInterpolator(mDecelerateInterpolator);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mAnimateToStartPosition);
}
private final Animation mAnimateToCorrectPosition = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
int targetTop = 0;
int endTarget = (int) (mSpinnerFinalOffset - Math.abs(mOriginalOffsetTop));
targetTop = (mFrom + (int) ((endTarget - mFrom) * interpolatedTime));
int offset = targetTop - mCircleView.getTop();
setTargetOffsetTopAndBottom(offset, false /* requires update */);
}
};
private final Animation mAnimateToStartPosition = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
int targetTop = 0;
targetTop = (mFrom + (int) ((mOriginalOffsetTop - mFrom) * interpolatedTime));
int offset = targetTop - mCircleView.getTop();
setTargetOffsetTopAndBottom(offset, false /* requires update */);
}
};
private void setTargetOffsetTopAndBottom(int offset, boolean requiresUpdate) {
mCircleView.bringToFront();
mCircleView.offsetTopAndBottom(offset);
mCurrentTargetOffsetTop = mCircleView.getTop();
if (requiresUpdate && android.os.Build.VERSION.SDK_INT < 11) {
invalidate();
}
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
}
}
/**
* Classes that wish to be notified when the swipe gesture correctly
* triggers a refresh should implement this interface.
*/
public interface OnRefreshListener {
public void onRefresh();
}
}
| v4/java/android/support/v4/widget/SwipeRefreshLayout.java | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v4.widget;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Transformation;
import android.widget.AbsListView;
/**
* The SwipeRefreshLayout should be used whenever the user can refresh the
* contents of a view via a vertical swipe gesture. The activity that
* instantiates this view should add an OnRefreshListener to be notified
* whenever the swipe to refresh gesture is completed. The SwipeRefreshLayout
* will notify the listener each and every time the gesture is completed again;
* the listener is responsible for correctly determining when to actually
* initiate a refresh of its content. If the listener determines there should
* not be a refresh, it must call setRefreshing(false) to cancel any visual
* indication of a refresh. If an activity wishes to show just the progress
* animation, it should call setRefreshing(true). To disable the gesture and
* progress animation, call setEnabled(false) on the view.
* <p>
* This layout should be made the parent of the view that will be refreshed as a
* result of the gesture and can only support one direct child. This view will
* also be made the target of the gesture and will be forced to match both the
* width and the height supplied in this layout. The SwipeRefreshLayout does not
* provide accessibility events; instead, a menu item must be provided to allow
* refresh of the content wherever this gesture is used.
* </p>
*/
public class SwipeRefreshLayout extends ViewGroup {
// Maps to ProgressBar.Large style
public static final int LARGE = MaterialProgressDrawable.LARGE;
// Maps to ProgressBar default style
public static final int DEFAULT = MaterialProgressDrawable.DEFAULT;
private static final String LOG_TAG = SwipeRefreshLayout.class.getSimpleName();
private static final int MAX_ALPHA = 255;
private static final int STARTING_PROGRESS_ALPHA = (int) (.3f * MAX_ALPHA);
private static final int CIRCLE_DIAMETER = 40;
private static final int CIRCLE_DIAMETER_LARGE = 56;
private static final float DECELERATE_INTERPOLATION_FACTOR = 2f;
private static final int INVALID_POINTER = -1;
private static final float DRAG_RATE = .5f;
// Max amount of circle that can be filled by progress during swipe gesture,
// where 1.0 is a full circle
private static final float MAX_PROGRESS_ANGLE = .8f;
private static final int SCALE_DOWN_DURATION = 150;
private static final int ALPHA_ANIMATION_DURATION = 300;
private static final int ANIMATE_TO_TRIGGER_DURATION = 200;
private static final int ANIMATE_TO_START_DURATION = 200;
// Default background for the progress spinner
private static final int CIRCLE_BG_LIGHT = 0xFFFAFAFA;
// Default offset in dips from the top of the view to where the progress spinner should stop
private static final int DEFAULT_CIRCLE_TARGET = 64;
private View mTarget; // the target of the gesture
private OnRefreshListener mListener;
private boolean mRefreshing = false;
private int mTouchSlop;
private float mTotalDragDistance = -1;
private int mMediumAnimationDuration;
private int mCurrentTargetOffsetTop;
private float mInitialMotionY;
private boolean mIsBeingDragged;
private int mActivePointerId = INVALID_POINTER;
// Whether this item is scaled up rather than clipped
private boolean mScale;
// Target is returning to its start offset because it was cancelled or a
// refresh was triggered.
private boolean mReturningToStart;
private final DecelerateInterpolator mDecelerateInterpolator;
private static final int[] LAYOUT_ATTRS = new int[] {
android.R.attr.enabled
};
private CircleImageView mCircleView;
protected int mFrom;
protected int mOriginalOffsetTop;
private MaterialProgressDrawable mProgress;
private Animation mScaleAnimation;
private Animation mScaleDownAnimation;
private Animation mAlphaStartAnimation;
private Animation mAlphaMaxAnimation;
private float mSpinnerFinalOffset;
private boolean mNotify;
private int mCircleWidth;
private int mCircleHeight;
private Animation.AnimationListener mRefreshListener = new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (mRefreshing) {
// Make sure the progress view is fully visible
mProgress.setAlpha(MAX_ALPHA);
mProgress.start();
if (mNotify) {
if (mListener != null) {
mListener.onRefresh();
}
}
} else {
mProgress.stop();
mCircleView.setVisibility(View.GONE);
// Return the circle to its start position
if (mScale) {
setAnimationProgress(0 /* animation complete and view is hidden */);
} else {
setAnimationProgress(1 /* animation complete and view is showing */);
setTargetOffsetTopAndBottom(-mCircleHeight - mCurrentTargetOffsetTop,
true /* requires update */);
mCircleView.setVisibility(View.VISIBLE);
}
}
mCurrentTargetOffsetTop = mCircleView.getTop();
}
};
private void setColorViewAlpha(int targetAlpha) {
mCircleView.getBackground().setAlpha(targetAlpha);
mProgress.setAlpha(targetAlpha);
}
/**
* The refresh indicator starting and resting position is always positioned
* near the top of the refreshing content. This position is a consistent
* location, but can be adjusted in either direction based on whether or not
* there is a toolbar or actionbar present.
*
* @param scale Set to true if there is no view at a higher z-order than
* where the progress spinner is set to appear.
* @param start The offset in pixels from the top of this view at which the
* progress spinner should appear.
* @param end The offset in pixels from the top of this view at which the
* progress spinner should come to rest after a successful swipe
* gesture.
*/
public void setProgressViewOffset(boolean scale, int start, int end) {
mScale = scale;
mCircleView.setVisibility(View.GONE);
mOriginalOffsetTop = mCurrentTargetOffsetTop = start;
mSpinnerFinalOffset = end;
mCircleView.invalidate();
}
/**
* The refresh indicator resting position is always positioned near the top
* of the refreshing content. This position is a consistent location, but
* can be adjusted in either direction based on whether or not there is a
* toolbar or actionbar present.
*
* @param scale Set to true if there is no view at a higher z-order than
* where the progress spinner is set to appear.
* @param end The offset in pixels from the top of this view at which the
* progress spinner should come to rest after a successful swipe
* gesture.
*/
public void setProgressViewEndTarget(boolean scale, int end) {
mSpinnerFinalOffset = end;
mScale = scale;
mCircleView.invalidate();
}
/**
* One of DEFAULT, or LARGE.
*/
public void setSize(int size) {
if (size != MaterialProgressDrawable.LARGE && size != MaterialProgressDrawable.DEFAULT) {
return;
}
final DisplayMetrics metrics = getResources().getDisplayMetrics();
if (size == MaterialProgressDrawable.LARGE) {
mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER_LARGE * metrics.density);
} else {
mCircleHeight = mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);
}
// force the bounds of the progress circle inside the circle view to
// update by setting it to null before updating its size and then
// re-setting it
mCircleView.setImageDrawable(null);
mProgress.updateSizes(size);
mCircleView.setImageDrawable(mProgress);
}
/**
* Simple constructor to use when creating a SwipeRefreshLayout from code.
*
* @param context
*/
public SwipeRefreshLayout(Context context) {
this(context, null);
}
/**
* Constructor that is called when inflating SwipeRefreshLayout from XML.
*
* @param context
* @param attrs
*/
public SwipeRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mMediumAnimationDuration = getResources().getInteger(
android.R.integer.config_mediumAnimTime);
setWillNotDraw(false);
mDecelerateInterpolator = new DecelerateInterpolator(DECELERATE_INTERPOLATION_FACTOR);
final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
setEnabled(a.getBoolean(0, true));
a.recycle();
final DisplayMetrics metrics = getResources().getDisplayMetrics();
mCircleWidth = (int) (CIRCLE_DIAMETER * metrics.density);
mCircleHeight = (int) (CIRCLE_DIAMETER * metrics.density);
createProgressView();
ViewCompat.setChildrenDrawingOrderEnabled(this, true);
// the absolute offset has to take into account that the circle starts at an offset
mSpinnerFinalOffset = DEFAULT_CIRCLE_TARGET * metrics.density;
mTotalDragDistance = mSpinnerFinalOffset;
}
protected int getChildDrawingOrder (int childCount, int i) {
if (getChildAt(i).equals(mCircleView)) {
return childCount - 1;
}
return i;
}
private void createProgressView() {
mCircleView = new CircleImageView(getContext(), CIRCLE_BG_LIGHT, CIRCLE_DIAMETER/2);
mProgress = new MaterialProgressDrawable(getContext(), this);
mProgress.setBackgroundColor(CIRCLE_BG_LIGHT);
mCircleView.setImageDrawable(mProgress);
addView(mCircleView);
mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleHeight;
}
/**
* Set the listener to be notified when a refresh is triggered via the swipe
* gesture.
*/
public void setOnRefreshListener(OnRefreshListener listener) {
mListener = listener;
}
/**
* Pre API 11, alpha is used to make the progress circle appear instead of scale.
*/
private boolean isAlphaUsedForScale() {
return android.os.Build.VERSION.SDK_INT < 11;
}
/**
* Notify the widget that refresh state has changed. Do not call this when
* refresh is triggered by a swipe gesture.
*
* @param refreshing Whether or not the view should show refresh progress.
*/
public void setRefreshing(boolean refreshing) {
if (refreshing && mRefreshing != refreshing) {
// scale and show
mRefreshing = refreshing;
setTargetOffsetTopAndBottom(
(int) ((mSpinnerFinalOffset + mOriginalOffsetTop) - mCurrentTargetOffsetTop),
true /* requires update */);
mNotify = false;
startScaleUpAnimation(mRefreshListener);
} else {
setRefreshing(refreshing, false /* notify */);
}
}
private void startScaleUpAnimation(AnimationListener listener) {
mCircleView.setVisibility(View.VISIBLE);
if (android.os.Build.VERSION.SDK_INT >= 11) {
// Pre API 11, alpha is used in place of scale up to show the
// progress circle appearing.
// Don't adjust the alpha during appearance otherwise.
mProgress.setAlpha(MAX_ALPHA);
}
mScaleAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
setAnimationProgress(interpolatedTime);
}
};
mScaleAnimation.setDuration(mMediumAnimationDuration);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleAnimation);
}
/**
* Pre API 11, this does an alpha animation.
* @param progress
*/
private void setAnimationProgress(float progress) {
if (isAlphaUsedForScale()) {
setColorViewAlpha((int) (progress * MAX_ALPHA));
} else {
ViewCompat.setScaleX(mCircleView, progress);
ViewCompat.setScaleY(mCircleView, progress);
}
}
private void setRefreshing(boolean refreshing, final boolean notify) {
if (mRefreshing != refreshing) {
mNotify = notify;
ensureTarget();
mRefreshing = refreshing;
if (mRefreshing) {
animateOffsetToCorrectPosition(mCurrentTargetOffsetTop, mRefreshListener);
} else {
startScaleDownAnimation(mRefreshListener);
}
}
}
private void startScaleDownAnimation(Animation.AnimationListener listener) {
mScaleDownAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
setAnimationProgress(1 - interpolatedTime);
}
};
mScaleDownAnimation.setDuration(SCALE_DOWN_DURATION);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mScaleDownAnimation);
}
private void startProgressAlphaStartAnimation() {
mAlphaStartAnimation = startAlphaAnimation(mProgress.getAlpha(), STARTING_PROGRESS_ALPHA);
}
private void startProgressAlphaMaxAnimation() {
mAlphaMaxAnimation = startAlphaAnimation(mProgress.getAlpha(), MAX_ALPHA);
}
private Animation startAlphaAnimation(final int startingAlpha, final int endingAlpha) {
// Pre API 11, alpha is used in place of scale. Don't also use it to
// show the trigger point.
if (mScale && isAlphaUsedForScale()) {
return null;
}
Animation alpha = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
mProgress
.setAlpha((int) (startingAlpha+ ((endingAlpha - startingAlpha)
* interpolatedTime)));
}
};
alpha.setDuration(ALPHA_ANIMATION_DURATION);
// Clear out the previous animation listeners.
mCircleView.setAnimationListener(null);
mCircleView.clearAnimation();
mCircleView.startAnimation(alpha);
return alpha;
}
/**
* Set the background color of the progress spinner disc.
*
* @param colorRes Resource id of the color.
*/
public void setProgressBackgroundColor(int colorRes) {
mCircleView.setBackgroundColor(colorRes);
mProgress.setBackgroundColor(getResources().getColor(colorRes));
}
/**
* @deprecated Use {@link #setColorSchemeResources(int...)}
*/
@Deprecated
public void setColorScheme(int... colors) {
setColorSchemeResources(colors);
}
/**
* Set the color resources used in the progress animation from color resources.
* The first color will also be the color of the bar that grows in response
* to a user swipe gesture.
*
* @param colorResIds
*/
public void setColorSchemeResources(int... colorResIds) {
final Resources res = getResources();
int[] colorRes = new int[colorResIds.length];
for (int i = 0; i < colorResIds.length; i++) {
colorRes[i] = res.getColor(colorResIds[i]);
}
setColorSchemeColors(colorRes);
}
/**
* Set the colors used in the progress animation. The first
* color will also be the color of the bar that grows in response to a user
* swipe gesture.
*
* @param colors
*/
public void setColorSchemeColors(int... colors) {
ensureTarget();
mProgress.setColorSchemeColors(colors);
}
/**
* @return Whether the SwipeRefreshWidget is actively showing refresh
* progress.
*/
public boolean isRefreshing() {
return mRefreshing;
}
private void ensureTarget() {
// Don't bother getting the parent height if the parent hasn't been laid
// out yet.
if (mTarget == null) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (!child.equals(mCircleView)) {
mTarget = child;
break;
}
}
}
}
/**
* Set the distance to trigger a sync in dips
*
* @param distance
*/
public void setDistanceToTriggerSync(int distance) {
mTotalDragDistance = distance;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
final int width = getMeasuredWidth();
final int height = getMeasuredHeight();
if (getChildCount() == 0) {
return;
}
if (mTarget == null) {
ensureTarget();
}
if (mTarget == null) {
return;
}
final View child = mTarget;
final int childLeft = getPaddingLeft();
final int childTop = getPaddingTop();
final int childWidth = width - getPaddingLeft() - getPaddingRight();
final int childHeight = height - getPaddingTop() - getPaddingBottom();
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
int circleWidth = mCircleView.getMeasuredWidth();
int circleHeight = mCircleView.getMeasuredHeight();
mCircleView.layout((width / 2 - circleWidth / 2), mCurrentTargetOffsetTop,
(width / 2 + circleWidth / 2), mCurrentTargetOffsetTop + circleHeight);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mTarget == null) {
ensureTarget();
}
if (mTarget == null) {
return;
}
mTarget.measure(MeasureSpec.makeMeasureSpec(
getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(
getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY));
mCircleView.measure(MeasureSpec.makeMeasureSpec(mCircleWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(mCircleHeight, MeasureSpec.EXACTLY));
}
/**
* @return Whether it is possible for the child view of this layout to
* scroll up. Override this if the child view is a custom view.
*/
public boolean canChildScrollUp() {
if (android.os.Build.VERSION.SDK_INT < 14) {
if (mTarget instanceof AbsListView) {
final AbsListView absListView = (AbsListView) mTarget;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
} else {
return mTarget.getScrollY() > 0;
}
} else {
return ViewCompat.canScrollVertically(mTarget, -1);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
ensureTarget();
final int action = MotionEventCompat.getActionMasked(ev);
if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
mReturningToStart = false;
}
if (!isEnabled() || mReturningToStart || canChildScrollUp() || mRefreshing) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
setTargetOffsetTopAndBottom(mOriginalOffsetTop - mCircleView.getTop(), true);
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsBeingDragged = false;
final float initialMotionY = getMotionEventY(ev, mActivePointerId);
if (initialMotionY == -1) {
return false;
}
mInitialMotionY = initialMotionY;
case MotionEvent.ACTION_MOVE:
if (mActivePointerId == INVALID_POINTER) {
Log.e(LOG_TAG, "Got ACTION_MOVE event but don't have an active pointer id.");
return false;
}
final float y = getMotionEventY(ev, mActivePointerId);
if (y == -1) {
return false;
}
final float yDiff = y - mInitialMotionY;
if (yDiff > mTouchSlop && !mIsBeingDragged) {
mIsBeingDragged = true;
mProgress.setAlpha(STARTING_PROGRESS_ALPHA);
}
break;
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mIsBeingDragged = false;
mActivePointerId = INVALID_POINTER;
break;
}
return mIsBeingDragged;
}
private float getMotionEventY(MotionEvent ev, int activePointerId) {
final int index = MotionEventCompat.findPointerIndex(ev, activePointerId);
if (index < 0) {
return -1;
}
return MotionEventCompat.getY(ev, index);
}
@Override
public void requestDisallowInterceptTouchEvent(boolean b) {
// Nope.
}
private boolean isAnimationRunning(Animation animation) {
return animation != null && animation.hasStarted() && !animation.hasEnded();
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = MotionEventCompat.getActionMasked(ev);
if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
mReturningToStart = false;
}
if (!isEnabled() || mReturningToStart || canChildScrollUp()) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsBeingDragged = false;
break;
case MotionEvent.ACTION_MOVE: {
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
if (pointerIndex < 0) {
Log.e(LOG_TAG, "Got ACTION_MOVE event but have an invalid active pointer id.");
return false;
}
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE;
if (mIsBeingDragged) {
mProgress.showArrow(true);
float originalDragPercent = overscrollTop / mTotalDragDistance;
if (originalDragPercent < 0) {
return false;
}
float dragPercent = Math.min(1f, Math.abs(originalDragPercent));
float adjustedPercent = (float) Math.max(dragPercent - .4, 0) * 5 / 3;
float extraOS = Math.abs(overscrollTop) - mTotalDragDistance;
float slingshotDist = mSpinnerFinalOffset;
float tensionSlingshotPercent = Math.max(0,
Math.min(extraOS, slingshotDist * 2) / slingshotDist);
float tensionPercent = (float) ((tensionSlingshotPercent / 4) - Math.pow(
(tensionSlingshotPercent / 4), 2)) * 2f;
float extraMove = (slingshotDist) * tensionPercent * 2;
int targetY = mOriginalOffsetTop
+ (int) ((slingshotDist * dragPercent) + extraMove);
// where 1.0f is a full circle
if (mCircleView.getVisibility() != View.VISIBLE) {
mCircleView.setVisibility(View.VISIBLE);
}
if (overscrollTop < mTotalDragDistance) {
if (mScale) {
setAnimationProgress(overscrollTop / mTotalDragDistance);
}
if (mProgress.getAlpha() > STARTING_PROGRESS_ALPHA
&& !isAnimationRunning(mAlphaStartAnimation)) {
// Animate the alpha
startProgressAlphaStartAnimation();
}
float strokeStart = (float) (adjustedPercent * .8f);
mProgress.setStartEndTrim(0f, Math.min(MAX_PROGRESS_ANGLE, strokeStart));
mProgress.setArrowScale(Math.min(1f, adjustedPercent));
} else {
if (mProgress.getAlpha() < MAX_ALPHA
&& !isAnimationRunning(mAlphaMaxAnimation)) {
// Animate the alpha
startProgressAlphaMaxAnimation();
}
}
float rotation = (-0.25f + .4f * adjustedPercent + tensionPercent * 2) * .5f;
mProgress.setProgressRotation(rotation);
setTargetOffsetTopAndBottom(targetY - mCurrentTargetOffsetTop,
true /* requires update */);
}
break;
}
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE;
mIsBeingDragged = false;
if (overscrollTop > mTotalDragDistance) {
setRefreshing(true, true /* notify */);
} else {
// cancel refresh
mRefreshing = false;
mProgress.setStartEndTrim(0f, 0f);
animateOffsetToStartPosition(mCurrentTargetOffsetTop, null);
mProgress.showArrow(false);
}
mActivePointerId = INVALID_POINTER;
return false;
}
}
return true;
}
private void animateOffsetToCorrectPosition(int from, AnimationListener listener) {
mFrom = from;
mAnimateToCorrectPosition.reset();
mAnimateToCorrectPosition.setDuration(ANIMATE_TO_TRIGGER_DURATION);
mAnimateToCorrectPosition.setInterpolator(mDecelerateInterpolator);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mAnimateToCorrectPosition);
}
private void animateOffsetToStartPosition(int from, AnimationListener listener) {
mFrom = from;
mAnimateToStartPosition.reset();
mAnimateToStartPosition.setDuration(ANIMATE_TO_START_DURATION);
mAnimateToStartPosition.setInterpolator(mDecelerateInterpolator);
if (listener != null) {
mCircleView.setAnimationListener(listener);
}
mCircleView.clearAnimation();
mCircleView.startAnimation(mAnimateToStartPosition);
}
private final Animation mAnimateToCorrectPosition = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
int targetTop = 0;
int endTarget = (int) (mSpinnerFinalOffset - Math.abs(mOriginalOffsetTop));
targetTop = (mFrom + (int) ((endTarget - mFrom) * interpolatedTime));
int offset = targetTop - mCircleView.getTop();
setTargetOffsetTopAndBottom(offset, false /* requires update */);
}
};
private final Animation mAnimateToStartPosition = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
int targetTop = 0;
if (mFrom != mOriginalOffsetTop) {
targetTop = (mFrom + (int) ((mOriginalOffsetTop - mFrom) * interpolatedTime));
}
int offset = targetTop - mCircleView.getTop();
setTargetOffsetTopAndBottom(offset, false /* requires update */);
}
};
private void setTargetOffsetTopAndBottom(int offset, boolean requiresUpdate) {
mCircleView.bringToFront();
mCircleView.offsetTopAndBottom(offset);
mCurrentTargetOffsetTop = mCircleView.getTop();
if (requiresUpdate && android.os.Build.VERSION.SDK_INT < 11) {
invalidate();
}
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
}
}
/**
* Classes that wish to be notified when the swipe gesture correctly
* triggers a refresh should implement this interface.
*/
public interface OnRefreshListener {
public void onRefresh();
}
}
| am f076ce0e: am b4ac9016: Merge "Use the negative measured height as the starting offset of the progress view" into lmp-dev
* commit 'f076ce0ef9b8374d617841a8b3e921925153c96d':
Use the negative measured height as the starting offset of the progress view
| v4/java/android/support/v4/widget/SwipeRefreshLayout.java | am f076ce0e: am b4ac9016: Merge "Use the negative measured height as the starting offset of the progress view" into lmp-dev | <ide><path>4/java/android/support/v4/widget/SwipeRefreshLayout.java
<ide> private float mTotalDragDistance = -1;
<ide> private int mMediumAnimationDuration;
<ide> private int mCurrentTargetOffsetTop;
<add> // Whether or not the starting offset has been determined.
<add> private boolean mOriginalOffsetCalculated = false;
<ide>
<ide> private float mInitialMotionY;
<ide> private boolean mIsBeingDragged;
<ide> private int mCircleWidth;
<ide>
<ide> private int mCircleHeight;
<add>
<add> // Whether the client has set a custom starting position;
<add> private boolean mUsingCustomStart;
<ide>
<ide> private Animation.AnimationListener mRefreshListener = new Animation.AnimationListener() {
<ide> @Override
<ide> mCircleView.setVisibility(View.GONE);
<ide> mOriginalOffsetTop = mCurrentTargetOffsetTop = start;
<ide> mSpinnerFinalOffset = end;
<add> mUsingCustomStart = true;
<ide> mCircleView.invalidate();
<ide> }
<ide>
<ide> mProgress.setBackgroundColor(CIRCLE_BG_LIGHT);
<ide> mCircleView.setImageDrawable(mProgress);
<ide> addView(mCircleView);
<del> mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleHeight;
<ide> }
<ide>
<ide> /**
<ide> getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY));
<ide> mCircleView.measure(MeasureSpec.makeMeasureSpec(mCircleWidth, MeasureSpec.EXACTLY),
<ide> MeasureSpec.makeMeasureSpec(mCircleHeight, MeasureSpec.EXACTLY));
<add> if (!mUsingCustomStart && !mOriginalOffsetCalculated) {
<add> mOriginalOffsetCalculated = true;
<add> mCurrentTargetOffsetTop = mOriginalOffsetTop = -mCircleView.getMeasuredHeight();
<add> }
<ide> }
<ide>
<ide> /**
<ide> @Override
<ide> public void applyTransformation(float interpolatedTime, Transformation t) {
<ide> int targetTop = 0;
<del> if (mFrom != mOriginalOffsetTop) {
<del> targetTop = (mFrom + (int) ((mOriginalOffsetTop - mFrom) * interpolatedTime));
<del> }
<add> targetTop = (mFrom + (int) ((mOriginalOffsetTop - mFrom) * interpolatedTime));
<ide> int offset = targetTop - mCircleView.getTop();
<ide> setTargetOffsetTopAndBottom(offset, false /* requires update */);
<ide> } |
|
Java | mit | c09f0b9f1af6a449ef9fb89a516231563116fbc5 | 0 | Narentharaa/evnts,naren-vivek/evnts | package com.code.hacks.codered.evnts.evnts.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.code.hacks.codered.evnts.evnts.R;
import com.code.hacks.codered.evnts.evnts.adapters.EventListAdapter;
import com.code.hacks.codered.evnts.evnts.bean.Event;
import com.code.hacks.codered.evnts.evnts.models.Events;
import com.google.gson.Gson;
/**
* Created by sudharsanan on 4/15/15.
*/
public class HomeFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private RecyclerView eventRecyclerView;
private RecyclerView.LayoutManager recylerLayoutManager;
private EventListAdapter eventListAdapter;
Context context;
RequestQueue queue;
public static HomeFragment newInstance(int sectionNumber) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
eventRecyclerView = (RecyclerView) rootView.findViewById(R.id.event_recycler_view);
eventRecyclerView.setHasFixedSize(true);
recylerLayoutManager = new LinearLayoutManager(getActivity());
eventRecyclerView.setLayoutManager(recylerLayoutManager);
queue = Volley.newRequestQueue(getContext());
context = getContext();
// new FetchEvents().execute(getArguments().getInt(ARG_SECTION_NUMBER));
//TODO Remove after server startup
// events = new Events();
// Gson gson = new Gson();
// String eventsJSON = Util.readJSONFile("events.json", getContext());
// events = gson.fromJson(eventsJSON, Events.class);
addData();
return rootView;
}
// private class FetchEvents extends AsyncTask<Integer, Integer, ArrayList<Event>> {
//
// @Override
// protected ArrayList<Event> doInBackground(Integer... sectionNumber) {
// return addData();
// }
//
// @Override
// protected void onPostExecute(ArrayList<Event> eventArrayList) {
// super.onPostExecute(eventArrayList);
//
// }
// }
private void addData() {
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.GET, "http://6172ea19.ngrok.io/api/v1/events",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Gson gson = new Gson();
Events events = gson.fromJson(response, Events.class);
for (Event event : events.getEvents())
event.setImageUrl("http://sudharti.github.io/paper/assets/img/img-8.jpg");
eventListAdapter = new EventListAdapter(getActivity(), events.getEvents());
eventRecyclerView.setAdapter(eventListAdapter);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Error while fetching events.", Toast.LENGTH_SHORT).show();
}
});
}
}
| app/src/main/java/com/code/hacks/codered/evnts/evnts/fragments/HomeFragment.java | package com.code.hacks.codered.evnts.evnts.fragments;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.code.hacks.codered.evnts.evnts.R;
import com.code.hacks.codered.evnts.evnts.adapters.EventListAdapter;
import com.code.hacks.codered.evnts.evnts.bean.Event;
import com.code.hacks.codered.evnts.evnts.models.Events;
import com.google.gson.Gson;
import java.util.ArrayList;
/**
* Created by sudharsanan on 4/15/15.
*/
public class HomeFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private RecyclerView eventRecyclerView;
private RecyclerView.LayoutManager recylerLayoutManager;
private EventListAdapter eventListAdapter;
Context context;
RequestQueue queue;
public static HomeFragment newInstance(int sectionNumber) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
eventRecyclerView = (RecyclerView) rootView.findViewById(R.id.event_recycler_view);
eventRecyclerView.setHasFixedSize(true);
recylerLayoutManager = new LinearLayoutManager(getActivity());
eventRecyclerView.setLayoutManager(recylerLayoutManager);
queue = Volley.newRequestQueue(getContext());
context = getContext();
// new FetchEvents().execute(getArguments().getInt(ARG_SECTION_NUMBER));
//TODO Remove after server startup
// events = new Events();
// Gson gson = new Gson();
// String eventsJSON = Util.readJSONFile("events.json", getContext());
// events = gson.fromJson(eventsJSON, Events.class);
addData();
return rootView;
}
private class FetchEvents extends AsyncTask<Integer, Integer, ArrayList<Event>> {
@Override
protected ArrayList<Event> doInBackground(Integer... sectionNumber) {
return addData();
}
@Override
protected void onPostExecute(ArrayList<Event> eventArrayList) {
super.onPostExecute(eventArrayList);
}
}
private ArrayList<Event> addData() {
ArrayList<Event> resultList = new ArrayList<Event>();
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.GET, "http://6172ea19.ngrok.io/api/v1/events", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Gson gson = new Gson();
Events events = gson.fromJson(response, Events.class);
for (Event event : events.getEvents())
event.setImageUrl("http://sudharti.github.io/paper/assets/img/img-8.jpg");
eventListAdapter = new EventListAdapter(getActivity(), events.getEvents());
eventRecyclerView.setAdapter(eventListAdapter);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Error while fetching events.", Toast.LENGTH_SHORT).show();
Log.d("EVENT", "Failed to fetch");
}
});
// for (Event event : events.getEvents()) {
// event.setImageUrl("http://sudharti.github.io/paper/assets/img/img-8.jpg");
// resultList.add(event);
// }
return resultList;
}
}
| Events REST call
| app/src/main/java/com/code/hacks/codered/evnts/evnts/fragments/HomeFragment.java | Events REST call | <ide><path>pp/src/main/java/com/code/hacks/codered/evnts/evnts/fragments/HomeFragment.java
<ide> package com.code.hacks.codered.evnts.evnts.fragments;
<ide>
<ide> import android.content.Context;
<del>import android.os.AsyncTask;
<ide> import android.os.Bundle;
<ide> import android.support.annotation.Nullable;
<ide> import android.support.v4.app.Fragment;
<ide> import android.support.v7.widget.LinearLayoutManager;
<ide> import android.support.v7.widget.RecyclerView;
<del>import android.util.Log;
<ide> import android.view.LayoutInflater;
<ide> import android.view.View;
<ide> import android.view.ViewGroup;
<ide> import com.code.hacks.codered.evnts.evnts.bean.Event;
<ide> import com.code.hacks.codered.evnts.evnts.models.Events;
<ide> import com.google.gson.Gson;
<del>
<del>import java.util.ArrayList;
<ide>
<ide> /**
<ide> * Created by sudharsanan on 4/15/15.
<ide> return rootView;
<ide> }
<ide>
<del> private class FetchEvents extends AsyncTask<Integer, Integer, ArrayList<Event>> {
<add>// private class FetchEvents extends AsyncTask<Integer, Integer, ArrayList<Event>> {
<add>//
<add>// @Override
<add>// protected ArrayList<Event> doInBackground(Integer... sectionNumber) {
<add>// return addData();
<add>// }
<add>//
<add>// @Override
<add>// protected void onPostExecute(ArrayList<Event> eventArrayList) {
<add>// super.onPostExecute(eventArrayList);
<add>//
<add>// }
<add>// }
<ide>
<del> @Override
<del> protected ArrayList<Event> doInBackground(Integer... sectionNumber) {
<del> return addData();
<del> }
<del>
<del> @Override
<del> protected void onPostExecute(ArrayList<Event> eventArrayList) {
<del> super.onPostExecute(eventArrayList);
<del>
<del> }
<del> }
<del>
<del> private ArrayList<Event> addData() {
<del> ArrayList<Event> resultList = new ArrayList<Event>();
<add> private void addData() {
<ide>
<ide> RequestQueue queue = Volley.newRequestQueue(context);
<ide>
<del> StringRequest sr = new StringRequest(Request.Method.GET, "http://6172ea19.ngrok.io/api/v1/events", new Response.Listener<String>() {
<del> @Override
<del> public void onResponse(String response) {
<del> Gson gson = new Gson();
<del> Events events = gson.fromJson(response, Events.class);
<del> for (Event event : events.getEvents())
<del> event.setImageUrl("http://sudharti.github.io/paper/assets/img/img-8.jpg");
<del> eventListAdapter = new EventListAdapter(getActivity(), events.getEvents());
<del> eventRecyclerView.setAdapter(eventListAdapter);
<del> }
<del> }, new Response.ErrorListener() {
<add> StringRequest sr = new StringRequest(Request.Method.GET, "http://6172ea19.ngrok.io/api/v1/events",
<add> new Response.Listener<String>() {
<add> @Override
<add> public void onResponse(String response) {
<add> Gson gson = new Gson();
<add> Events events = gson.fromJson(response, Events.class);
<add> for (Event event : events.getEvents())
<add> event.setImageUrl("http://sudharti.github.io/paper/assets/img/img-8.jpg");
<add>
<add> eventListAdapter = new EventListAdapter(getActivity(), events.getEvents());
<add> eventRecyclerView.setAdapter(eventListAdapter);
<add> }
<add> }, new Response.ErrorListener() {
<ide> @Override
<ide> public void onErrorResponse(VolleyError error) {
<ide> Toast.makeText(context, "Error while fetching events.", Toast.LENGTH_SHORT).show();
<del> Log.d("EVENT", "Failed to fetch");
<ide> }
<ide> });
<ide>
<del>// for (Event event : events.getEvents()) {
<del>// event.setImageUrl("http://sudharti.github.io/paper/assets/img/img-8.jpg");
<del>// resultList.add(event);
<del>// }
<del>
<del> return resultList;
<ide> }
<ide> } |
|
JavaScript | mit | 02566e8744f599be5fbcb1462f4872a421281217 | 0 | hustcer/star | #!/usr/bin/env node
/**
* @author hustcer
* @license MIT
* @copyright TraceInvest.com
* @create 05/18/2015
*/
"use strict";
let _ = require('lodash'),
colors = require('colors'),
Promise = require('bluebird'),
cmd = require('commander');
const pkg = require('./package.json');
let conf = require('./lib/conf.js').conf;
let action = null; // cmd action
/**
* Available colors are:
* bold, italic, underline, inverse, yellow, cyan, white,
* green, red, grey, blue, rainbow, zebra, random, magenta,
*/
const COLOR_THEME = {
error : 'red',
info : 'blue',
data : 'grey',
header : 'blue',
warn : 'yellow',
em : 'magenta'
};
colors.setTheme(COLOR_THEME);
cmd
.version(pkg.version)
.usage('[options]' + ' OR'.em + ' star code1,code2,code3...,codeN')
.description('Star is a command line tool for STock Analysis and Research.')
.option('-a, --all' , 'display all stocks.')
.option('-o, --hold' , 'display all held stocks.')
.option('-M, --margin' , 'display stocks that support Margin.')
.option('-C, --cal' , 'display finance calendar of the future month.')
.option('-I, --ignore' , 'display all ignored stocks.')
.option('-i, --insider [c]' , 'display insider trading records of specified stocks. data source: sse or szse')
.option(' --code [code]' , 'specify the stock code of insider tradings you want to query. data source: traceinvest.com')
.option(' --market <mkt>' , 'specify the market of insider trading query, case insensitive:SZM-深圳主板, SZGEM-深圳创业板, SZSME-深圳中小板,\n' + ' '.repeat(20) +
' SHM-上海主板. multiple market should be separated by "," or ",". ')
.option(' --top-buy' , 'query top buy of insider tradings, should be used with "-i" or "--insider". time span:1m~12m.')
.option(' --top-sell' , 'query top sell of insider tradings, should be used with "-i" or "--insider". time span:1m~12m.')
.option(' --latest-sz' , 'query latest insider tradings of ShenZhen market, should be used with "-i" or "--insider". data source: szse')
.option(' --latest-sh' , 'query latest insider tradings of ShangHai market, should be used with "-i" or "--insider". data source: sse')
.option(' --show-detail' , 'show detail latest insider trading records, should be used with "-i" or "--insider".')
.option('-w, --watch [c1...]', 'watch specified stocks or watch all the stocks in watch list.')
.option('-r, --reverse' , 'sort stocks in ascending order according to designated field.')
.option('-l, --limit <n>' , 'set total display limit of current page.', parseInt)
.option('-p, --page <n>' , 'specify the page index to display.', parseInt)
.option('-d, --data <data>' , 'specify data provider, should be one of "sina" or "tencent".')
.option('-f, --file <file>' , 'specify the symbol file path.')
.option('--from <2014/06/01>', 'specify the beginning date of insider tradings.')
.option('--to <2015/07/09>' , 'specify the ending date of insider tradings.')
.option('--span <3m>' , 'specify the month span of insider tradings ahead of today, should be 1m~24m.')
.option('-L, --lte <pct> ' , 'filter the symbols whose upside potential is lower than or equal to the specified percentage.', parseInt)
.option('-G, --gte <pct> ' , 'filter the symbols whose upside potential is greater than or equal to the specified percentage.', parseInt)
.option('-U, --under <star>' , 'filter the symbols whose star is under or equal to the specified star value.', parseInt)
.option('-A, --above <star>' , 'filter the symbols whose star is above or equal to the specified star value.', parseInt)
.option('--lteb [pct]' , "filter the symbols whose current price is lower than or equal to it's buy/cheap price", parseInt)
.option('--gtes [pct]' , "filter the symbols whose current price is greater than or equal to it's sell/expensive price", parseInt)
.option('-g, --grep <kw> ' , 'specify the keyword to grep in name or comment, multiple keywords should be separated by ",".')
.option('--remove <kw> ' , 'remove the symbols from result with the specified keywords in name or comment, multiple keywords should be separated by ",".')
.option('-e, --exclude <pre>', 'exclude stocks whose code number begin with: 300,600,002 or 000, etc. multiple prefixs can be\n' + ' '.repeat(20) +
' used and should be separated by "," or ",". ')
.option('-c, --contain <pre>', 'display stocks whose code number begin with: 300,600,002 or 000, etc. multiple prefixs can be\n' + ' '.repeat(20) +
' used and should be separated by "," or ",". ')
.option('-s, --sort <sort>' , 'specify sorting field, could be sorted by: code/star/price/targetp/incp/bdiff/sdiff/capacity/\n' + ' '.repeat(20) +
' pe/pb to sort stocks by code, star, price, price to target percent, price increase percent, \n' + ' '.repeat(20) +
' (s.price - s.cheap)/s.price, (s.price - s.expensive)/s.price, capacity, PE and PB separately.\n' + ' '.repeat(20) +
' and sort by capacity/pe/pb only works while using tencent data source.')
.parse(process.argv);
let actions = {
'WATCH' : function(){
let Watch = require('./lib/watch.js').Watch;
Watch.doWatch(cmd.watch);
},
'CAL' : function(){
let Cal = require('./lib/cal.js').Cal;
Cal.showCal();
},
'INSIDER': function(){
let async = require('async');
let Insider = require('./lib/insider.js').Insider;
if(cmd.latestSz){ Insider.querySZLatest(); return false; }
if(cmd.latestSh){ Insider.querySHLatest(); return false; }
if(cmd.topBuy) { Insider.queryTopList('BV'); return false; }
if(cmd.topSell) { Insider.queryTopList('SV'); return false; }
if(cmd.insider === true){ Insider.queryMiscInsider(); return false; }
let query = cmd.insider.replace(/,/g, ',');
let symbols = _.trimRight(query, ',').split(',');
if(symbols.length > conf.chunkSize){
console.error(('You can query at most ' + conf.chunkSize + ' symbols once.').error);
return false;
}
async.eachSeries(symbols, function(c, callback){
Insider.queryInsider(c, callback);
}, function(){
console.log('ALL DONE!');
});
},
'QUERY' : function(){
let Query = require('./lib/query.js').Query;
Query.doQuery(cmd.args[0]);
},
'TRACE' : function(){
let Trace = require('./lib/trace.js').Trace;
let symbols = Trace.getFilteredSymbols();
if(!symbols){ return false; }
let symList = _.chunk(symbols, conf.chunkSize);
Promise
.resolve(symList)
.each(syms => Trace.querySymbols(syms))
.then(() => Trace.printResults())
.then(() => Trace.printSummary());
}
};
let doCmd = function() {
// 'TRACE' is the default action
action = 'TRACE';
if(cmd.watch) { action = 'WATCH'; }
if(cmd.insider){ action = 'INSIDER'; }
if(cmd.cal) { action = 'CAL'; }
if(cmd.args.length === 1 ){
action = 'QUERY';
}else if (cmd.args.length > 1) {
console.error('Input error, please try again, or run "star -h" for more help.'.error);
return false;
}
actions[action]();
};
// Get the Job Done!
doCmd();
| star.js | #!/usr/bin/env node --harmony
/**
* @author hustcer
* @license MIT
* @copyright TraceInvest.com
* @create 05/18/2015
*/
"use strict";
let _ = require('lodash'),
colors = require('colors'),
Promise = require('bluebird'),
cmd = require('commander');
const pkg = require('./package.json');
let conf = require('./lib/conf.js').conf;
let action = null; // cmd action
/**
* Available colors are:
* bold, italic, underline, inverse, yellow, cyan, white,
* green, red, grey, blue, rainbow, zebra, random, magenta,
*/
const COLOR_THEME = {
error : 'red',
info : 'blue',
data : 'grey',
header : 'blue',
warn : 'yellow',
em : 'magenta'
};
colors.setTheme(COLOR_THEME);
cmd
.version(pkg.version)
.usage('[options]' + ' OR'.em + ' star code1,code2,code3...,codeN')
.description('Star is a command line tool for STock Analysis and Research.')
.option('-a, --all' , 'display all stocks.')
.option('-o, --hold' , 'display all held stocks.')
.option('-M, --margin' , 'display stocks that support Margin.')
.option('-C, --cal' , 'display finance calendar of the future month.')
.option('-I, --ignore' , 'display all ignored stocks.')
.option('-i, --insider [c]' , 'display insider trading records of specified stocks. data source: sse or szse')
.option(' --code [code]' , 'specify the stock code of insider tradings you want to query. data source: traceinvest.com')
.option(' --market <mkt>' , 'specify the market of insider trading query, case insensitive:SZM-深圳主板, SZGEM-深圳创业板, SZSME-深圳中小板,\n' + ' '.repeat(20) +
' SHM-上海主板. multiple market should be separated by "," or ",". ')
.option(' --top-buy' , 'query top buy of insider tradings, should be used with "-i" or "--insider". time span:1m~12m.')
.option(' --top-sell' , 'query top sell of insider tradings, should be used with "-i" or "--insider". time span:1m~12m.')
.option(' --latest-sz' , 'query latest insider tradings of ShenZhen market, should be used with "-i" or "--insider". data source: szse')
.option(' --latest-sh' , 'query latest insider tradings of ShangHai market, should be used with "-i" or "--insider". data source: sse')
.option(' --show-detail' , 'show detail latest insider trading records, should be used with "-i" or "--insider".')
.option('-w, --watch [c1...]', 'watch specified stocks or watch all the stocks in watch list.')
.option('-r, --reverse' , 'sort stocks in ascending order according to designated field.')
.option('-l, --limit <n>' , 'set total display limit of current page.', parseInt)
.option('-p, --page <n>' , 'specify the page index to display.', parseInt)
.option('-d, --data <data>' , 'specify data provider, should be one of "sina" or "tencent".')
.option('-f, --file <file>' , 'specify the symbol file path.')
.option('--from <2014/06/01>', 'specify the beginning date of insider tradings.')
.option('--to <2015/07/09>' , 'specify the ending date of insider tradings.')
.option('--span <3m>' , 'specify the month span of insider tradings ahead of today, should be 1m~24m.')
.option('-L, --lte <pct> ' , 'filter the symbols whose upside potential is lower than or equal to the specified percentage.', parseInt)
.option('-G, --gte <pct> ' , 'filter the symbols whose upside potential is greater than or equal to the specified percentage.', parseInt)
.option('-U, --under <star>' , 'filter the symbols whose star is under or equal to the specified star value.', parseInt)
.option('-A, --above <star>' , 'filter the symbols whose star is above or equal to the specified star value.', parseInt)
.option('--lteb [pct]' , "filter the symbols whose current price is lower than or equal to it's buy/cheap price", parseInt)
.option('--gtes [pct]' , "filter the symbols whose current price is greater than or equal to it's sell/expensive price", parseInt)
.option('-g, --grep <kw> ' , 'specify the keyword to grep in name or comment, multiple keywords should be separated by ",".')
.option('--remove <kw> ' , 'remove the symbols from result with the specified keywords in name or comment, multiple keywords should be separated by ",".')
.option('-e, --exclude <pre>', 'exclude stocks whose code number begin with: 300,600,002 or 000, etc. multiple prefixs can be\n' + ' '.repeat(20) +
' used and should be separated by "," or ",". ')
.option('-c, --contain <pre>', 'display stocks whose code number begin with: 300,600,002 or 000, etc. multiple prefixs can be\n' + ' '.repeat(20) +
' used and should be separated by "," or ",". ')
.option('-s, --sort <sort>' , 'specify sorting field, could be sorted by: code/star/price/targetp/incp/bdiff/sdiff/capacity/\n' + ' '.repeat(20) +
' pe/pb to sort stocks by code, star, price, price to target percent, price increase percent, \n' + ' '.repeat(20) +
' (s.price - s.cheap)/s.price, (s.price - s.expensive)/s.price, capacity, PE and PB separately.\n' + ' '.repeat(20) +
' and sort by capacity/pe/pb only works while using tencent data source.')
.parse(process.argv);
let actions = {
'WATCH' : function(){
let Watch = require('./lib/watch.js').Watch;
Watch.doWatch(cmd.watch);
},
'CAL' : function(){
let Cal = require('./lib/cal.js').Cal;
Cal.showCal();
},
'INSIDER': function(){
let async = require('async');
let Insider = require('./lib/insider.js').Insider;
if(cmd.latestSz){ Insider.querySZLatest(); return false; }
if(cmd.latestSh){ Insider.querySHLatest(); return false; }
if(cmd.topBuy) { Insider.queryTopList('BV'); return false; }
if(cmd.topSell) { Insider.queryTopList('SV'); return false; }
if(cmd.insider === true){ Insider.queryMiscInsider(); return false; }
let query = cmd.insider.replace(/,/g, ',');
let symbols = _.trimRight(query, ',').split(',');
if(symbols.length > conf.chunkSize){
console.error(('You can query at most ' + conf.chunkSize + ' symbols once.').error);
return false;
}
async.eachSeries(symbols, function(c, callback){
Insider.queryInsider(c, callback);
}, function(){
console.log('ALL DONE!');
});
},
'QUERY' : function(){
let Query = require('./lib/query.js').Query;
Query.doQuery(cmd.args[0]);
},
'TRACE' : function(){
let Trace = require('./lib/trace.js').Trace;
let symbols = Trace.getFilteredSymbols();
if(!symbols){ return false; }
let symList = _.chunk(symbols, conf.chunkSize);
Promise
.resolve(symList)
.each(syms => Trace.querySymbols(syms))
.then(() => Trace.printResults())
.then(() => Trace.printSummary());
}
};
let doCmd = function() {
// 'TRACE' is the default action
action = 'TRACE';
if(cmd.watch) { action = 'WATCH'; }
if(cmd.insider){ action = 'INSIDER'; }
if(cmd.cal) { action = 'CAL'; }
if(cmd.args.length === 1 ){
action = 'QUERY';
}else if (cmd.args.length > 1) {
console.error('Input error, please try again, or run "star -h" for more help.'.error);
return false;
}
actions[action]();
};
// Get the Job Done!
doCmd();
| Remove harmony flag
| star.js | Remove harmony flag | <ide><path>tar.js
<del>#!/usr/bin/env node --harmony
<add>#!/usr/bin/env node
<ide>
<ide> /**
<ide> * @author hustcer |
|
JavaScript | mit | 8b93288b441b078426f62a84b28fd922ba5188b3 | 0 | yitzchak/ouroboros,yitzchak/dicy,yitzchak/dicy,yitzchak/dicy,yitzchak/ouroboros | /* @flow */
import path from 'path'
import commandJoin from 'command-join'
import State from './State'
import File from './File'
import StateConsumer from './StateConsumer'
import type { Action, Command, Phase, CommandOptions } from './types'
export default class Rule extends StateConsumer {
static fileTypes: Set<string> = new Set()
static phases: Set<Phase> = new Set(['execute'])
static commands: Set<Command> = new Set(['build'])
static alwaysEvaluate: boolean = false
static ignoreJobName: boolean = false
static description: string = ''
id: string
command: Command
phase: Phase
parameters: Array<File> = []
inputs: Map<string, File> = new Map()
outputs: Map<string, File> = new Map()
actions: Map<Action, Set<File>> = new Map()
success: boolean = true
static async analyzePhase (state: State, command: Command, phase: Phase, jobName: ?string) {
if (await this.appliesToPhase(state, command, phase, jobName)) {
const rule = new this(state, command, phase, jobName)
await rule.initialize()
if (rule.alwaysEvaluate) rule.addAction()
return rule
}
}
static async appliesToPhase (state: State, command: Command, phase: Phase, jobName: ?string): Promise<boolean> {
return this.commands.has(command) &&
this.phases.has(phase) &&
this.fileTypes.size === 0
}
static async analyzeFile (state: State, command: Command, phase: Phase, jobName: ?string, file: File): Promise<?Rule> {
if (await this.appliesToFile(state, command, phase, jobName, file)) {
const rule = new this(state, command, phase, jobName, file)
await rule.initialize()
if (rule.alwaysEvaluate) rule.addAction(file)
return rule
}
}
static async appliesToFile (state: State, command: Command, phase: Phase, jobName: ?string, file: File): Promise<boolean> {
return this.commands.has(command) &&
this.phases.has(phase) &&
(this.fileTypes.has('*') || this.fileTypes.has(file.type)) &&
Array.from(file.rules.values()).every(rule => rule.constructor.name !== this.name || rule.jobName !== jobName)
}
constructor (state: State, command: Command, phase: Phase, jobName: ?string, ...parameters: Array<File>) {
super(state, jobName)
this.parameters = parameters
this.command = command
this.phase = phase
this.id = state.getRuleId(this.constructor.name, command, phase, jobName, ...parameters)
for (const file: File of parameters) {
if (jobName) file.jobNames.add(jobName)
this.inputs.set(file.filePath, file)
// $FlowIgnore
file.addRule(this)
}
}
async initialize () {}
async phaseInitialize (command: ?Command, phase: ?Phase) {
if ((!command || command === this.command) && (!phase || phase === this.phase) && this.constructor.alwaysEvaluate) {
if (this.inputs.size === 0) {
this.addAction()
} else {
for (const input of this.inputs.values()) {
for (const action of await this.getFileActions(input)) {
this.addAction(input, action)
}
}
}
}
}
async addFileActions (file: File, command: ?Command, phase: ?Phase): Promise<void> {
if ((!command || command === this.command) && (!phase || phase === this.phase) && file.hasBeenUpdated) {
const timeStamp: ?Date = this.timeStamp
const ruleNeedsUpdate = !timeStamp || timeStamp < file.timeStamp
for (const action of await this.getFileActions(file)) {
if (action === 'updateDependencies' || ruleNeedsUpdate) {
this.addAction(file, action)
// Clear the failure flag since an input update has happened
this.success = true
}
}
}
}
async getFileActions (file: File): Promise<Array<Action>> {
return ['run']
}
addAction (file: ?File, action: Action = 'run'): void {
const files: ?Set<File> = this.actions.get(action)
if (!files) {
this.actions.set(action, new Set(file ? [file] : []))
} else if (file) {
files.add(file)
}
}
get firstParameter (): File {
return this.parameters[0]
}
get secondParameter (): File {
return this.parameters[1]
}
get needsEvaluation (): boolean {
return this.actions.size !== 0
}
get timeStamp (): ?Date {
return Array.from(this.outputs.values()).reduce((c, t) => !c || t.timeStamp > c ? t.timeStamp : c, null)
}
async preEvaluate (): Promise<void> {}
async evaluate (action: Action): Promise<boolean> {
await this.preEvaluate()
if (!this.actions.has(action)) return true
this.actionTrace(action)
this.success = (action === 'updateDependencies')
? await this.updateDependencies()
: await this.run()
this.actions.delete(action)
await this.updateOutputs()
return this.success
}
async updateDependencies (): Promise<boolean> {
const files = this.actions.get('updateDependencies')
if (files) {
for (const file of files.values()) {
if (file.value) {
if (file.value.inputs) await this.getInputs(file.value.inputs)
if (file.value.outputs) await this.getOutputs(file.value.outputs)
}
}
}
return true
}
async run (): Promise<boolean> {
let success: boolean = true
const options = this.constructProcessOptions()
const { args, severity } = this.constructCommand()
const command = commandJoin(args)
this.emit('command', {
type: 'command',
rule: this.id,
command
})
const { stdout, stderr, error } = await this.executeChildProcess(command, options)
if (error) {
this.log({ severity, text: error.toString(), name: this.constructor.name })
success = false
}
return await this.processOutput(stdout, stderr) && success
}
async processOutput (stdout: string, stderr: string): Promise<boolean> {
return true
}
async getOutput (filePath: string): Promise<?File> {
filePath = this.normalizePath(filePath)
let file: ?File = this.outputs.get(filePath)
if (!file) {
file = await this.getFile(filePath)
if (!file) return
if (!this.outputs.has(filePath)) {
this.outputs.set(filePath, file)
this.emit('outputAdded', { type: 'outputAdded', rule: this.id, file: filePath })
}
}
return file
}
async getOutputs (filePaths: Array<string>): Promise<Array<File>> {
const files = []
for (const filePath of filePaths) {
const file = await this.getOutput(filePath)
if (file) files.push(file)
}
return files
}
async updateOutputs () {
for (const file: File of this.outputs.values()) {
if (await file.update()) {
this.emit('fileChanged', { type: 'fileChanged', file })
}
}
}
async getInput (filePath: string): Promise<?File> {
filePath = this.normalizePath(filePath)
let file: ?File = this.inputs.get(filePath)
if (!file) {
file = await this.getFile(filePath)
if (!file) return
if (!this.inputs.has(filePath)) {
// $FlowIgnore
await file.addRule(this)
this.inputs.set(filePath, file)
this.emit('inputAdded', { type: 'inputAdded', rule: this.id, file: filePath })
}
}
return file
}
async getInputs (filePaths: Array<string>): Promise<Array<File>> {
const files = []
for (const filePath of filePaths) {
const file = await this.getInput(filePath)
if (file) files.push(file)
}
return files
}
async removeFile (file: File): Promise<boolean> {
this.inputs.delete(file.filePath)
this.outputs.delete(file.filePath)
if (this.parameters.includes(file)) {
for (const input of this.inputs.values()) {
// $FlowIgnore
input.removeRule(this)
}
return true
}
// $FlowIgnore
file.removeRule(this)
return false
}
async getResolvedInput (filePath: string, reference?: File | string): Promise<?File> {
const expanded = this.resolvePath(filePath, reference)
return this.getInput(expanded)
}
async getResolvedInputs (filePaths: Array<string>, reference?: File | string): Promise<Array<File>> {
const files = []
for (const filePath of filePaths) {
const file = await this.getResolvedInput(filePath, reference)
if (file) files.push(file)
}
return files
}
async getResolvedOutput (filePath: string, reference?: File | string): Promise<?File> {
const expanded = this.resolvePath(filePath, reference)
return this.getOutput(expanded)
}
async getResolvedOutputs (filePaths: Array<string>, reference?: File | string): Promise<Array<File>> {
const files = []
for (const filePath of filePaths) {
const file = await this.getResolvedOutput(filePath, reference)
if (file) files.push(file)
}
return files
}
async getGlobbedInputs (pattern: string, reference?: File | string): Promise<Array<File>> {
const files = []
for (const filePath of await this.globPath(pattern, reference)) {
const file = await this.getInput(filePath)
if (file) files.push(file)
}
return files
}
async getGlobbedOutputs (pattern: string, reference?: File | string): Promise<Array<File>> {
const files = []
for (const filePath of await this.globPath(pattern, reference)) {
const file = await this.getOutput(filePath)
if (file) files.push(file)
}
return files
}
constructProcessOptions (): Object {
const processOptions = {
cwd: this.rootPath,
env: Object.assign({}, process.env)
}
for (const [name, value] of this.state.getOptions(this.jobName)) {
if (!name.startsWith('$')) continue
const envName = (process.platform === 'win32' && name === '$PATH') ? 'Path' : name.substring(1)
if (Array.isArray(value)) {
const emptyPath = (name === '$PATH') ? process.env[envName] : ''
const paths: Array<string> = value.map(filePath => filePath ? this.resolvePath(filePath) : emptyPath)
if (processOptions.env[envName] && paths.length > 0 && paths[paths.length - 1] === '') {
paths[paths.length - 1] = processOptions.env[envName]
}
processOptions.env[envName] = paths.join(path.delimiter)
} else {
processOptions.env[envName] = this.expandVariables(value)
}
}
return processOptions
}
constructCommand (): CommandOptions {
return { args: [], severity: 'error' }
}
actionTrace (action: Action) {
const files: ?Set<File> = this.actions.get(action)
this.emit('action', {
type: 'action',
action,
rule: this.id,
triggers: files ? Array.from(files).map(file => file.filePath) : []
})
}
}
| packages/core/src/Rule.js | /* @flow */
import path from 'path'
import commandJoin from 'command-join'
import State from './State'
import File from './File'
import StateConsumer from './StateConsumer'
import type { Action, Command, Phase, CommandOptions } from './types'
export default class Rule extends StateConsumer {
static fileTypes: Set<string> = new Set()
static phases: Set<Phase> = new Set(['execute'])
static commands: Set<Command> = new Set(['build'])
static alwaysEvaluate: boolean = false
static ignoreJobName: boolean = false
static description: string = ''
id: string
command: Command
phase: Phase
parameters: Array<File> = []
inputs: Map<string, File> = new Map()
outputs: Map<string, File> = new Map()
actions: Map<Action, Set<File>> = new Map()
success: boolean = true
static async analyzePhase (state: State, command: Command, phase: Phase, jobName: ?string) {
if (await this.appliesToPhase(state, command, phase, jobName)) {
const rule = new this(state, command, phase, jobName)
await rule.initialize()
if (rule.alwaysEvaluate) rule.addAction()
return rule
}
}
static async appliesToPhase (state: State, command: Command, phase: Phase, jobName: ?string): Promise<boolean> {
return this.commands.has(command) &&
this.phases.has(phase) &&
this.fileTypes.size === 0
}
static async analyzeFile (state: State, command: Command, phase: Phase, jobName: ?string, file: File): Promise<?Rule> {
if (await this.appliesToFile(state, command, phase, jobName, file)) {
const rule = new this(state, command, phase, jobName, file)
await rule.initialize()
if (rule.alwaysEvaluate) rule.addAction(file)
return rule
}
}
static async appliesToFile (state: State, command: Command, phase: Phase, jobName: ?string, file: File): Promise<boolean> {
return this.commands.has(command) &&
this.phases.has(phase) &&
(this.fileTypes.has('*') || this.fileTypes.has(file.type)) &&
Array.from(file.rules.values()).every(rule => rule.constructor.name !== this.name || rule.jobName !== jobName)
}
constructor (state: State, command: Command, phase: Phase, jobName: ?string, ...parameters: Array<File>) {
super(state, jobName)
this.parameters = parameters
this.command = command
this.phase = phase
this.id = state.getRuleId(this.constructor.name, command, phase, jobName, ...parameters)
for (const file: File of parameters) {
if (jobName) file.jobNames.add(jobName)
this.inputs.set(file.filePath, file)
// $FlowIgnore
file.addRule(this)
}
}
async initialize () {}
async phaseInitialize (command: ?Command, phase: ?Phase) {
if ((!command || command === this.command) && (!phase || phase === this.phase) && this.constructor.alwaysEvaluate) {
if (this.inputs.size === 0) {
this.addAction()
} else {
for (const input of this.inputs.values()) {
for (const action of await this.getFileActions(input)) {
this.addAction(input, action)
}
}
}
}
}
async addFileActions (file: File, command: ?Command, phase: ?Phase): Promise<void> {
if ((!command || command === this.command) && (!phase || phase === this.phase) && file.hasBeenUpdated) {
const timeStamp: ?Date = this.timeStamp
const ruleNeedsUpdate = !timeStamp || timeStamp < file.timeStamp
for (const action of await this.getFileActions(file)) {
if (action === 'updateDependencies' || ruleNeedsUpdate) {
this.addAction(file, action)
}
}
}
}
async getFileActions (file: File): Promise<Array<Action>> {
return ['run']
}
addAction (file: ?File, action: Action = 'run'): void {
const files: ?Set<File> = this.actions.get(action)
if (!files) {
this.actions.set(action, new Set(file ? [file] : []))
} else if (file) {
files.add(file)
}
}
get firstParameter (): File {
return this.parameters[0]
}
get secondParameter (): File {
return this.parameters[1]
}
get needsEvaluation (): boolean {
return this.actions.size !== 0
}
get timeStamp (): ?Date {
return Array.from(this.outputs.values()).reduce((c, t) => !c || t.timeStamp > c ? t.timeStamp : c, null)
}
async preEvaluate (): Promise<void> {}
async evaluate (action: Action): Promise<boolean> {
await this.preEvaluate()
if (!this.actions.has(action)) return true
this.actionTrace(action)
this.success = (action === 'updateDependencies')
? await this.updateDependencies()
: await this.run()
this.actions.delete(action)
await this.updateOutputs()
return this.success
}
async updateDependencies (): Promise<boolean> {
const files = this.actions.get('updateDependencies')
if (files) {
for (const file of files.values()) {
if (file.value) {
if (file.value.inputs) await this.getInputs(file.value.inputs)
if (file.value.outputs) await this.getOutputs(file.value.outputs)
}
}
}
return true
}
async run (): Promise<boolean> {
let success: boolean = true
const options = this.constructProcessOptions()
const { args, severity } = this.constructCommand()
const command = commandJoin(args)
this.emit('command', {
type: 'command',
rule: this.id,
command
})
const { stdout, stderr, error } = await this.executeChildProcess(command, options)
if (error) {
this.log({ severity, text: error.toString(), name: this.constructor.name })
success = false
}
return await this.processOutput(stdout, stderr) && success
}
async processOutput (stdout: string, stderr: string): Promise<boolean> {
return true
}
async getOutput (filePath: string): Promise<?File> {
filePath = this.normalizePath(filePath)
let file: ?File = this.outputs.get(filePath)
if (!file) {
file = await this.getFile(filePath)
if (!file) return
if (!this.outputs.has(filePath)) {
this.outputs.set(filePath, file)
this.emit('outputAdded', { type: 'outputAdded', rule: this.id, file: filePath })
}
}
return file
}
async getOutputs (filePaths: Array<string>): Promise<Array<File>> {
const files = []
for (const filePath of filePaths) {
const file = await this.getOutput(filePath)
if (file) files.push(file)
}
return files
}
async updateOutputs () {
for (const file: File of this.outputs.values()) {
if (await file.update()) {
this.emit('fileChanged', { type: 'fileChanged', file })
}
}
}
async getInput (filePath: string): Promise<?File> {
filePath = this.normalizePath(filePath)
let file: ?File = this.inputs.get(filePath)
if (!file) {
file = await this.getFile(filePath)
if (!file) return
if (!this.inputs.has(filePath)) {
// $FlowIgnore
await file.addRule(this)
this.inputs.set(filePath, file)
this.emit('inputAdded', { type: 'inputAdded', rule: this.id, file: filePath })
}
}
return file
}
async getInputs (filePaths: Array<string>): Promise<Array<File>> {
const files = []
for (const filePath of filePaths) {
const file = await this.getInput(filePath)
if (file) files.push(file)
}
return files
}
async removeFile (file: File): Promise<boolean> {
this.inputs.delete(file.filePath)
this.outputs.delete(file.filePath)
if (this.parameters.includes(file)) {
for (const input of this.inputs.values()) {
// $FlowIgnore
input.removeRule(this)
}
return true
}
// $FlowIgnore
file.removeRule(this)
return false
}
async getResolvedInput (filePath: string, reference?: File | string): Promise<?File> {
const expanded = this.resolvePath(filePath, reference)
return this.getInput(expanded)
}
async getResolvedInputs (filePaths: Array<string>, reference?: File | string): Promise<Array<File>> {
const files = []
for (const filePath of filePaths) {
const file = await this.getResolvedInput(filePath, reference)
if (file) files.push(file)
}
return files
}
async getResolvedOutput (filePath: string, reference?: File | string): Promise<?File> {
const expanded = this.resolvePath(filePath, reference)
return this.getOutput(expanded)
}
async getResolvedOutputs (filePaths: Array<string>, reference?: File | string): Promise<Array<File>> {
const files = []
for (const filePath of filePaths) {
const file = await this.getResolvedOutput(filePath, reference)
if (file) files.push(file)
}
return files
}
async getGlobbedInputs (pattern: string, reference?: File | string): Promise<Array<File>> {
const files = []
for (const filePath of await this.globPath(pattern, reference)) {
const file = await this.getInput(filePath)
if (file) files.push(file)
}
return files
}
async getGlobbedOutputs (pattern: string, reference?: File | string): Promise<Array<File>> {
const files = []
for (const filePath of await this.globPath(pattern, reference)) {
const file = await this.getOutput(filePath)
if (file) files.push(file)
}
return files
}
constructProcessOptions (): Object {
const processOptions = {
cwd: this.rootPath,
env: Object.assign({}, process.env)
}
for (const [name, value] of this.state.getOptions(this.jobName)) {
if (!name.startsWith('$')) continue
const envName = (process.platform === 'win32' && name === '$PATH') ? 'Path' : name.substring(1)
if (Array.isArray(value)) {
const emptyPath = (name === '$PATH') ? process.env[envName] : ''
const paths: Array<string> = value.map(filePath => filePath ? this.resolvePath(filePath) : emptyPath)
if (processOptions.env[envName] && paths.length > 0 && paths[paths.length - 1] === '') {
paths[paths.length - 1] = processOptions.env[envName]
}
processOptions.env[envName] = paths.join(path.delimiter)
} else {
processOptions.env[envName] = this.expandVariables(value)
}
}
return processOptions
}
constructCommand (): CommandOptions {
return { args: [], severity: 'error' }
}
actionTrace (action: Action) {
const files: ?Set<File> = this.actions.get(action)
this.emit('action', {
type: 'action',
action,
rule: this.id,
triggers: files ? Array.from(files).map(file => file.filePath) : []
})
}
}
| Reset failure flag on input change
| packages/core/src/Rule.js | Reset failure flag on input change | <ide><path>ackages/core/src/Rule.js
<ide> for (const action of await this.getFileActions(file)) {
<ide> if (action === 'updateDependencies' || ruleNeedsUpdate) {
<ide> this.addAction(file, action)
<add> // Clear the failure flag since an input update has happened
<add> this.success = true
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | 3934742bdbd046ce0ca9f860b7207b9785fd7fe7 | 0 | balazs-zsoldos/querydsl,robertandrewbain/querydsl,mosoft521/querydsl,attila-kiss-it/querydsl,gordski/querydsl,lpandzic/querydsl,robertandrewbain/querydsl,johnktims/querydsl,mdiazf/querydsl,tomforster/querydsl,Log10Solutions/querydsl,querydsl/querydsl,vveloso/querydsl,attila-kiss-it/querydsl,mdiazf/querydsl,izeye/querydsl,johnktims/querydsl,kevinleturc/querydsl,dharaburda/querydsl,Log10Solutions/querydsl,izeye/querydsl,querydsl/querydsl,lpandzic/querydsl,pkcool/querydsl,mosoft521/querydsl,vveloso/querydsl,johnktims/querydsl,balazs-zsoldos/querydsl,izeye/querydsl,lpandzic/querydsl,robertandrewbain/querydsl,gordski/querydsl,gordski/querydsl,vveloso/querydsl,dharaburda/querydsl,tomforster/querydsl,Log10Solutions/querydsl,attila-kiss-it/querydsl,lpandzic/querydsl,querydsl/querydsl,pkcool/querydsl,querydsl/querydsl,dharaburda/querydsl,mosoft521/querydsl,tomforster/querydsl,mdiazf/querydsl,pkcool/querydsl,kevinleturc/querydsl,kevinleturc/querydsl,balazs-zsoldos/querydsl | /*
* Copyright 2011, Mysema Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mysema.query.sql.types;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
/**
* @author tiwe
*
*/
public class BooleanType extends AbstractType<Boolean> {
public BooleanType() {
super(Types.BOOLEAN);
}
public BooleanType(int type) {
super(type);
}
@Override
public Boolean getValue(ResultSet rs, int startIndex) throws SQLException {
return rs.getBoolean(startIndex);
}
@Override
public Class<Boolean> getReturnedClass() {
return Boolean.class;
}
@Override
public void setValue(PreparedStatement st, int startIndex, Boolean value) throws SQLException {
st.setBoolean(startIndex, value);
}
}
| querydsl-sql/src/main/java/com/mysema/query/sql/types/BooleanType.java | /*
* Copyright 2011, Mysema Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mysema.query.sql.types;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
/**
* @author tiwe
*
*/
public class BooleanType extends AbstractType<Boolean> {
public BooleanType() {
super(Types.BOOLEAN);
}
public BooleanType(int type) {
super(type);
}
@Override
public Boolean getValue(ResultSet rs, int startIndex) throws SQLException {
Object value = rs.getObject(startIndex);
return value instanceof Boolean ? (Boolean)value : null;
}
@Override
public Class<Boolean> getReturnedClass() {
return Boolean.class;
}
@Override
public void setValue(PreparedStatement st, int startIndex, Boolean value) throws SQLException {
st.setBoolean(startIndex, value);
}
}
| Added support to read boolean values in databases which do not have boolean type.
| querydsl-sql/src/main/java/com/mysema/query/sql/types/BooleanType.java | Added support to read boolean values in databases which do not have boolean type. | <ide><path>uerydsl-sql/src/main/java/com/mysema/query/sql/types/BooleanType.java
<ide>
<ide> @Override
<ide> public Boolean getValue(ResultSet rs, int startIndex) throws SQLException {
<del> Object value = rs.getObject(startIndex);
<del> return value instanceof Boolean ? (Boolean)value : null;
<add> return rs.getBoolean(startIndex);
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | 4e592324a73ec9af4762a8bb26176d2258dbf720 | 0 | mylog00/flink,mtunique/flink,rmetzger/flink,apache/flink,jinglining/flink,mbode/flink,wwjiang007/flink,godfreyhe/flink,lincoln-lil/flink,haohui/flink,godfreyhe/flink,darionyaphet/flink,fanzhidongyzby/flink,hequn8128/flink,fhueske/flink,WangTaoTheTonic/flink,mtunique/flink,greghogan/flink,gyfora/flink,sunjincheng121/flink,lincoln-lil/flink,hwstreaming/flink,greghogan/flink,mylog00/flink,rmetzger/flink,rmetzger/flink,mbode/flink,kl0u/flink,mylog00/flink,rmetzger/flink,kaibozhou/flink,xccui/flink,fanzhidongyzby/flink,bowenli86/flink,zjureel/flink,clarkyzl/flink,zohar-mizrahi/flink,fanyon/flink,bowenli86/flink,tzulitai/flink,hwstreaming/flink,tzulitai/flink,zohar-mizrahi/flink,shaoxuan-wang/flink,mbode/flink,wwjiang007/flink,gustavoanatoly/flink,gustavoanatoly/flink,hequn8128/flink,DieBauer/flink,gyfora/flink,wwjiang007/flink,yew1eb/flink,xccui/flink,StephanEwen/incubator-flink,zohar-mizrahi/flink,gustavoanatoly/flink,zjureel/flink,yew1eb/flink,apache/flink,tony810430/flink,haohui/flink,wwjiang007/flink,yew1eb/flink,xccui/flink,Xpray/flink,gyfora/flink,twalthr/flink,mbode/flink,haohui/flink,tony810430/flink,rmetzger/flink,clarkyzl/flink,ueshin/apache-flink,Xpray/flink,tony810430/flink,yew1eb/flink,WangTaoTheTonic/flink,zentol/flink,tillrohrmann/flink,greghogan/flink,apache/flink,fanyon/flink,bowenli86/flink,kl0u/flink,hongyuhong/flink,jinglining/flink,WangTaoTheTonic/flink,WangTaoTheTonic/flink,mylog00/flink,StephanEwen/incubator-flink,zhangminglei/flink,hongyuhong/flink,tillrohrmann/flink,shaoxuan-wang/flink,fhueske/flink,mylog00/flink,hongyuhong/flink,fanzhidongyzby/flink,Xpray/flink,hequn8128/flink,tony810430/flink,Xpray/flink,twalthr/flink,PangZhi/flink,apache/flink,mtunique/flink,gyfora/flink,zentol/flink,kaibozhou/flink,ueshin/apache-flink,haohui/flink,tillrohrmann/flink,sunjincheng121/flink,shaoxuan-wang/flink,godfreyhe/flink,GJL/flink,zimmermatt/flink,zjureel/flink,darionyaphet/flink,zimmermatt/flink,zohar-mizrahi/flink,tony810430/flink,StephanEwen/incubator-flink,fhueske/flink,yew1eb/flink,shaoxuan-wang/flink,zhangminglei/flink,hequn8128/flink,twalthr/flink,bowenli86/flink,clarkyzl/flink,fanyon/flink,twalthr/flink,gyfora/flink,tzulitai/flink,jinglining/flink,zentol/flink,zhangminglei/flink,twalthr/flink,WangTaoTheTonic/flink,PangZhi/flink,GJL/flink,DieBauer/flink,ueshin/apache-flink,hequn8128/flink,gustavoanatoly/flink,StephanEwen/incubator-flink,zjureel/flink,twalthr/flink,zentol/flink,rmetzger/flink,jinglining/flink,gyfora/flink,zjureel/flink,GJL/flink,sunjincheng121/flink,GJL/flink,zentol/flink,PangZhi/flink,DieBauer/flink,fhueske/flink,shaoxuan-wang/flink,bowenli86/flink,PangZhi/flink,haohui/flink,greghogan/flink,sunjincheng121/flink,zimmermatt/flink,hongyuhong/flink,zimmermatt/flink,zentol/flink,zimmermatt/flink,gyfora/flink,zjureel/flink,tzulitai/flink,hwstreaming/flink,wwjiang007/flink,greghogan/flink,godfreyhe/flink,kl0u/flink,godfreyhe/flink,ueshin/apache-flink,wwjiang007/flink,godfreyhe/flink,lincoln-lil/flink,fanyon/flink,kaibozhou/flink,fanzhidongyzby/flink,clarkyzl/flink,kl0u/flink,twalthr/flink,zhangminglei/flink,darionyaphet/flink,mbode/flink,jinglining/flink,aljoscha/flink,aljoscha/flink,sunjincheng121/flink,apache/flink,aljoscha/flink,kaibozhou/flink,kl0u/flink,xccui/flink,kaibozhou/flink,zentol/flink,apache/flink,hequn8128/flink,wwjiang007/flink,zhangminglei/flink,tillrohrmann/flink,StephanEwen/incubator-flink,jinglining/flink,PangZhi/flink,GJL/flink,aljoscha/flink,mtunique/flink,fhueske/flink,tzulitai/flink,aljoscha/flink,hwstreaming/flink,xccui/flink,clarkyzl/flink,ueshin/apache-flink,fanyon/flink,lincoln-lil/flink,aljoscha/flink,darionyaphet/flink,tillrohrmann/flink,kl0u/flink,zjureel/flink,sunjincheng121/flink,hwstreaming/flink,zohar-mizrahi/flink,xccui/flink,fanzhidongyzby/flink,tony810430/flink,rmetzger/flink,tony810430/flink,tillrohrmann/flink,gustavoanatoly/flink,mtunique/flink,tillrohrmann/flink,lincoln-lil/flink,Xpray/flink,GJL/flink,kaibozhou/flink,xccui/flink,bowenli86/flink,apache/flink,StephanEwen/incubator-flink,hongyuhong/flink,lincoln-lil/flink,shaoxuan-wang/flink,DieBauer/flink,darionyaphet/flink,godfreyhe/flink,greghogan/flink,lincoln-lil/flink,tzulitai/flink,DieBauer/flink,fhueske/flink | /*
* 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.flink.runtime.util;
import org.slf4j.Logger;
import sun.misc.Signal;
/**
* This signal handler / signal logger is based on Apache Hadoop's org.apache.hadoop.util.SignalLogger.
*/
public class SignalHandler {
private static boolean registered = false;
/**
* Our signal handler.
*/
private static class Handler implements sun.misc.SignalHandler {
final private Logger LOG;
final private sun.misc.SignalHandler prevHandler;
Handler(String name, Logger LOG) {
this.LOG = LOG;
prevHandler = Signal.handle(new Signal(name), this);
}
/**
* Handle an incoming signal.
*
* @param signal The incoming signal
*/
@Override
public void handle(Signal signal) {
LOG.info("RECEIVED SIGNAL {}: SIG{}. Shutting down as requested.",
signal.getNumber(),
signal.getName());
prevHandler.handle(signal);
}
}
/**
* Register some signal handlers.
*
* @param LOG The slf4j logger
*/
public static void register(final Logger LOG) {
if (registered) {
throw new IllegalStateException("Can't re-install the signal handlers.");
}
registered = true;
StringBuilder bld = new StringBuilder();
bld.append("registered UNIX signal handlers for [");
final String[] SIGNALS = { "TERM", "HUP", "INT" };
String separator = "";
for (String signalName : SIGNALS) {
try {
new Handler(signalName, LOG);
bld.append(separator);
bld.append(signalName);
separator = ", ";
} catch (Exception e) {
LOG.debug("Error while registering signal handler", e);
}
}
bld.append("]");
LOG.info(bld.toString());
}
}
| flink-runtime/src/main/java/org/apache/flink/runtime/util/SignalHandler.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.flink.runtime.util;
import org.slf4j.Logger;
import sun.misc.Signal;
/**
* This signal handler / signal logger is based on Apache Hadoop's org.apache.hadoop.util.SignalLogger.
*/
public class SignalHandler {
private static boolean registered = false;
/**
* Our signal handler.
*/
private static class Handler implements sun.misc.SignalHandler {
final private Logger LOG;
final private sun.misc.SignalHandler prevHandler;
Handler(String name, Logger LOG) {
this.LOG = LOG;
prevHandler = Signal.handle(new Signal(name), this);
}
/**
* Handle an incoming signal.
*
* @param signal The incoming signal
*/
@Override
public void handle(Signal signal) {
LOG.error("RECEIVED SIGNAL " + signal.getNumber() + ": SIG" + signal.getName());
LOG.error("This JVM will shut down because it was killed from the outside.");
prevHandler.handle(signal);
}
}
/**
* Register some signal handlers.
*
* @param LOG The slf4j logger
*/
public static void register(final Logger LOG) {
if (registered) {
throw new IllegalStateException("Can't re-install the signal handlers.");
}
registered = true;
StringBuilder bld = new StringBuilder();
bld.append("registered UNIX signal handlers for [");
final String[] SIGNALS = { "TERM", "HUP", "INT" };
String separator = "";
for (String signalName : SIGNALS) {
try {
new Handler(signalName, LOG);
bld.append(separator);
bld.append(signalName);
separator = ", ";
} catch (Exception e) {
LOG.debug("Error while registering signal handler", e);
}
}
bld.append("]");
LOG.info(bld.toString());
}
}
| [FLINK-3100] signal handler prints error on normal shutdown of cluster
| flink-runtime/src/main/java/org/apache/flink/runtime/util/SignalHandler.java | [FLINK-3100] signal handler prints error on normal shutdown of cluster | <ide><path>link-runtime/src/main/java/org/apache/flink/runtime/util/SignalHandler.java
<ide> */
<ide> @Override
<ide> public void handle(Signal signal) {
<del> LOG.error("RECEIVED SIGNAL " + signal.getNumber() + ": SIG" + signal.getName());
<del> LOG.error("This JVM will shut down because it was killed from the outside.");
<add> LOG.info("RECEIVED SIGNAL {}: SIG{}. Shutting down as requested.",
<add> signal.getNumber(),
<add> signal.getName());
<ide> prevHandler.handle(signal);
<ide> }
<ide> } |
|
Java | epl-1.0 | 14ee0889a5159a0413fde32b4b368c8c614ef5af | 0 | css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio | package org.csstudio.diag.pvutil.view;
import org.csstudio.diag.pvutil.gui.GUI;
import org.csstudio.diag.pvutil.model.PVUtilModel;
import org.csstudio.platform.logging.CentralLogger;
import org.csstudio.platform.model.IFrontEndControllerName;
import org.csstudio.platform.model.IProcessVariable;
import org.csstudio.platform.ui.internal.dataexchange.ProcessVariableDragSource;
import org.csstudio.platform.ui.internal.dataexchange.ProcessVariableDropTarget;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
/** Eclipse "View" for the PV Utility
* <p>
* Creates the PVUtilDataAPI and displays the GUI within an Eclipse "View" site.
* @author 9pj
*/
public class PVUtilView extends ViewPart
{
final public static String ID = PVUtilView.class.getName();
//private static final String URL = "jdbc:oracle:thin:sns_reports/sns@//snsdev3.sns.ornl.gov:1521/devl";
public static final String URL = "jdbc:oracle:thin:sns_reports/sns@//snsdb1.sns.ornl.gov/prod"; //$NON-NLS-1$
private PVUtilModel model = null;
private GUI gui;
public PVUtilView()
{
try
{
model = new PVUtilModel();
}
catch (Exception ex)
{
CentralLogger.getInstance().getLogger(this).error("Exception", ex);
}
}
@Override
public void createPartControl(Composite parent)
{
if (model == null)
{
new Label(parent, 0).setText("Cannot initialize"); //$NON-NLS-1$
return;
}
gui = new GUI(parent, model);
// Allow Eclipse to listen to PV selection changes
final TableViewer pv_table = gui.getPVTableViewer();
getSite().setSelectionProvider(pv_table);
// Allow dragging PV names & Archive Info out of the name table.
new ProcessVariableDragSource(pv_table.getTable(),
pv_table);
// Enable 'Drop'
final Text pv_filter = gui.getPVFilterText();
new ProcessVariableDropTarget(pv_filter)
{
@Override
public void handleDrop(IProcessVariable name,
DropTargetEvent event)
{
setPVFilter(name.getName());
}
};
// Add empty context menu so that other CSS apps can
// add themselves to it
MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
Menu menu = menuMgr.createContextMenu(pv_table.getControl());
pv_table.getControl().setMenu(menu);
getSite().registerContextMenu(menuMgr, pv_table);
// Add context menu to the name table.
// One reason: Get object contribs for the NameTableItems.
IWorkbenchPartSite site = getSite();
MenuManager manager = new MenuManager("#PopupMenu"); //$NON-NLS-1$
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
Menu contextMenu = manager.createContextMenu(pv_table.getControl());
pv_table.getControl().setMenu(contextMenu);
site.registerContextMenu(manager, pv_table);
}
@Override
public void setFocus()
{
gui.setFocus();
}
public static boolean activateWithPV(IProcessVariable pv_name)
{
try
{
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
IWorkbenchPage page = window.getActivePage();
PVUtilView pv_view = (PVUtilView) page.showView(PVUtilView.ID);
pv_view.setPVFilter(pv_name.getName());
}
catch (Exception ex)
{
CentralLogger.getInstance().getLogger(new PVUtilView()).error("Exception", ex);
}
return false;
}
public static boolean activateWithDevice(IFrontEndControllerName device_name)
{
try
{
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
IWorkbenchPage page = window.getActivePage();
PVUtilView pv_view = (PVUtilView) page.showView(PVUtilView.ID);
pv_view.setDeviceFilter(device_name.getName());
}
catch (Exception ex)
{
CentralLogger.getInstance().getLogger(new PVUtilView()).error("Exception", ex);
}
return false;
}
private void setPVFilter(final String pv_name)
{
gui.getDeviceFilterText().setText("");
model.setFECFilter("");
gui.getPVFilterText().setText(pv_name);
model.setPVFilter(pv_name);
}
private void setDeviceFilter(final String device_name)
{
gui.getDeviceFilterText().setText(device_name);
model.setFECFilter(device_name);
}
}
| products/SNS/plugins/org.csstudio.diag.pvutil/src/org/csstudio/diag/pvutil/view/PVUtilView.java | package org.csstudio.diag.pvutil.view;
import org.csstudio.diag.pvutil.gui.GUI;
import org.csstudio.diag.pvutil.model.PVUtilModel;
import org.csstudio.platform.logging.CentralLogger;
import org.csstudio.platform.model.IFrontEndControllerName;
import org.csstudio.platform.model.IProcessVariable;
import org.csstudio.platform.ui.internal.dataexchange.ProcessVariableDragSource;
import org.csstudio.platform.ui.internal.dataexchange.ProcessVariableDropTarget;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
/** Eclipse "View" for the PV Utility
* <p>
* Creates the PVUtilDataAPI and displays the GUI within an Eclipse "View" site.
* @author 9pj
*/
public class PVUtilView extends ViewPart
{
final public static String ID = PVUtilView.class.getName();
//private static final String URL = "jdbc:oracle:thin:sns_reports/sns@//snsdev3.sns.ornl.gov:1521/devl";
public static final String URL = "jdbc:oracle:thin:sns_reports/sns@//snsdb1.sns.ornl.gov/prod"; //$NON-NLS-1$
private PVUtilModel model = null;
private GUI gui;
public PVUtilView()
{
try
{
model = new PVUtilModel();
}
catch (Exception ex)
{
CentralLogger.getInstance().getLogger(this).error("Exception", ex);
}
}
@Override
public void createPartControl(Composite parent)
{
if (model == null)
{
new Label(parent, 0).setText("Cannot initialize"); //$NON-NLS-1$
return;
}
gui = new GUI(parent, model);
// Allow Eclipse to listen to PV selection changes
final TableViewer pv_table = gui.getPVTableViewer();
getSite().setSelectionProvider(pv_table);
// Allow dragging PV names & Archive Info out of the name table.
new ProcessVariableDragSource(pv_table.getTable(),
pv_table);
// Enable 'Drop'
final Text pv_filter = gui.getPVFilterText();
new ProcessVariableDropTarget(pv_filter)
{
@Override
public void handleDrop(IProcessVariable name,
DropTargetEvent event)
{
setPVFilter(name.getName());
}
};
// Add empty context menu so that other CSS apps can
// add themselves to it
MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
Menu menu = menuMgr.createContextMenu(pv_table.getControl());
pv_table.getControl().setMenu(menu);
getSite().registerContextMenu(menuMgr, pv_table);
// Add context menu to the name table.
// One reason: Get object contribs for the NameTableItems.
IWorkbenchPartSite site = getSite();
MenuManager manager = new MenuManager("#PopupMenu"); //$NON-NLS-1$
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
Menu contextMenu = manager.createContextMenu(pv_table.getControl());
pv_table.getControl().setMenu(contextMenu);
site.registerContextMenu(manager, pv_table);
}
@Override
public void setFocus()
{
gui.setFocus();
}
public static boolean activateWithPV(IProcessVariable pv_name)
{
try
{
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
IWorkbenchPage page = window.getActivePage();
PVUtilView pv_view = (PVUtilView) page.showView(PVUtilView.ID);
pv_view.setPVFilter(pv_name.getName());
}
catch (Exception ex)
{
CentralLogger.getInstance().getLogger(new PVUtilView()).error("Exception", ex);
}
return false;
}
public static boolean activateWithDevice(IFrontEndControllerName device_name)
{
try
{
IWorkbench workbench = PlatformUI.getWorkbench();
IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
IWorkbenchPage page = window.getActivePage();
PVUtilView pv_view = (PVUtilView) page.showView(PVUtilView.ID);
pv_view.setDeviceFilter(device_name.getName());
}
catch (Exception ex)
{
CentralLogger.getInstance().getLogger(new PVUtilView()).error("Exception", ex);
}
return false;
}
private void setPVFilter(final String pv_name)
{
gui.getPVFilterText().setText(pv_name);
model.setPVFilter(pv_name);
}
private void setDeviceFilter(final String device_name)
{
gui.getDeviceFilterText().setText(device_name);
model.setFECFilter(device_name);
}
}
| Small fix
| products/SNS/plugins/org.csstudio.diag.pvutil/src/org/csstudio/diag/pvutil/view/PVUtilView.java | Small fix | <ide><path>roducts/SNS/plugins/org.csstudio.diag.pvutil/src/org/csstudio/diag/pvutil/view/PVUtilView.java
<ide>
<ide> private void setPVFilter(final String pv_name)
<ide> {
<del> gui.getPVFilterText().setText(pv_name);
<add> gui.getDeviceFilterText().setText("");
<add> model.setFECFilter("");
<add> gui.getPVFilterText().setText(pv_name);
<ide> model.setPVFilter(pv_name);
<add>
<ide> }
<ide>
<ide> private void setDeviceFilter(final String device_name) |
|
Java | apache-2.0 | 043a7dfba5525022687f980d799b22d0bb794c27 | 0 | jtablesaw/tablesaw,jtablesaw/tablesaw,jtablesaw/tablesaw | /*
* 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 tech.tablesaw.io;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.google.common.io.Files;
import tech.tablesaw.api.Table;
import tech.tablesaw.io.csv.CsvReadOptions;
import tech.tablesaw.io.csv.CsvReader;
import tech.tablesaw.io.jdbc.SqlResultSetReader;
public class DataFrameReader {
private final ReaderRegistry registry;
public DataFrameReader(ReaderRegistry registry) {
this.registry = registry;
}
/**
* Reads the given URL into a table using default options
* Uses appropriate converter based on mime-type
* Use {@link #usingOptions(ReadOptions) usingOptions} to use non-default options
*/
public Table url(String url) throws IOException {
return url(new URL(url));
}
/**
* Reads the given URL into a table using default options
* Uses appropriate converter based on mime-type
* Use {@link #usingOptions(ReadOptions) usingOptions} to use non-default options
*/
public Table url(URL url) throws IOException {
URLConnection connection = url.openConnection();
String mimeType = connection.getContentType();
DataReader<?> reader = registry.getReaderForMimeType(mimeType);
return reader.read(new Source(connection.getInputStream()));
}
/**
* Reads the given string contents into a table using default options
* Uses converter specified based on given file extension
* Use {@link #usingOptions(ReadOptions) usingOptions} to use non-default options
*/
public Table string(String s, String fileExtension) {
DataReader<?> reader = registry.getReaderForExtension(fileExtension);
try {
return reader.read(Source.fromString(s));
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
/**
* Reads the given file into a table using default options
* Uses converter specified based on given file extension
* Use {@link #usingOptions(ReadOptions) usingOptions} to use non-default options
*/
public Table file(String file) throws IOException {
return file(new File(file));
}
/**
* Reads the given file into a table using default options
* Uses converter specified based on given file extension
* Use {@link #usingOptions(ReadOptions) usingOptions} to use non-default options
*/
public Table file(File file) throws IOException {
String extension = Files.getFileExtension(file.getCanonicalPath());
DataReader<?> reader = registry.getReaderForExtension(extension);
return reader.read(new Source(file));
}
public <T extends ReadOptions> Table usingOptions(T options) throws IOException {
DataReader<T> reader = registry.getReaderForOptions(options);
return reader.read(options);
}
public Table usingOptions(ReadOptions.Builder builder) throws IOException {
return usingOptions(builder.build());
}
public Table db(ResultSet resultSet) throws SQLException {
return SqlResultSetReader.read(resultSet);
}
public Table db(ResultSet resultSet, String tableName) throws SQLException {
Table table = SqlResultSetReader.read(resultSet);
table.setName(tableName);
return table;
}
// Legacy reader methods for backwards-compatibility
public Table csv(String file) throws IOException {
return csv(CsvReadOptions.builder(file));
}
public Table csv(String contents, String tableName) {
try {
return csv(CsvReadOptions.builder(new StringReader(contents)).tableName(tableName));
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public Table csv(File file) throws IOException {
return csv(CsvReadOptions.builder(file));
}
public Table csv(InputStream stream) throws IOException {
return csv(CsvReadOptions.builder(stream));
}
public Table csv(Reader reader) throws IOException {
return csv(CsvReadOptions.builder(reader));
}
public Table csv(CsvReadOptions.Builder options) throws IOException {
return csv(options.build());
}
public Table csv(CsvReadOptions options) throws IOException {
return new CsvReader().read(options);
}
}
| core/src/main/java/tech/tablesaw/io/DataFrameReader.java | /*
* 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 tech.tablesaw.io;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.google.common.io.Files;
import tech.tablesaw.api.Table;
import tech.tablesaw.io.csv.CsvReadOptions;
import tech.tablesaw.io.csv.CsvReader;
import tech.tablesaw.io.jdbc.SqlResultSetReader;
public class DataFrameReader {
private final ReaderRegistry registry;
public DataFrameReader(ReaderRegistry registry) {
this.registry = registry;
}
/**
* Reads the given URL into a table using default options
* Uses appropriate converter based on mime-type
* Use {@link #withOptions(ReadOptions) withOptions} to use non-default options
*/
public Table url(String url) throws IOException {
return url(new URL(url));
}
/**
* Reads the given URL into a table using default options
* Uses appropriate converter based on mime-type
* Use {@link #withOptions(ReadOptions) withOptions} to use non-default options
*/
public Table url(URL url) throws IOException {
URLConnection connection = url.openConnection();
String mimeType = connection.getContentType();
DataReader<?> reader = registry.getReaderForMimeType(mimeType);
return reader.read(new Source(connection.getInputStream()));
}
/**
* Reads the given string contents into a table using default options
* Uses converter specified based on given file extension
* Use {@link #withOptions(ReadOptions) withOptions} to use non-default options
*/
public Table string(String s, String fileExtension) {
DataReader<?> reader = registry.getReaderForExtension(fileExtension);
try {
return reader.read(Source.fromString(s));
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
/**
* Reads the given file into a table using default options
* Uses converter specified based on given file extension
* Use {@link #withOptions(ReadOptions) withOptions} to use non-default options
*/
public Table file(String file) throws IOException {
return file(new File(file));
}
/**
* Reads the given file into a table using default options
* Uses converter specified based on given file extension
* Use {@link #withOptions(ReadOptions) withOptions} to use non-default options
*/
public Table file(File file) throws IOException {
String extension = Files.getFileExtension(file.getCanonicalPath());
DataReader<?> reader = registry.getReaderForExtension(extension);
return reader.read(new Source(file));
}
public <T extends ReadOptions> Table usingOptions(T options) throws IOException {
DataReader<T> reader = registry.getReaderForOptions(options);
return reader.read(options);
}
public Table usingOptions(ReadOptions.Builder builder) throws IOException {
return usingOptions(builder.build());
}
public Table db(ResultSet resultSet) throws SQLException {
return SqlResultSetReader.read(resultSet);
}
public Table db(ResultSet resultSet, String tableName) throws SQLException {
Table table = SqlResultSetReader.read(resultSet);
table.setName(tableName);
return table;
}
// Legacy reader methods for backwards-compatibility
public Table csv(String file) throws IOException {
return csv(CsvReadOptions.builder(file));
}
public Table csv(String contents, String tableName) {
try {
return csv(CsvReadOptions.builder(new StringReader(contents)).tableName(tableName));
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public Table csv(File file) throws IOException {
return csv(CsvReadOptions.builder(file));
}
public Table csv(InputStream stream) throws IOException {
return csv(CsvReadOptions.builder(stream));
}
public Table csv(Reader reader) throws IOException {
return csv(CsvReadOptions.builder(reader));
}
public Table csv(CsvReadOptions.Builder options) throws IOException {
return csv(options.build());
}
public Table csv(CsvReadOptions options) throws IOException {
return new CsvReader().read(options);
}
}
| Fix bad javadoc reference
| core/src/main/java/tech/tablesaw/io/DataFrameReader.java | Fix bad javadoc reference | <ide><path>ore/src/main/java/tech/tablesaw/io/DataFrameReader.java
<ide> /**
<ide> * Reads the given URL into a table using default options
<ide> * Uses appropriate converter based on mime-type
<del> * Use {@link #withOptions(ReadOptions) withOptions} to use non-default options
<add> * Use {@link #usingOptions(ReadOptions) usingOptions} to use non-default options
<ide> */
<ide> public Table url(String url) throws IOException {
<ide> return url(new URL(url));
<ide> /**
<ide> * Reads the given URL into a table using default options
<ide> * Uses appropriate converter based on mime-type
<del> * Use {@link #withOptions(ReadOptions) withOptions} to use non-default options
<add> * Use {@link #usingOptions(ReadOptions) usingOptions} to use non-default options
<ide> */
<ide> public Table url(URL url) throws IOException {
<ide> URLConnection connection = url.openConnection();
<ide> /**
<ide> * Reads the given string contents into a table using default options
<ide> * Uses converter specified based on given file extension
<del> * Use {@link #withOptions(ReadOptions) withOptions} to use non-default options
<add> * Use {@link #usingOptions(ReadOptions) usingOptions} to use non-default options
<ide> */
<ide> public Table string(String s, String fileExtension) {
<ide> DataReader<?> reader = registry.getReaderForExtension(fileExtension);
<ide> /**
<ide> * Reads the given file into a table using default options
<ide> * Uses converter specified based on given file extension
<del> * Use {@link #withOptions(ReadOptions) withOptions} to use non-default options
<add> * Use {@link #usingOptions(ReadOptions) usingOptions} to use non-default options
<ide> */
<ide> public Table file(String file) throws IOException {
<ide> return file(new File(file));
<ide> /**
<ide> * Reads the given file into a table using default options
<ide> * Uses converter specified based on given file extension
<del> * Use {@link #withOptions(ReadOptions) withOptions} to use non-default options
<add> * Use {@link #usingOptions(ReadOptions) usingOptions} to use non-default options
<ide> */
<ide> public Table file(File file) throws IOException {
<ide> String extension = Files.getFileExtension(file.getCanonicalPath()); |
|
Java | apache-2.0 | e1353ed025faceead5f32153b2206b21ef429d49 | 0 | zetbaitsu/Address_Book | package com.zelory.kace.adressbook.ui;
import com.zelory.kace.adressbook.data.model.Person;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
import java.awt.*;
public class PersonDetailDialog extends JDialog {
private JTextField firsNameField;
private JTextField lastNameField;
private JTextField addressField;
private JTextField cityField;
private JTextField stateField;
private JTextField zipField;
private JTextField phoneField;
private Person person;
private SaveListener saveListener;
private boolean create;
public PersonDetailDialog(JFrame parent, Person person) {
this(parent, person, null);
}
public PersonDetailDialog(JFrame parent, Person person, SaveListener saveListener) {
super(parent);
this.person = person;
this.saveListener = saveListener;
create = person == null;
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setSize(320, 240);
setResizable(false);
setModalityType(ModalityType.DOCUMENT_MODAL);
JPanel personDetailPanel = new JPanel();
GridLayout personDetailLayout = new GridLayout(7, 2);
personDetailLayout.setHgap(4);
personDetailLayout.setVgap(4);
personDetailPanel.setLayout(personDetailLayout);
firsNameField = new JTextField();
lastNameField = new JTextField();
addressField = new JTextField();
cityField = new JTextField();
stateField = new JTextField();
zipField = new JTextField();
phoneField = new JTextField();
PlainDocument integerOnly = new PlainDocument();
integerOnly.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int off, String str, AttributeSet attr)
throws BadLocationException
{
fb.insertString(off, str.replaceAll("\\D++", ""), attr); // remove non-digits
}
@Override
public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr)
throws BadLocationException
{
fb.replace(off, len, str.replaceAll("\\D++", ""), attr); // remove non-digits
}
});
phoneField.setDocument(integerOnly);
personDetailPanel.add(new JLabel("First Name"));
personDetailPanel.add(firsNameField);
personDetailPanel.add(new JLabel("Last Name"));
personDetailPanel.add(lastNameField);
personDetailPanel.add(new JLabel("Address"));
personDetailPanel.add(addressField);
personDetailPanel.add(new JLabel("City"));
personDetailPanel.add(cityField);
personDetailPanel.add(new JLabel("State"));
personDetailPanel.add(stateField);
personDetailPanel.add(new JLabel("ZIP Code"));
personDetailPanel.add(zipField);
personDetailPanel.add(new JLabel("Phone Number"));
personDetailPanel.add(phoneField);
JPanel actionPanel = new JPanel();
GridLayout actionLayout = new GridLayout(1, 2);
actionLayout.setHgap(4);
actionLayout.setVgap(4);
actionPanel.setLayout(actionLayout);
actionPanel.add(new Button(create ? "Save" : "Update", e -> savePerson()));
actionPanel.add(new Button(create ? "Cancel" : "Close", e -> close()));
JPanel mainPanel = new JPanel();
mainPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
mainPanel.setLayout(new BorderLayout(4, 4));
mainPanel.add(personDetailPanel, BorderLayout.CENTER);
mainPanel.add(actionPanel, BorderLayout.SOUTH);
getContentPane().add(mainPanel);
if (!create) {
showPersonDetail();
} else {
setTitle("Add Person");
}
}
private void showPersonDetail() {
setTitle(person.getName());
firsNameField.setText(person.getFirstName());
lastNameField.setText(person.getLastName());
addressField.setText(person.getAddress());
cityField.setText(person.getCity());
stateField.setText(person.getState());
zipField.setText(person.getZip());
phoneField.setText(person.getPhoneNumber());
firsNameField.setEditable(false);
lastNameField.setEditable(false);
}
private void savePerson() {
if(validateInput()) {
JOptionPane.showMessageDialog(this, "Plase provide person name!", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (create) {
person = new Person();
}
person.setFirstName(firsNameField.getText());
person.setLastName(lastNameField.getText());
person.setAddress(addressField.getText());
person.setCity(cityField.getText());
person.setState(stateField.getText());
person.setZip(zipField.getText());
person.setPhoneNumber(phoneField.getText());
if (saveListener != null) {
saveListener.onPersonSaved(person);
}
if (create) {
close();
}
}
private boolean validateInput() {
String firstName = firsNameField.getText().trim();
String lastName = lastNameField.getText().trim();
return firstName.equals("") || lastName.equals("");
}
private void close() {
setVisible(false);
dispose();
}
public interface SaveListener {
void onPersonSaved(Person person);
}
}
| src/com/zelory/kace/adressbook/ui/PersonDetailDialog.java | package com.zelory.kace.adressbook.ui;
import com.zelory.kace.adressbook.data.model.Person;
import javax.swing.*;
import java.awt.*;
public class PersonDetailDialog extends JDialog {
private JTextField firsNameField;
private JTextField lastNameField;
private JTextField addressField;
private JTextField cityField;
private JTextField stateField;
private JTextField zipField;
private JTextField phoneField;
private Person person;
private SaveListener saveListener;
private boolean create;
public PersonDetailDialog(JFrame parent, Person person) {
this(parent, person, null);
}
public PersonDetailDialog(JFrame parent, Person person, SaveListener saveListener) {
super(parent);
this.person = person;
this.saveListener = saveListener;
create = person == null;
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setSize(320, 240);
setResizable(false);
setModalityType(ModalityType.DOCUMENT_MODAL);
JPanel personDetailPanel = new JPanel();
GridLayout personDetailLayout = new GridLayout(7, 2);
personDetailLayout.setHgap(4);
personDetailLayout.setVgap(4);
personDetailPanel.setLayout(personDetailLayout);
firsNameField = new JTextField();
lastNameField = new JTextField();
addressField = new JTextField();
cityField = new JTextField();
stateField = new JTextField();
zipField = new JTextField();
phoneField = new JTextField();
personDetailPanel.add(new JLabel("First Name"));
personDetailPanel.add(firsNameField);
personDetailPanel.add(new JLabel("Last Name"));
personDetailPanel.add(lastNameField);
personDetailPanel.add(new JLabel("Address"));
personDetailPanel.add(addressField);
personDetailPanel.add(new JLabel("City"));
personDetailPanel.add(cityField);
personDetailPanel.add(new JLabel("State"));
personDetailPanel.add(stateField);
personDetailPanel.add(new JLabel("ZIP Code"));
personDetailPanel.add(zipField);
personDetailPanel.add(new JLabel("Phone Number"));
personDetailPanel.add(phoneField);
JPanel actionPanel = new JPanel();
GridLayout actionLayout = new GridLayout(1, 2);
actionLayout.setHgap(4);
actionLayout.setVgap(4);
actionPanel.setLayout(actionLayout);
actionPanel.add(new Button(create ? "Save" : "Update", e -> savePerson()));
actionPanel.add(new Button(create ? "Cancel" : "Close", e -> close()));
JPanel mainPanel = new JPanel();
mainPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
mainPanel.setLayout(new BorderLayout(4, 4));
mainPanel.add(personDetailPanel, BorderLayout.CENTER);
mainPanel.add(actionPanel, BorderLayout.SOUTH);
getContentPane().add(mainPanel);
if (!create) {
showPersonDetail();
} else {
setTitle("Add Person");
}
}
private void showPersonDetail() {
setTitle(person.getName());
firsNameField.setText(person.getFirstName());
lastNameField.setText(person.getLastName());
addressField.setText(person.getAddress());
cityField.setText(person.getCity());
stateField.setText(person.getState());
zipField.setText(person.getZip());
phoneField.setText(person.getPhoneNumber());
firsNameField.setEditable(false);
lastNameField.setEditable(false);
}
private void savePerson() {
if(validateInput()) {
JOptionPane.showMessageDialog(this, "Plase provide person name!", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (create) {
person = new Person();
}
person.setFirstName(firsNameField.getText());
person.setLastName(lastNameField.getText());
person.setAddress(addressField.getText());
person.setCity(cityField.getText());
person.setState(stateField.getText());
person.setZip(zipField.getText());
person.setPhoneNumber(phoneField.getText());
if (saveListener != null) {
saveListener.onPersonSaved(person);
}
if (create) {
close();
}
}
private boolean validateInput() {
String firstName = firsNameField.getText().trim();
String lastName = lastNameField.getText().trim();
return firstName.equals("") || lastName.equals("");
}
private void close() {
setVisible(false);
dispose();
}
public interface SaveListener {
void onPersonSaved(Person person);
}
}
| Phone number nomor doank :v
| src/com/zelory/kace/adressbook/ui/PersonDetailDialog.java | Phone number nomor doank :v | <ide><path>rc/com/zelory/kace/adressbook/ui/PersonDetailDialog.java
<ide> import com.zelory.kace.adressbook.data.model.Person;
<ide>
<ide> import javax.swing.*;
<add>import javax.swing.text.AttributeSet;
<add>import javax.swing.text.BadLocationException;
<add>import javax.swing.text.DocumentFilter;
<add>import javax.swing.text.PlainDocument;
<ide> import java.awt.*;
<ide>
<ide> public class PersonDetailDialog extends JDialog {
<ide> stateField = new JTextField();
<ide> zipField = new JTextField();
<ide> phoneField = new JTextField();
<add>
<add> PlainDocument integerOnly = new PlainDocument();
<add> integerOnly.setDocumentFilter(new DocumentFilter() {
<add> @Override
<add> public void insertString(FilterBypass fb, int off, String str, AttributeSet attr)
<add> throws BadLocationException
<add> {
<add> fb.insertString(off, str.replaceAll("\\D++", ""), attr); // remove non-digits
<add> }
<add> @Override
<add> public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr)
<add> throws BadLocationException
<add> {
<add> fb.replace(off, len, str.replaceAll("\\D++", ""), attr); // remove non-digits
<add> }
<add> });
<add>
<add> phoneField.setDocument(integerOnly);
<add>
<ide>
<ide> personDetailPanel.add(new JLabel("First Name"));
<ide> personDetailPanel.add(firsNameField); |
|
Java | mit | 176921aeae7c8121aee53e0de7fb475f58d5aef1 | 0 | 30days-tech/android | package com.thirtydays.common.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by chenxiaojin on 2017/9/13.
* 验证工具类
*/
public class ValidateUtil {
/**
* 检查手机号码是否合法
*
* @param mobileNumber 要检查的手机号码
* @return true合法,false不合法
*/
public static boolean isMobileNumber(String mobileNumber) {
Pattern p = Pattern.compile("^((13)|(14)|(15)|(17)|(18))\\d{9}$");
Matcher m = p.matcher(mobileNumber);
return m.matches();
}
/**
* 描述:是否是邮箱.
*
* @param str 指定的字符串
* @return 是否是邮箱:是为true,否则false
*/
public static boolean isEmail(String str) {
Boolean isEmail = false;
String expr = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
if (str.matches(expr)) {
isEmail = true;
}
return isEmail;
}
/**
* 判断是否符合身份证号码的规范
*
* @param idCard 身份证号码
* @return
*/
public static boolean isIDCard(String idCard) {
if (idCard != null) {
String IDCardRegex = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x|Y|y)$)";
return idCard.matches(IDCardRegex);
}
return false;
}
}
| 公共组件/common/src/main/java/com/thirtydays/common/util/ValidateUtil.java | package com.thirtydays.common.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by chenxiaojin on 2017/9/13.
* 验证工具类
*/
public class ValidateUtil {
/**
* 检查手机号码是否合法
*
* @param mobileNumber 要检查的手机号码
* @return true合法,false不合法
*/
public static boolean isMobileNumber(String mobileNumber) {
Pattern p = Pattern.compile("^((13)|(14)|(15)|(17)|(18))\\d{9}$");
Matcher m = p.matcher(mobileNumber);
return m.matches();
}
/**
* 描述:是否是邮箱.
*
* @param str 指定的字符串
* @return 是否是邮箱:是为true,否则false
*/
public static boolean isEmail(String str) {
Boolean isEmail = false;
String expr = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
if (str.matches(expr)) {
isEmail = true;
}
return isEmail;
}
}
| 修改工具类
| 公共组件/common/src/main/java/com/thirtydays/common/util/ValidateUtil.java | 修改工具类 | <ide><path>共组件/common/src/main/java/com/thirtydays/common/util/ValidateUtil.java
<ide> }
<ide> return isEmail;
<ide> }
<add>
<add> /**
<add> * 判断是否符合身份证号码的规范
<add> *
<add> * @param idCard 身份证号码
<add> * @return
<add> */
<add> public static boolean isIDCard(String idCard) {
<add> if (idCard != null) {
<add> String IDCardRegex = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x|Y|y)$)";
<add> return idCard.matches(IDCardRegex);
<add> }
<add> return false;
<add> }
<ide> } |
|
Java | apache-2.0 | 962cc62131b8551da6a8e118eebd52df84d6c76a | 0 | duke-compsci290-spring2016/sakai,kingmook/sakai,duke-compsci290-spring2016/sakai,kingmook/sakai,colczr/sakai,kwedoff1/sakai,ktakacs/sakai,kwedoff1/sakai,rodriguezdevera/sakai,duke-compsci290-spring2016/sakai,surya-janani/sakai,rodriguezdevera/sakai,bzhouduke123/sakai,frasese/sakai,colczr/sakai,clhedrick/sakai,ktakacs/sakai,OpenCollabZA/sakai,kingmook/sakai,joserabal/sakai,udayg/sakai,udayg/sakai,bzhouduke123/sakai,whumph/sakai,lorenamgUMU/sakai,introp-software/sakai,willkara/sakai,OpenCollabZA/sakai,willkara/sakai,noondaysun/sakai,udayg/sakai,bkirschn/sakai,zqian/sakai,pushyamig/sakai,introp-software/sakai,whumph/sakai,frasese/sakai,bzhouduke123/sakai,Fudan-University/sakai,clhedrick/sakai,frasese/sakai,zqian/sakai,Fudan-University/sakai,ktakacs/sakai,OpenCollabZA/sakai,colczr/sakai,zqian/sakai,OpenCollabZA/sakai,tl-its-umich-edu/sakai,ktakacs/sakai,Fudan-University/sakai,introp-software/sakai,Fudan-University/sakai,rodriguezdevera/sakai,pushyamig/sakai,pushyamig/sakai,clhedrick/sakai,udayg/sakai,wfuedu/sakai,hackbuteer59/sakai,pushyamig/sakai,surya-janani/sakai,wfuedu/sakai,joserabal/sakai,lorenamgUMU/sakai,introp-software/sakai,wfuedu/sakai,pushyamig/sakai,puramshetty/sakai,OpenCollabZA/sakai,hackbuteer59/sakai,hackbuteer59/sakai,puramshetty/sakai,liubo404/sakai,buckett/sakai-gitflow,tl-its-umich-edu/sakai,liubo404/sakai,duke-compsci290-spring2016/sakai,pushyamig/sakai,conder/sakai,lorenamgUMU/sakai,zqian/sakai,puramshetty/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,willkara/sakai,zqian/sakai,whumph/sakai,conder/sakai,colczr/sakai,ktakacs/sakai,colczr/sakai,hackbuteer59/sakai,wfuedu/sakai,conder/sakai,lorenamgUMU/sakai,bkirschn/sakai,kingmook/sakai,udayg/sakai,bkirschn/sakai,Fudan-University/sakai,ouit0408/sakai,kingmook/sakai,OpenCollabZA/sakai,noondaysun/sakai,liubo404/sakai,introp-software/sakai,whumph/sakai,lorenamgUMU/sakai,rodriguezdevera/sakai,kwedoff1/sakai,frasese/sakai,whumph/sakai,noondaysun/sakai,joserabal/sakai,colczr/sakai,tl-its-umich-edu/sakai,Fudan-University/sakai,whumph/sakai,introp-software/sakai,rodriguezdevera/sakai,ouit0408/sakai,willkara/sakai,buckett/sakai-gitflow,tl-its-umich-edu/sakai,tl-its-umich-edu/sakai,wfuedu/sakai,bkirschn/sakai,clhedrick/sakai,puramshetty/sakai,liubo404/sakai,clhedrick/sakai,conder/sakai,ouit0408/sakai,puramshetty/sakai,ouit0408/sakai,kingmook/sakai,lorenamgUMU/sakai,joserabal/sakai,frasese/sakai,surya-janani/sakai,bkirschn/sakai,noondaysun/sakai,bzhouduke123/sakai,colczr/sakai,lorenamgUMU/sakai,wfuedu/sakai,zqian/sakai,surya-janani/sakai,conder/sakai,introp-software/sakai,Fudan-University/sakai,noondaysun/sakai,surya-janani/sakai,conder/sakai,rodriguezdevera/sakai,liubo404/sakai,ktakacs/sakai,kwedoff1/sakai,Fudan-University/sakai,kingmook/sakai,hackbuteer59/sakai,lorenamgUMU/sakai,puramshetty/sakai,duke-compsci290-spring2016/sakai,noondaysun/sakai,udayg/sakai,OpenCollabZA/sakai,joserabal/sakai,surya-janani/sakai,frasese/sakai,frasese/sakai,duke-compsci290-spring2016/sakai,kingmook/sakai,bkirschn/sakai,clhedrick/sakai,willkara/sakai,bzhouduke123/sakai,OpenCollabZA/sakai,clhedrick/sakai,kwedoff1/sakai,tl-its-umich-edu/sakai,ouit0408/sakai,kwedoff1/sakai,tl-its-umich-edu/sakai,puramshetty/sakai,joserabal/sakai,joserabal/sakai,hackbuteer59/sakai,colczr/sakai,bkirschn/sakai,ktakacs/sakai,udayg/sakai,zqian/sakai,liubo404/sakai,duke-compsci290-spring2016/sakai,puramshetty/sakai,noondaysun/sakai,pushyamig/sakai,liubo404/sakai,wfuedu/sakai,whumph/sakai,buckett/sakai-gitflow,surya-janani/sakai,ouit0408/sakai,kwedoff1/sakai,buckett/sakai-gitflow,udayg/sakai,willkara/sakai,clhedrick/sakai,hackbuteer59/sakai,conder/sakai,joserabal/sakai,liubo404/sakai,bkirschn/sakai,frasese/sakai,ktakacs/sakai,pushyamig/sakai,buckett/sakai-gitflow,rodriguezdevera/sakai,zqian/sakai,buckett/sakai-gitflow,whumph/sakai,kwedoff1/sakai,bzhouduke123/sakai,buckett/sakai-gitflow,bzhouduke123/sakai,rodriguezdevera/sakai,buckett/sakai-gitflow,duke-compsci290-spring2016/sakai,bzhouduke123/sakai,wfuedu/sakai,noondaysun/sakai,willkara/sakai,ouit0408/sakai,introp-software/sakai,conder/sakai,willkara/sakai,surya-janani/sakai,hackbuteer59/sakai | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.sakaiproject.site.tool;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Random;
import java.util.Set;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.tools.generic.SortTool;
import org.sakaiproject.alias.api.Alias;
import org.sakaiproject.alias.cover.AliasService;
import org.sakaiproject.archive.api.ImportMetadata;
import org.sakaiproject.archive.cover.ArchiveService;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.AuthzPermissionException;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.Member;
import org.sakaiproject.authz.api.PermissionsHelper;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceActionII;
import org.sakaiproject.cheftool.PortletConfig;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.api.Menu;
import org.sakaiproject.cheftool.api.MenuItem;
import org.sakaiproject.cheftool.menu.MenuEntry;
import org.sakaiproject.cheftool.menu.MenuImpl;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.cover.ContentHostingService;
import org.sakaiproject.coursemanagement.api.AcademicSession;
import org.sakaiproject.coursemanagement.api.CourseOffering;
import org.sakaiproject.coursemanagement.api.CourseSet;
import org.sakaiproject.coursemanagement.api.Enrollment;
import org.sakaiproject.coursemanagement.api.EnrollmentSet;
import org.sakaiproject.coursemanagement.api.Membership;
import org.sakaiproject.coursemanagement.api.Section;
import org.sakaiproject.coursemanagement.api.exception.IdNotFoundException;
import org.sakaiproject.email.cover.EmailService;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.EntityProducer;
import org.sakaiproject.entity.api.EntityPropertyNotDefinedException;
import org.sakaiproject.entity.api.EntityPropertyTypeException;
import org.sakaiproject.entity.api.EntityTransferrer;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.ImportException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.id.cover.IdManager;
import org.sakaiproject.importer.api.ImportDataSource;
import org.sakaiproject.importer.api.ImportService;
import org.sakaiproject.importer.api.SakaiArchive;
import org.sakaiproject.javax.PagingPosition;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SitePage;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.site.api.SiteService.SortType;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.sitemanage.api.SectionField;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserAlreadyDefinedException;
import org.sakaiproject.user.api.UserEdit;
import org.sakaiproject.user.api.UserIdInvalidException;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.api.UserPermissionException;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.ArrayUtil;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.SortedIterator;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
/**
* <p>
* SiteAction controls the interface for worksite setup.
* </p>
*/
public class SiteAction extends PagedResourceActionII {
/** Our logger. */
private static Log M_log = LogFactory.getLog(SiteAction.class);
private ImportService importService = org.sakaiproject.importer.cover.ImportService
.getInstance();
/** portlet configuration parameter values* */
/** Resource bundle using current language locale */
private static ResourceLoader rb = new ResourceLoader("sitesetupgeneric");
private org.sakaiproject.coursemanagement.api.CourseManagementService cms = (org.sakaiproject.coursemanagement.api.CourseManagementService) ComponentManager
.get(org.sakaiproject.coursemanagement.api.CourseManagementService.class);
private org.sakaiproject.authz.api.GroupProvider groupProvider = (org.sakaiproject.authz.api.GroupProvider) ComponentManager
.get(org.sakaiproject.authz.api.GroupProvider.class);
private org.sakaiproject.authz.api.AuthzGroupService authzGroupService = (org.sakaiproject.authz.api.AuthzGroupService) ComponentManager
.get(org.sakaiproject.authz.api.AuthzGroupService.class);
private org.sakaiproject.sitemanage.api.SectionFieldProvider sectionFieldProvider = (org.sakaiproject.sitemanage.api.SectionFieldProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.SectionFieldProvider.class);
private org.sakaiproject.sitemanage.api.AffiliatedSectionProvider affiliatedSectionProvider = (org.sakaiproject.sitemanage.api.AffiliatedSectionProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.AffiliatedSectionProvider.class);
private org.sakaiproject.sitemanage.api.UserNotificationProvider userNotificationProvider = (org.sakaiproject.sitemanage.api.UserNotificationProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.UserNotificationProvider.class);
private static final String SITE_MODE_SITESETUP = "sitesetup";
private static final String SITE_MODE_SITEINFO = "siteinfo";
private static final String STATE_SITE_MODE = "site_mode";
protected final static String[] TEMPLATE = {
"-list",// 0
"-type",
"-newSiteInformation",
"-newSiteFeatures",
"-addRemoveFeature",
"-addParticipant",
"",
"",
"-siteDeleteConfirm",
"",
"-newSiteConfirm",// 10
"",
"-siteInfo-list",// 12
"-siteInfo-editInfo",
"-siteInfo-editInfoConfirm",
"-addRemoveFeatureConfirm",// 15
"",
"",
"-siteInfo-editAccess",
"-addParticipant-sameRole",
"-addParticipant-differentRole",// 20
"-addParticipant-notification",
"-addParticipant-confirm",
"",
"",
"",// 25
"-modifyENW",
"-importSites",
"-siteInfo-import",
"-siteInfo-duplicate",
"",// 30
"",// 31
"",// 32
"",// 33
"",// 34
"",// 35
"-newSiteCourse",// 36
"-newSiteCourseManual",// 37
"",// 38
"",// 39
"",// 40
"",// 41
"-gradtoolsConfirm",// 42
"-siteInfo-editClass",// 43
"-siteInfo-addCourseConfirm",// 44
"-siteInfo-importMtrlMaster", // 45 -- htripath for import
// material from a file
"-siteInfo-importMtrlCopy", // 46
"-siteInfo-importMtrlCopyConfirm",
"-siteInfo-importMtrlCopyConfirmMsg", // 48
"-siteInfo-group", // 49
"-siteInfo-groupedit", // 50
"-siteInfo-groupDeleteConfirm", // 51,
"",
"-findCourse" // 53
};
/** Name of state attribute for Site instance id */
private static final String STATE_SITE_INSTANCE_ID = "site.instance.id";
/** Name of state attribute for Site Information */
private static final String STATE_SITE_INFO = "site.info";
/** Name of state attribute for CHEF site type */
private static final String STATE_SITE_TYPE = "site-type";
/** Name of state attribute for poissible site types */
private static final String STATE_SITE_TYPES = "site_types";
private static final String STATE_DEFAULT_SITE_TYPE = "default_site_type";
private static final String STATE_PUBLIC_CHANGEABLE_SITE_TYPES = "changeable_site_types";
private static final String STATE_PUBLIC_SITE_TYPES = "public_site_types";
private static final String STATE_PRIVATE_SITE_TYPES = "private_site_types";
private static final String STATE_DISABLE_JOINABLE_SITE_TYPE = "disable_joinable_site_types";
// Names of state attributes corresponding to properties of a site
private final static String PROP_SITE_CONTACT_EMAIL = "contact-email";
private final static String PROP_SITE_CONTACT_NAME = "contact-name";
private final static String PROP_SITE_TERM = "term";
private final static String PROP_SITE_TERM_EID = "term_eid";
/**
* Name of the state attribute holding the site list column list is sorted
* by
*/
private static final String SORTED_BY = "site.sorted.by";
/** the list of criteria for sorting */
private static final String SORTED_BY_TITLE = "title";
private static final String SORTED_BY_DESCRIPTION = "description";
private static final String SORTED_BY_TYPE = "type";
private static final String SORTED_BY_STATUS = "status";
private static final String SORTED_BY_CREATION_DATE = "creationdate";
private static final String SORTED_BY_JOINABLE = "joinable";
private static final String SORTED_BY_PARTICIPANT_NAME = "participant_name";
private static final String SORTED_BY_PARTICIPANT_UNIQNAME = "participant_uniqname";
private static final String SORTED_BY_PARTICIPANT_ROLE = "participant_role";
private static final String SORTED_BY_PARTICIPANT_ID = "participant_id";
private static final String SORTED_BY_PARTICIPANT_COURSE = "participant_course";
private static final String SORTED_BY_PARTICIPANT_CREDITS = "participant_credits";
private static final String SORTED_BY_PARTICIPANT_STATUS = "participant_status";
private static final String SORTED_BY_MEMBER_NAME = "member_name";
/** Name of the state attribute holding the site list column to sort by */
private static final String SORTED_ASC = "site.sort.asc";
/** State attribute for list of sites to be deleted. */
private static final String STATE_SITE_REMOVALS = "site.removals";
/** Name of the state attribute holding the site list View selected */
private static final String STATE_VIEW_SELECTED = "site.view.selected";
/** Names of lists related to tools */
private static final String STATE_TOOL_REGISTRATION_LIST = "toolRegistrationList";
private static final String STATE_TOOL_REGISTRATION_SELECTED_LIST = "toolRegistrationSelectedList";
private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST = "toolRegistrationOldSelectedList";
private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME = "toolRegistrationOldSelectedHome";
private static final String STATE_TOOL_EMAIL_ADDRESS = "toolEmailAddress";
private static final String STATE_TOOL_HOME_SELECTED = "toolHomeSelected";
private static final String STATE_PROJECT_TOOL_LIST = "projectToolList";
private final static String STATE_MULTIPLE_TOOL_ID_SET = "multipleToolIdSet";
private final static String STATE_MULTIPLE_TOOL_ID_TITLE_MAP = "multipleToolIdTitleMap";
private final static String SITE_DEFAULT_LIST = ServerConfigurationService
.getString("site.types");
private final static String STATE_SITE_QUEST_UNIQNAME = "site_quest_uniqname";
private static final String STATE_SITE_ADD_COURSE = "canAddCourse";
// %%% get rid of the IdAndText tool lists and just use ToolConfiguration or
// ToolRegistration lists
// %%% same for CourseItems
// Names for other state attributes that are lists
private final static String STATE_WORKSITE_SETUP_PAGE_LIST = "wSetupPageList"; // the
// list
// of
// site
// pages
// consistent
// with
// Worksite
// Setup
// page
// patterns
/**
* The name of the state form field containing additional information for a
* course request
*/
private static final String FORM_ADDITIONAL = "form.additional";
/** %%% in transition from putting all form variables in state */
private final static String FORM_TITLE = "form_title";
private final static String FORM_DESCRIPTION = "form_description";
private final static String FORM_HONORIFIC = "form_honorific";
private final static String FORM_INSTITUTION = "form_institution";
private final static String FORM_SUBJECT = "form_subject";
private final static String FORM_PHONE = "form_phone";
private final static String FORM_EMAIL = "form_email";
private final static String FORM_REUSE = "form_reuse";
private final static String FORM_RELATED_CLASS = "form_related_class";
private final static String FORM_RELATED_PROJECT = "form_related_project";
private final static String FORM_NAME = "form_name";
private final static String FORM_SHORT_DESCRIPTION = "form_short_description";
private final static String FORM_ICON_URL = "iconUrl";
/** site info edit form variables */
private final static String FORM_SITEINFO_TITLE = "siteinfo_title";
private final static String FORM_SITEINFO_TERM = "siteinfo_term";
private final static String FORM_SITEINFO_DESCRIPTION = "siteinfo_description";
private final static String FORM_SITEINFO_SHORT_DESCRIPTION = "siteinfo_short_description";
private final static String FORM_SITEINFO_SKIN = "siteinfo_skin";
private final static String FORM_SITEINFO_INCLUDE = "siteinfo_include";
private final static String FORM_SITEINFO_ICON_URL = "siteinfo_icon_url";
private final static String FORM_SITEINFO_CONTACT_NAME = "siteinfo_contact_name";
private final static String FORM_SITEINFO_CONTACT_EMAIL = "siteinfo_contact_email";
private final static String FORM_WILL_NOTIFY = "form_will_notify";
/** Context action */
private static final String CONTEXT_ACTION = "SiteAction";
/** The name of the Attribute for display template index */
private static final String STATE_TEMPLATE_INDEX = "site.templateIndex";
/** State attribute for state initialization. */
private static final String STATE_INITIALIZED = "site.initialized";
/** The action for menu */
private static final String STATE_ACTION = "site.action";
/** The user copyright string */
private static final String STATE_MY_COPYRIGHT = "resources.mycopyright";
/** The copyright character */
private static final String COPYRIGHT_SYMBOL = "copyright (c)";
/** The null/empty string */
private static final String NULL_STRING = "";
/** The state attribute alerting user of a sent course request */
private static final String REQUEST_SENT = "site.request.sent";
/** The state attributes in the make public vm */
private static final String STATE_JOINABLE = "state_joinable";
private static final String STATE_JOINERROLE = "state_joinerRole";
/** the list of selected user */
private static final String STATE_SELECTED_USER_LIST = "state_selected_user_list";
private static final String STATE_SELECTED_PARTICIPANT_ROLES = "state_selected_participant_roles";
private static final String STATE_SELECTED_PARTICIPANTS = "state_selected_participants";
private static final String STATE_PARTICIPANT_LIST = "state_participant_list";
private static final String STATE_ADD_PARTICIPANTS = "state_add_participants";
/** for changing participant roles */
private static final String STATE_CHANGEROLE_SAMEROLE = "state_changerole_samerole";
private static final String STATE_CHANGEROLE_SAMEROLE_ROLE = "state_changerole_samerole_role";
/** for remove user */
private static final String STATE_REMOVEABLE_USER_LIST = "state_removeable_user_list";
private static final String STATE_IMPORT = "state_import";
private static final String STATE_IMPORT_SITES = "state_import_sites";
private static final String STATE_IMPORT_SITE_TOOL = "state_import_site_tool";
/** for navigating between sites in site list */
private static final String STATE_SITES = "state_sites";
private static final String STATE_PREV_SITE = "state_prev_site";
private static final String STATE_NEXT_SITE = "state_next_site";
/** for course information */
private final static String STATE_TERM_COURSE_LIST = "state_term_course_list";
private final static String STATE_TERM_COURSE_HASH = "state_term_course_hash";
private final static String STATE_TERM_SELECTED = "state_term_selected";
private final static String STATE_INSTRUCTOR_SELECTED = "state_instructor_selected";
private final static String STATE_FUTURE_TERM_SELECTED = "state_future_term_selected";
private final static String STATE_ADD_CLASS_PROVIDER = "state_add_class_provider";
private final static String STATE_ADD_CLASS_PROVIDER_CHOSEN = "state_add_class_provider_chosen";
private final static String STATE_ADD_CLASS_MANUAL = "state_add_class_manual";
private final static String STATE_AUTO_ADD = "state_auto_add";
private final static String STATE_MANUAL_ADD_COURSE_NUMBER = "state_manual_add_course_number";
private final static String STATE_MANUAL_ADD_COURSE_FIELDS = "state_manual_add_course_fields";
public final static String PROP_SITE_REQUEST_COURSE = "site-request-course-sections";
public final static String SITE_PROVIDER_COURSE_LIST = "site_provider_course_list";
public final static String SITE_MANUAL_COURSE_LIST = "site_manual_course_list";
private final static String STATE_SUBJECT_AFFILIATES = "site.subject.affiliates";
private final static String STATE_ICONS = "icons";
// site template used to create a UM Grad Tools student site
public static final String SITE_GTS_TEMPLATE = "!gtstudent";
// the type used to identify a UM Grad Tools student site
public static final String SITE_TYPE_GRADTOOLS_STUDENT = "GradToolsStudent";
// list of UM Grad Tools site types for editing
public static final String GRADTOOLS_SITE_TYPES = "gradtools_site_types";
public static final String SITE_DUPLICATED = "site_duplicated";
public static final String SITE_DUPLICATED_NAME = "site_duplicated_named";
// used for site creation wizard title
public static final String SITE_CREATE_TOTAL_STEPS = "site_create_total_steps";
public static final String SITE_CREATE_CURRENT_STEP = "site_create_current_step";
// types of site whose title can be editable
public static final String TITLE_EDITABLE_SITE_TYPE = "title_editable_site_type";
// types of site where site view roster permission is editable
public static final String EDIT_VIEW_ROSTER_SITE_TYPE = "edit_view_roster_site_type";
// htripath : for import material from file - classic import
private static final String ALL_ZIP_IMPORT_SITES = "allzipImports";
private static final String FINAL_ZIP_IMPORT_SITES = "finalzipImports";
private static final String DIRECT_ZIP_IMPORT_SITES = "directzipImports";
private static final String CLASSIC_ZIP_FILE_NAME = "classicZipFileName";
private static final String SESSION_CONTEXT_ID = "sessionContextId";
// page size for worksite setup tool
private static final String STATE_PAGESIZE_SITESETUP = "state_pagesize_sitesetup";
// page size for site info tool
private static final String STATE_PAGESIZE_SITEINFO = "state_pagesize_siteinfo";
// group info
private static final String STATE_GROUP_INSTANCE_ID = "state_group_instance_id";
private static final String STATE_GROUP_TITLE = "state_group_title";
private static final String STATE_GROUP_DESCRIPTION = "state_group_description";
private static final String STATE_GROUP_MEMBERS = "state_group_members";
private static final String STATE_GROUP_REMOVE = "state_group_remove";
private static final String GROUP_PROP_WSETUP_CREATED = "group_prop_wsetup_created";
private static final String IMPORT_DATA_SOURCE = "import_data_source";
private static final String EMAIL_CHAR = "@";
// Special tool id for Home page
private static final String HOME_TOOL_ID = "home";
private static final String STATE_CM_LEVELS = "site.cm.levels";
private static final String STATE_CM_LEVEL_OPTS = "site.cm.level_opts";
private static final String STATE_CM_LEVEL_SELECTIONS = "site.cm.level.selections";
private static final String STATE_CM_SELECTED_SECTION = "site.cm.selectedSection";
private static final String STATE_CM_REQUESTED_SECTIONS = "site.cm.requested";
private static final String STATE_CM_SELECTED_SECTIONS = "site.cm.selectedSections";
private static final String STATE_PROVIDER_SECTION_LIST = "site_provider_section_list";
private static final String STATE_CM_CURRENT_USERID = "site_cm_current_userId";
private static final String STATE_CM_AUTHORIZER_LIST = "site_cm_authorizer_list";
private static final String STATE_CM_AUTHORIZER_SECTIONS = "site_cm_authorizer_sections";
private String cmSubjectCategory;
private boolean warnedNoSubjectCategory = false;
// the string marks the protocol part in url
private static final String PROTOCOL_STRING = "://";
private static final String TOOL_ID_SUMMARY_CALENDAR = "sakai.summary.calendar";
// the string for course site type
private static final String STATE_COURSE_SITE_TYPE = "state_course_site_type";
/**
* Populate the state object, if needed.
*/
protected void initState(SessionState state, VelocityPortlet portlet,
JetspeedRunData rundata) {
super.initState(state, portlet, rundata);
// store current userId in state
User user = UserDirectoryService.getCurrentUser();
String userId = user.getEid();
state.setAttribute(STATE_CM_CURRENT_USERID, userId);
PortletConfig config = portlet.getPortletConfig();
// types of sites that can either be public or private
String changeableTypes = StringUtil.trimToNull(config
.getInitParameter("publicChangeableSiteTypes"));
if (state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES) == null) {
if (changeableTypes != null) {
state
.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES,
new ArrayList(Arrays.asList(changeableTypes
.split(","))));
} else {
state.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES,
new Vector());
}
}
// type of sites that are always public
String publicTypes = StringUtil.trimToNull(config
.getInitParameter("publicSiteTypes"));
if (state.getAttribute(STATE_PUBLIC_SITE_TYPES) == null) {
if (publicTypes != null) {
state.setAttribute(STATE_PUBLIC_SITE_TYPES, new ArrayList(
Arrays.asList(publicTypes.split(","))));
} else {
state.setAttribute(STATE_PUBLIC_SITE_TYPES, new Vector());
}
}
// types of sites that are always private
String privateTypes = StringUtil.trimToNull(config
.getInitParameter("privateSiteTypes"));
if (state.getAttribute(STATE_PRIVATE_SITE_TYPES) == null) {
if (privateTypes != null) {
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new ArrayList(
Arrays.asList(privateTypes.split(","))));
} else {
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector());
}
}
// default site type
String defaultType = StringUtil.trimToNull(config
.getInitParameter("defaultSiteType"));
if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) == null) {
if (defaultType != null) {
state.setAttribute(STATE_DEFAULT_SITE_TYPE, defaultType);
} else {
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector());
}
}
// certain type(s) of site cannot get its "joinable" option set
if (state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE) == null) {
if (ServerConfigurationService
.getStrings("wsetup.disable.joinable") != null) {
state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE,
new ArrayList(Arrays.asList(ServerConfigurationService
.getStrings("wsetup.disable.joinable"))));
} else {
state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE,
new Vector());
}
}
// course site type
if (state.getAttribute(STATE_COURSE_SITE_TYPE) == null)
{
state.setAttribute(STATE_COURSE_SITE_TYPE, ServerConfigurationService.getString("courseSiteType", "course"));
}
if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) {
state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0));
}
// skins if any
if (state.getAttribute(STATE_ICONS) == null) {
setupIcons(state);
}
if (state.getAttribute(GRADTOOLS_SITE_TYPES) == null) {
List gradToolsSiteTypes = new Vector();
if (ServerConfigurationService.getStrings("gradToolsSiteType") != null) {
gradToolsSiteTypes = new ArrayList(Arrays
.asList(ServerConfigurationService
.getStrings("gradToolsSiteType")));
}
state.setAttribute(GRADTOOLS_SITE_TYPES, gradToolsSiteTypes);
}
if (ServerConfigurationService.getStrings("titleEditableSiteType") != null) {
state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new ArrayList(Arrays
.asList(ServerConfigurationService
.getStrings("titleEditableSiteType"))));
} else {
state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new Vector());
}
if (state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE) == null) {
List siteTypes = new Vector();
if (ServerConfigurationService.getStrings("editViewRosterSiteType") != null) {
siteTypes = new ArrayList(Arrays
.asList(ServerConfigurationService
.getStrings("editViewRosterSiteType")));
}
state.setAttribute(EDIT_VIEW_ROSTER_SITE_TYPE, siteTypes);
}
// get site tool mode from tool registry
String site_mode = portlet.getPortletConfig().getInitParameter(
STATE_SITE_MODE);
state.setAttribute(STATE_SITE_MODE, site_mode);
} // initState
/**
* cleanState removes the current site instance and it's properties from
* state
*/
private void cleanState(SessionState state) {
state.removeAttribute(STATE_SITE_INSTANCE_ID);
state.removeAttribute(STATE_SITE_INFO);
state.removeAttribute(STATE_SITE_TYPE);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
state.removeAttribute(STATE_TOOL_HOME_SELECTED);
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_JOINABLE);
state.removeAttribute(STATE_JOINERROLE);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
state.removeAttribute(STATE_IMPORT);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
// remove those state attributes related to course site creation
state.removeAttribute(STATE_TERM_COURSE_LIST);
state.removeAttribute(STATE_TERM_COURSE_HASH);
state.removeAttribute(STATE_TERM_SELECTED);
state.removeAttribute(STATE_INSTRUCTOR_SELECTED);
state.removeAttribute(STATE_FUTURE_TERM_SELECTED);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_ADD_CLASS_MANUAL);
state.removeAttribute(STATE_AUTO_ADD);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(SITE_CREATE_TOTAL_STEPS);
state.removeAttribute(SITE_CREATE_CURRENT_STEP);
state.removeAttribute(STATE_PROVIDER_SECTION_LIST);
state.removeAttribute(STATE_CM_LEVELS);
state.removeAttribute(STATE_CM_LEVEL_SELECTIONS);
state.removeAttribute(STATE_CM_SELECTED_SECTION);
state.removeAttribute(STATE_CM_REQUESTED_SECTIONS);
state.removeAttribute(STATE_CM_CURRENT_USERID);
state.removeAttribute(STATE_CM_AUTHORIZER_LIST);
state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS);
state.removeAttribute(FORM_ADDITIONAL); // don't we need to clena this
// too? -daisyf
} // cleanState
/**
* Fire up the permissions editor
*/
public void doPermissions(RunData data, Context context) {
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String contextString = ToolManager.getCurrentPlacement().getContext();
String siteRef = SiteService.siteReference(contextString);
// if it is in Worksite setup tool, pass the selected site's reference
if (state.getAttribute(STATE_SITE_MODE) != null
&& ((String) state.getAttribute(STATE_SITE_MODE))
.equals(SITE_MODE_SITESETUP)) {
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) {
Site s = getStateSite(state);
if (s != null) {
siteRef = s.getReference();
}
}
}
// setup for editing the permissions of the site for this tool, using
// the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb
.getString("setperfor")
+ " " + SiteService.getSiteDisplay(contextString));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "site.");
} // doPermissions
/**
* Build the context for normal display
*/
public String buildMainPanelContext(VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
context.put("tlang", rb);
// TODO: what is all this doing? if we are in helper mode, we are
// already setup and don't get called here now -ggolden
/*
* String helperMode = (String)
* state.getAttribute(PermissionsAction.STATE_MODE); if (helperMode !=
* null) { Site site = getStateSite(state); if (site != null) { if
* (site.getType() != null && ((List)
* state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE)).contains(site.getType())) {
* context.put("editViewRoster", Boolean.TRUE); } else {
* context.put("editViewRoster", Boolean.FALSE); } } else {
* context.put("editViewRoster", Boolean.FALSE); } // for new, don't
* show site.del in Permission page context.put("hiddenLock",
* "site.del");
*
* String template = PermissionsAction.buildHelperContext(portlet,
* context, data, state); if (template == null) { addAlert(state,
* rb.getString("theisa")); } else { return template; } }
*/
String template = null;
context.put("action", CONTEXT_ACTION);
// updatePortlet(state, portlet, data);
if (state.getAttribute(STATE_INITIALIZED) == null) {
init(portlet, data, state);
}
int index = Integer.valueOf(
(String) state.getAttribute(STATE_TEMPLATE_INDEX)).intValue();
template = buildContextForTemplate(index, portlet, context, data, state);
return template;
} // buildMainPanelContext
/**
* Build the context for each template using template_index parameter passed
* in a form hidden field. Each case is associated with a template. (Not all
* templates implemented). See String[] TEMPLATES.
*
* @param index
* is the number contained in the template's template_index
*/
private String buildContextForTemplate(int index, VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
String realmId = "";
String site_type = "";
String sortedBy = "";
String sortedAsc = "";
ParameterParser params = data.getParameters();
context.put("tlang", rb);
context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
} else {
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
// Lists used in more than one template
// Access
List roles = new Vector();
// the hashtables for News and Web Content tools
Hashtable newsTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable wcUrls = new Hashtable();
List toolRegistrationList = new Vector();
List toolRegistrationSelectedList = new Vector();
ResourceProperties siteProperties = null;
// for showing site creation steps
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null) {
context.put("totalSteps", state
.getAttribute(SITE_CREATE_TOTAL_STEPS));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) {
context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP));
}
String hasGradSites = ServerConfigurationService.getString(
"withDissertation", Boolean.FALSE.toString());
context.put("cms", cms);
// course site type
context.put("courseSiteType", state.getAttribute(STATE_COURSE_SITE_TYPE));
//can the user create course sites?
context.put(STATE_SITE_ADD_COURSE, SiteService.allowAddCourseSite());
Site site = getStateSite(state);
switch (index) {
case 0:
/*
* buildContextForTemplate chef_site-list.vm
*
*/
// site types
List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);
// make sure auto-updates are enabled
Hashtable views = new Hashtable();
if (SecurityService.isSuperUser()) {
views.put(rb.getString("java.allmy"), rb
.getString("java.allmy"));
views.put(rb.getString("java.my") + " "
+ rb.getString("java.sites"), rb.getString("java.my"));
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
views.put(type + " " + rb.getString("java.sites"), type);
}
if (hasGradSites.equalsIgnoreCase("true")) {
views.put(rb.getString("java.gradtools") + " "
+ rb.getString("java.sites"), rb
.getString("java.gradtools"));
}
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, rb
.getString("java.allmy"));
}
context.put("superUser", Boolean.TRUE);
} else {
context.put("superUser", Boolean.FALSE);
views.put(rb.getString("java.allmy"), rb
.getString("java.allmy"));
// if there is a GradToolsStudent choice inside
boolean remove = false;
if (hasGradSites.equalsIgnoreCase("true")) {
try {
// the Grad Tools site option is only presented to
// GradTools Candidates
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
// am I a grad student?
if (!isGradToolsCandidate(userId)) {
// not a gradstudent
remove = true;
}
} catch (Exception e) {
remove = true;
}
} else {
// not support for dissertation sites
remove = true;
}
// do not show this site type in views
// sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT));
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
if (!type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) {
views
.put(type + " " + rb.getString("java.sites"),
type);
}
}
if (!remove) {
views.put(rb.getString("java.gradtools") + " "
+ rb.getString("java.sites"), rb
.getString("java.gradtools"));
}
// default view
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, rb
.getString("java.allmy"));
}
}
context.put("views", views);
if (state.getAttribute(STATE_VIEW_SELECTED) != null) {
context.put("viewSelected", (String) state
.getAttribute(STATE_VIEW_SELECTED));
}
String search = (String) state.getAttribute(STATE_SEARCH);
context.put("search_term", search);
sortedBy = (String) state.getAttribute(SORTED_BY);
if (sortedBy == null) {
state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
sortedBy = SortType.TITLE_ASC.toString();
}
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
String portalUrl = ServerConfigurationService.getPortalUrl();
context.put("portalUrl", portalUrl);
List sites = prepPage(state);
state.setAttribute(STATE_SITES, sites);
context.put("sites", sites);
context.put("totalPageNumber", new Integer(totalPageNumber(state)));
context.put("searchString", state.getAttribute(STATE_SEARCH));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state
.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state
.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
// put the service in the context (used for allow update calls on
// each site)
context.put("service", SiteService.getInstance());
context.put("sortby_title", SortType.TITLE_ASC.toString());
context.put("sortby_type", SortType.TYPE_ASC.toString());
context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
// top menu bar
Menu bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site"));
}
bar.add(new MenuEntry(rb.getString("java.revise"), null, true,
MenuItem.CHECKED_NA, "doGet_site", "sitesForm"));
bar.add(new MenuEntry(rb.getString("java.delete"), null, true,
MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm"));
context.put("menu", bar);
// default to be no pageing
context.put("paged", Boolean.FALSE);
Menu bar2 = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
// add the search commands
addSearchMenus(bar2, state);
context.put("menu2", bar2);
pagingInfoToContext(state, context);
return (String) getContext(data).get("template") + TEMPLATE[0];
case 1:
/*
* buildContextForTemplate chef_site-type.vm
*
*/
if (hasGradSites.equalsIgnoreCase("true")) {
context.put("withDissertation", Boolean.TRUE);
try {
// the Grad Tools site option is only presented to UM grad
// students
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
// am I a UM grad student?
Boolean isGradStudent = new Boolean(
isGradToolsCandidate(userId));
context.put("isGradStudent", isGradStudent);
// if I am a UM grad student, do I already have a Grad Tools
// site?
boolean noGradToolsSite = true;
if (hasGradToolsStudentSite(userId))
noGradToolsSite = false;
context
.put("noGradToolsSite",
new Boolean(noGradToolsSite));
} catch (Exception e) {
if (Log.isWarnEnabled()) {
M_log.warn("buildContextForTemplate chef_site-type.vm "
+ e);
}
}
} else {
context.put("withDissertation", Boolean.FALSE);
}
List types = (List) state.getAttribute(STATE_SITE_TYPES);
context.put("siteTypes", types);
// put selected/default site type into context
if (siteInfo.site_type != null && siteInfo.site_type.length() > 0) {
context.put("typeSelected", siteInfo.site_type);
} else if (types.size() > 0) {
context.put("typeSelected", types.get(0));
}
setTermListForContext(context, state, true); // true => only
// upcoming terms
setSelectedTermForContext(context, state, STATE_TERM_SELECTED);
return (String) getContext(data).get("template") + TEMPLATE[1];
case 2:
/*
* buildContextForTemplate chef_site-newSiteInformation.vm
*
*/
context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES));
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("type", siteType);
if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
List<SectionObject> cmRequestedList = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (cmRequestedList != null) {
context.put("cmRequestedSections", cmRequestedList);
context.put("back", "53");
}
List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (cmAuthorizerSectionList != null) {
context
.put("cmAuthorizerSections",
cmAuthorizerSectionList);
context.put("back", "36");
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("back", "37");
} else {
if (courseManagementIsImplemented()) {
context.put("back", "36");
} else {
context.put("back", "0");
context.put("template-index", "37");
}
}
context.put("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) {
context.put("selectedIcon", siteInfo.getIconUrl());
}
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null) {
context.put(FORM_ICON_URL, siteInfo.iconUrl);
}
context.put("back", "1");
}
context.put(FORM_TITLE, siteInfo.title);
context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description);
context.put(FORM_DESCRIPTION, siteInfo.description);
// defalt the site contact person to the site creator
if (siteInfo.site_contact_name.equals(NULL_STRING)
&& siteInfo.site_contact_email.equals(NULL_STRING)) {
User user = UserDirectoryService.getCurrentUser();
siteInfo.site_contact_name = user.getDisplayName();
siteInfo.site_contact_email = user.getEmail();
}
context.put("form_site_contact_name", siteInfo.site_contact_name);
context.put("form_site_contact_email", siteInfo.site_contact_email);
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[2];
case 3:
/*
* buildContextForTemplate chef_site-newSiteFeatures.vm
*
*/
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
}
context.put("defaultTools", ServerConfigurationService
.getToolsRequired(siteType));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// If this is the first time through, check for tools
// which should be selected by default.
List defaultSelectedTools = ServerConfigurationService
.getDefaultTools(siteType);
if (toolRegistrationSelectedList == null) {
toolRegistrationSelectedList = new Vector(defaultSelectedTools);
}
// String toolId's
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList);
// use ToolRegistrations for template list titles for multiple tool instances
context.put(STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
// The "Home" tool checkbox needs special treatment to be selected
// by
// default.
Boolean checkHome = (Boolean) state
.getAttribute(STATE_TOOL_HOME_SELECTED);
if (checkHome == null) {
if ((defaultSelectedTools != null)
&& defaultSelectedTools.contains(HOME_TOOL_ID)) {
checkHome = Boolean.TRUE;
}
}
context.put("check_home", checkHome);
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
context.put("import", state.getAttribute(STATE_IMPORT));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[3];
case 4:
/*
* buildContextForTemplate chef_site-addRemoveFeatures.vm
*
*/
context.put("SiteTitle", site.getTitle());
String type = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("defaultTools", ServerConfigurationService
.getToolsRequired(type));
boolean myworkspace_site = false;
// Put up tool lists filtered by category
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes.contains(type)) {
myworkspace_site = false;
}
if (SiteService.isUserSite(site.getId())
|| (type != null && type.equalsIgnoreCase("myworkspace"))) {
myworkspace_site = true;
type = "myworkspace";
}
context.put("myworkspace_site", new Boolean(myworkspace_site));
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST));
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
// titles for multiple tool instances
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
// get the email alias when an Email Archive tool has been selected
String channelReference = mailArchiveChannelReference(site.getId());
List aliases = AliasService.getAliases(channelReference, 1, 1);
if (aliases.size() > 0) {
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases
.get(0)).getId());
} else {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[4];
case 5:
/*
* buildContextForTemplate chef_site-addParticipant.vm
*
*/
context.put("title", site.getTitle());
roles = getRoles(state);
context.put("roles", roles);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("isCourseSite", siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))?Boolean.TRUE:Boolean.FALSE);
// Note that (for now) these strings are in both sakai.properties
// and sitesetupgeneric.properties
context.put("officialAccountSectionTitle", ServerConfigurationService
.getString("officialAccountSectionTitle"));
context.put("officialAccountName", ServerConfigurationService
.getString("officialAccountName"));
context.put("officialAccountLabel", ServerConfigurationService
.getString("officialAccountLabel"));
context.put("nonOfficialAccountSectionTitle", ServerConfigurationService
.getString("nonOfficialAccountSectionTitle"));
context.put("nonOfficialAccountName", ServerConfigurationService
.getString("nonOfficialAccountName"));
context.put("nonOfficialAccountLabel", ServerConfigurationService
.getString("nonOfficialAccountLabel"));
if (state.getAttribute("officialAccountValue") != null) {
context.put("officialAccountValue", (String) state
.getAttribute("officialAccountValue"));
}
if (state.getAttribute("nonOfficialAccountValue") != null) {
context.put("nonOfficialAccountValue", (String) state
.getAttribute("nonOfficialAccountValue"));
}
if (state.getAttribute("form_same_role") != null) {
context.put("form_same_role", ((Boolean) state
.getAttribute("form_same_role")).toString());
} else {
context.put("form_same_role", Boolean.TRUE.toString());
}
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[5];
case 8:
/*
* buildContextForTemplate chef_site-siteDeleteConfirm.vm
*
*/
String site_title = NULL_STRING;
String[] removals = (String[]) state
.getAttribute(STATE_SITE_REMOVALS);
List remove = new Vector();
String user = SessionManager.getCurrentSessionUserId();
String workspace = SiteService.getUserSiteId(user);
if (removals != null && removals.length != 0) {
for (int i = 0; i < removals.length; i++) {
String id = (String) removals[i];
if (!(id.equals(workspace))) {
try {
site_title = SiteService.getSite(id).getTitle();
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.doSite_delete_confirmed - IdUnusedException "
+ id);
addAlert(state, rb.getString("java.sitewith") + " "
+ id + " " + rb.getString("java.couldnt")
+ " ");
}
if (SiteService.allowRemoveSite(id)) {
try {
Site removeSite = SiteService.getSite(id);
remove.add(removeSite);
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException");
}
} else {
addAlert(state, site_title + " "
+ rb.getString("java.couldntdel") + " ");
}
} else {
addAlert(state, rb.getString("java.yourwork"));
}
}
if (remove.size() == 0) {
addAlert(state, rb.getString("java.click"));
}
}
context.put("removals", remove);
return (String) getContext(data).get("template") + TEMPLATE[8];
case 10:
/*
* buildContextForTemplate chef_site-newSiteConfirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
context.put("selectedAuthorizerCourse", state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
context.put("selectedRequestedCourse", state
.getAttribute(STATE_CM_REQUESTED_SECTIONS));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) {
context.put("selectedIcon", siteInfo.getIconUrl());
}
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType != null && siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null) {
context.put("iconUrl", siteInfo.iconUrl);
}
}
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("siteContactName", siteInfo.site_contact_name);
context.put("siteContactEmail", siteInfo.site_contact_email);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use Tool
// titles for multiple tool instances
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", new Boolean(siteInfo.include));
context.put("published", new Boolean(siteInfo.published));
context.put("joinable", new Boolean(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
// back to edit access page
context.put("back", "18");
context.put("importSiteTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("siteService", SiteService.getInstance());
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[10];
case 12:
/*
* buildContextForTemplate chef_site-siteInfo-list.vm
*
*/
context.put("userDirectoryService", UserDirectoryService
.getInstance());
try {
siteProperties = site.getProperties();
siteType = site.getType();
if (siteType != null) {
state.setAttribute(STATE_SITE_TYPE, siteType);
}
boolean isMyWorkspace = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
isMyWorkspace = true;
context.put("siteUserId", SiteService
.getSiteUserId(site.getId()));
}
}
context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));
String siteId = site.getId();
if (state.getAttribute(STATE_ICONS) != null) {
List skins = (List) state.getAttribute(STATE_ICONS);
for (int i = 0; i < skins.size(); i++) {
MyIcon s = (MyIcon) skins.get(i);
if (!StringUtil
.different(s.getUrl(), site.getIconUrl())) {
context.put("siteUnit", s.getName());
break;
}
}
}
context.put("siteIcon", site.getIconUrl());
context.put("siteTitle", site.getTitle());
context.put("siteDescription", site.getDescription());
context.put("siteJoinable", new Boolean(site.isJoinable()));
if (site.isPublished()) {
context.put("published", Boolean.TRUE);
} else {
context.put("published", Boolean.FALSE);
context.put("owner", site.getCreatedBy().getSortName());
}
Time creationTime = site.getCreatedTime();
if (creationTime != null) {
context.put("siteCreationDate", creationTime
.toStringLocalFull());
}
boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));
boolean allowUpdateGroupMembership = SiteService
.allowUpdateGroupMembership(siteId);
context.put("allowUpdateGroupMembership", Boolean
.valueOf(allowUpdateGroupMembership));
boolean allowUpdateSiteMembership = SiteService
.allowUpdateSiteMembership(siteId);
context.put("allowUpdateSiteMembership", Boolean
.valueOf(allowUpdateSiteMembership));
Menu b = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (allowUpdateSite)
{
// top menu bar
if (!isMyWorkspace) {
b.add(new MenuEntry(rb.getString("java.editsite"),
"doMenu_edit_site_info"));
}
b.add(new MenuEntry(rb.getString("java.edittools"),
"doMenu_edit_site_tools"));
// if the page order helper is available, not
// stealthed and not hidden, show the link
if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) {
b.add(new MenuEntry(rb.getString("java.orderpages"),
"doPageOrderHelper"));
}
}
if (allowUpdateSiteMembership)
{
// show add participant menu
if (!isMyWorkspace) {
// show the Add Participant menu
b.add(new MenuEntry(rb.getString("java.addp"),
"doMenu_siteInfo_addParticipant"));
// show the Edit Class Roster menu
if (siteType != null && siteType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
b.add(new MenuEntry(rb.getString("java.editc"),
"doMenu_siteInfo_editClass"));
}
}
}
if (allowUpdateGroupMembership) {
// show Manage Groups menu
if (!isMyWorkspace
&& (ServerConfigurationService
.getString("wsetup.group.support") == "" || ServerConfigurationService
.getString("wsetup.group.support")
.equalsIgnoreCase(Boolean.TRUE.toString()))) {
// show the group toolbar unless configured
// to not support group
b.add(new MenuEntry(rb.getString("java.group"),
"doMenu_group"));
}
}
if (allowUpdateSite)
{
if (!isMyWorkspace) {
List gradToolsSiteTypes = (List) state
.getAttribute(GRADTOOLS_SITE_TYPES);
boolean isGradToolSite = false;
if (siteType != null
&& gradToolsSiteTypes.contains(siteType)) {
isGradToolSite = true;
}
if (siteType == null || siteType != null
&& !isGradToolSite) {
// hide site access for GRADTOOLS
// type of sites
b.add(new MenuEntry(
rb.getString("java.siteaccess"),
"doMenu_edit_site_access"));
}
if (siteType == null || siteType != null
&& !isGradToolSite) {
// hide site duplicate and import
// for GRADTOOLS type of sites
if (SiteService.allowAddSite(null))
{
b.add(new MenuEntry(rb.getString("java.duplicate"),
"doMenu_siteInfo_duplicate"));
}
List updatableSites = SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null,
SortType.TITLE_ASC, null);
// import link should be visible even if only one
// site
if (updatableSites.size() > 0) {
b.add(new MenuEntry(
rb.getString("java.import"),
"doMenu_siteInfo_import"));
// a configuration param for
// showing/hiding import
// from file choice
String importFromFile = ServerConfigurationService
.getString("site.setup.import.file",
Boolean.TRUE.toString());
if (importFromFile.equalsIgnoreCase("true")) {
// htripath: June
// 4th added as per
// Kris and changed
// desc of above
b.add(new MenuEntry(rb
.getString("java.importFile"),
"doAttachmentsMtrlFrmFile"));
}
}
}
}
}
if (b.size() > 0)
{
// add the menus to vm
context.put("menu", b);
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
// editing from worksite setup tool
context.put("fromWSetup", Boolean.TRUE);
if (state.getAttribute(STATE_PREV_SITE) != null) {
context.put("prevSite", state
.getAttribute(STATE_PREV_SITE));
}
if (state.getAttribute(STATE_NEXT_SITE) != null) {
context.put("nextSite", state
.getAttribute(STATE_NEXT_SITE));
}
} else {
context.put("fromWSetup", Boolean.FALSE);
}
// allow view roster?
boolean allowViewRoster = SiteService.allowViewRoster(siteId);
if (allowViewRoster) {
context.put("viewRoster", Boolean.TRUE);
} else {
context.put("viewRoster", Boolean.FALSE);
}
// set participant list
if (allowUpdateSite || allowViewRoster
|| allowUpdateSiteMembership) {
Collection participantsCollection = getParticipantList(state);
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy == null) {
state.setAttribute(SORTED_BY,
SORTED_BY_PARTICIPANT_NAME);
sortedBy = SORTED_BY_PARTICIPANT_NAME;
}
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
context.put("participantListSize", new Integer(participantsCollection.size()));
context.put("participantList", prepPage(state));
pagingInfoToContext(state, context);
}
context.put("include", Boolean.valueOf(site.isPubView()));
// site contact information
String contactName = siteProperties
.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null) {
User u = site.getCreatedBy();
String email = u.getEmail();
if (email != null) {
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
if (contactName != null) {
context.put("contactName", contactName);
}
if (contactEmail != null) {
context.put("contactEmail", contactEmail);
}
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
coursesIntoContext(state, context, site);
context.put("term", siteProperties
.getProperty(PROP_SITE_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
} catch (Exception e) {
M_log.warn(this + " site info list: " + e.toString());
}
roles = getRoles(state);
context.put("roles", roles);
// will have the choice to active/inactive user or not
String activeInactiveUser = ServerConfigurationService.getString(
"activeInactiveUser", Boolean.FALSE.toString());
if (activeInactiveUser.equalsIgnoreCase("true")) {
context.put("activeInactiveUser", Boolean.TRUE);
} else {
context.put("activeInactiveUser", Boolean.FALSE);
}
context.put("groupsWithMember", site
.getGroupsWithMember(UserDirectoryService.getCurrentUser()
.getId()));
return (String) getContext(data).get("template") + TEMPLATE[12];
case 13:
/*
* buildContextForTemplate chef_site-siteInfo-editInfo.vm
*
*/
siteProperties = site.getProperties();
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, site.getType())));
context.put("type", site.getType());
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("skins", state.getAttribute(STATE_ICONS));
if (state.getAttribute(FORM_SITEINFO_SKIN) != null) {
context.put("selectedIcon", state
.getAttribute(FORM_SITEINFO_SKIN));
} else if (site.getIconUrl() != null) {
context.put("selectedIcon", site.getIconUrl());
}
setTermListForContext(context, state, true); // true->only future terms
if (state.getAttribute(FORM_SITEINFO_TERM) == null) {
String currentTerm = site.getProperties().getProperty(
PROP_SITE_TERM);
if (currentTerm != null) {
state.setAttribute(FORM_SITEINFO_TERM, currentTerm);
}
}
setSelectedTermForContext(context, state, FORM_SITEINFO_TERM);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null
&& StringUtil.trimToNull(site.getIconUrl()) != null) {
state.setAttribute(FORM_SITEINFO_ICON_URL, site
.getIconUrl());
}
if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null) {
context.put("iconUrl", state
.getAttribute(FORM_SITEINFO_ICON_URL));
}
}
context.put("description", state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("short_description", state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("form_site_contact_name", state
.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("form_site_contact_email", state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
// Display of appearance icon/url list with course site based on
// "disable.course.site.skin.selection" value set with
// sakai.properties file.
if ((ServerConfigurationService
.getString("disable.course.site.skin.selection"))
.equals("true")) {
context.put("disableCourseSelection", Boolean.TRUE);
}
return (String) getContext(data).get("template") + TEMPLATE[13];
case 14:
/*
* buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm
*
*/
siteProperties = site.getProperties();
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
context.put("oTitle", site.getTitle());
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("description", state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("oDescription", site.getDescription());
context.put("short_description", state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("oShort_description", site.getShortDescription());
context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN));
context.put("oSkin", site.getIconUrl());
context.put("skins", state.getAttribute(STATE_ICONS));
context.put("oIcon", site.getIconUrl());
context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL));
context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE));
context.put("oInclude", Boolean.valueOf(site.isPubView()));
context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("oName", siteProperties
.getProperty(PROP_SITE_CONTACT_NAME));
context.put("email", state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
context.put("oEmail", siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL));
return (String) getContext(data).get("template") + TEMPLATE[14];
case 15:
/*
* buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm
*
*/
context.put("title", site.getTitle());
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
myworkspace_site = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
myworkspace_site = true;
site_type = "myworkspace";
}
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("selectedTools", orderToolIds(state, (String) state
.getAttribute(STATE_SITE_TYPE), (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)));
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("oldSelectedHome", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME));
context.put("continueIndex", "12");
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
// titles for multiple tool instances
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
if (fromENWModifyView(state)) {
context.put("back", "26");
} else {
context.put("back", "4");
}
return (String) getContext(data).get("template") + TEMPLATE[15];
case 18:
/*
* buildContextForTemplate chef_siteInfo-editAccess.vm
*
*/
List publicChangeableSiteTypes = (List) state
.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
List unJoinableSiteTypes = (List) state
.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);
if (site != null) {
// editing existing site
context.put("site", site);
siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state
.getAttribute(STATE_SITE_TYPE)
: null;
if (siteType != null
&& publicChangeableSiteTypes.contains(siteType)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(site.isPubView()));
if (siteType != null && !unJoinableSiteTypes.contains(siteType)) {
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
if (state.getAttribute(STATE_JOINABLE) == null) {
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site
.isJoinable()));
}
if (state.getAttribute(STATE_JOINERROLE) == null
|| state.getAttribute(STATE_JOINABLE) != null
&& ((Boolean) state.getAttribute(STATE_JOINABLE))
.booleanValue()) {
state.setAttribute(STATE_JOINERROLE, site
.getJoinerRole());
}
if (state.getAttribute(STATE_JOINABLE) != null) {
context.put("joinable", state
.getAttribute(STATE_JOINABLE));
}
if (state.getAttribute(STATE_JOINERROLE) != null) {
context.put("joinerRole", state
.getAttribute(STATE_JOINERROLE));
}
} else {
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
context.put("roles", getRoles(state));
context.put("back", "12");
} else {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteInfo.site_type != null
&& publicChangeableSiteTypes
.contains(siteInfo.site_type)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(siteInfo.getInclude()));
context.put("published", Boolean.valueOf(siteInfo
.getPublished()));
if (siteInfo.site_type != null
&& !unJoinableSiteTypes.contains(siteInfo.site_type)) {
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
} else {
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
// use the type's template, if defined
String realmTemplate = "!site.template";
if (siteInfo.site_type != null) {
realmTemplate = realmTemplate + "." + siteInfo.site_type;
}
try {
AuthzGroup r = AuthzGroupService
.getAuthzGroup(realmTemplate);
context.put("roles", r.getRoles());
} catch (GroupNotDefinedException e) {
try {
AuthzGroup rr = AuthzGroupService
.getAuthzGroup("!site.template");
context.put("roles", rr.getRoles());
} catch (GroupNotDefinedException ee) {
}
}
// new site, go to confirmation page
context.put("continue", "10");
if (fromENWModifyView(state)) {
context.put("back", "26");
} else if (state.getAttribute(STATE_IMPORT) != null) {
context.put("back", "27");
} else {
context.put("back", "3");
}
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
}
}
return (String) getContext(data).get("template") + TEMPLATE[18];
case 19:
/*
* buildContextForTemplate chef_site-addParticipant-sameRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("participantList", state
.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("form_selectedRole", state
.getAttribute("form_selectedRole"));
return (String) getContext(data).get("template") + TEMPLATE[19];
case 20:
/*
* buildContextForTemplate chef_site-addParticipant-differentRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("participantList", state
.getAttribute(STATE_ADD_PARTICIPANTS));
return (String) getContext(data).get("template") + TEMPLATE[20];
case 21:
/*
* buildContextForTemplate chef_site-addParticipant-notification.vm
*
*/
context.put("title", site.getTitle());
context.put("sitePublished", Boolean.valueOf(site.isPublished()));
if (state.getAttribute("form_selectedNotify") == null) {
state.setAttribute("form_selectedNotify", Boolean.FALSE);
}
context.put("notify", state.getAttribute("form_selectedNotify"));
boolean same_role = state.getAttribute("form_same_role") == null ? true
: ((Boolean) state.getAttribute("form_same_role"))
.booleanValue();
if (same_role) {
context.put("backIndex", "19");
} else {
context.put("backIndex", "20");
}
return (String) getContext(data).get("template") + TEMPLATE[21];
case 22:
/*
* buildContextForTemplate chef_site-addParticipant-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("participants", state
.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("notify", state.getAttribute("form_selectedNotify"));
context.put("roles", getRoles(state));
context.put("same_role", state.getAttribute("form_same_role"));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context
.put("selectedRole", state
.getAttribute("form_selectedRole"));
return (String) getContext(data).get("template") + TEMPLATE[22];
case 26:
/*
* buildContextForTemplate chef_site-modifyENW.vm
*
*/
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean existingSite = site != null ? true : false;
if (existingSite) {
// revising a existing site's tool
context.put("existingSite", Boolean.TRUE);
context.put("back", "4");
context.put("continue", "15");
context.put("function", "eventSubmit_doAdd_remove_features");
} else {
// new site
context.put("existingSite", Boolean.FALSE);
context.put("function", "eventSubmit_doAdd_features");
if (state.getAttribute(STATE_IMPORT) != null) {
context.put("back", "27");
} else {
// new site, go to edit access page
context.put("back", "3");
}
context.put("continue", "18");
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_MULTIPLE_TOOL_ID_SET, state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET));
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP));
context.put("toolManager", ToolManager.getInstance());
String emailId = (String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
if (emailId != null) {
context.put("emailId", emailId);
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
return (String) getContext(data).get("template") + TEMPLATE[26];
case 27:
/*
* buildContextForTemplate chef_site-importSites.vm
*
*/
existingSite = site != null ? true : false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (existingSite) {
// revising a existing site's tool
context.put("continue", "12");
context.put("back", "28");
context.put("totalSteps", "2");
context.put("step", "2");
context.put("currentSite", site);
} else {
// new site, go to edit access page
context.put("back", "3");
if (fromENWModifyView(state)) {
context.put("continue", "26");
} else {
context.put("continue", "18");
}
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("selectedTools", orderToolIds(state, site_type,
(List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); // String toolId's
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
return (String) getContext(data).get("template") + TEMPLATE[27];
case 28:
/*
* buildContextForTemplate chef_siteinfo-import.vm
*
*/
context.put("currentSite", site);
context.put("importSiteList", state
.getAttribute(STATE_IMPORT_SITES));
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
return (String) getContext(data).get("template") + TEMPLATE[28];
case 29:
/*
* buildContextForTemplate chef_siteinfo-duplicate.vm
*
*/
context.put("siteTitle", site.getTitle());
String sType = site.getType();
if (sType != null && sType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("currentTermId", site.getProperties().getProperty(
PROP_SITE_TERM));
setTermListForContext(context, state, true); // true upcoming only
} else {
context.put("isCourseSite", Boolean.FALSE);
}
if (state.getAttribute(SITE_DUPLICATED) == null) {
context.put("siteDuplicated", Boolean.FALSE);
} else {
context.put("siteDuplicated", Boolean.TRUE);
context.put("duplicatedName", state
.getAttribute(SITE_DUPLICATED_NAME));
}
return (String) getContext(data).get("template") + TEMPLATE[29];
case 36:
/*
* buildContextForTemplate chef_site-newSiteCourse.vm
*/
// SAK-9824
Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE);
context.put("enableCourseCreationForUser", enableCourseCreationForUser);
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
setTermListForContext(context, state, true); // true -> upcoming only
List providerCourseList = (List) state
.getAttribute(SITE_PROVIDER_COURSE_LIST);
coursesIntoContext(state, context, site);
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
context.put("term", t);
if (t != null) {
String userId = UserDirectoryService.getCurrentUser().getEid();
List courses = prepareCourseAndSectionListing(userId, t
.getEid(), state);
if (courses != null && courses.size() > 0) {
Vector notIncludedCourse = new Vector();
// remove included sites
for (Iterator i = courses.iterator(); i.hasNext();) {
CourseObject c = (CourseObject) i.next();
if (providerCourseList == null || providerCourseList != null && !providerCourseList.contains(c.getEid())) {
notIncludedCourse.add(c);
}
}
state.setAttribute(STATE_TERM_COURSE_LIST,
notIncludedCourse);
} else {
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
}
// step number used in UI
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1"));
} else {
// need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS
// contains sections that doens't belongs to current user and
// STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does -
// v2.4 daisyf
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null
|| state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
List<String> providerSectionList = (List<String>) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (providerSectionList != null) {
/*
List list1 = prepareSectionObject(providerSectionList,
(String) state
.getAttribute(STATE_CM_CURRENT_USERID));
*/
context.put("selectedProviderCourse", providerSectionList);
}
List<SectionObject> authorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (authorizerSectionList != null) {
List authorizerList = (List) state
.getAttribute(STATE_CM_AUTHORIZER_LIST);
//authorizerList is a list of SectionObject
/*
String userId = null;
if (authorizerList != null) {
userId = (String) authorizerList.get(0);
}
List list2 = prepareSectionObject(
authorizerSectionList, userId);
*/
ArrayList list2 = new ArrayList();
for (int i=0; i<authorizerSectionList.size();i++){
SectionObject so = (SectionObject)authorizerSectionList.get(i);
list2.add(so.getEid());
}
context.put("selectedAuthorizerCourse", list2);
}
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
context.put("selectedManualCourse", Boolean.TRUE);
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("currentUserId", (String) state
.getAttribute(STATE_CM_CURRENT_USERID));
context.put("form_additional", (String) state
.getAttribute(FORM_ADDITIONAL));
context.put("authorizers", getAuthorizers(state));
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
context.put("backIndex", "1");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
context.put("backIndex", "");
}
List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST);
context.put("termCourseList", state
.getAttribute(STATE_TERM_COURSE_LIST));
// added for 2.4 -daisyf
context.put("campusDirectory", getCampusDirectory());
context.put("userId", (String) state
.getAttribute(STATE_INSTRUCTOR_SELECTED));
/*
* for measuring how long it takes to load sections java.util.Date
* date = new java.util.Date(); M_log.debug("***2. finish at:
* "+date); M_log.debug("***3. userId:"+(String) state
* .getAttribute(STATE_INSTRUCTOR_SELECTED));
*/
return (String) getContext(data).get("template") + TEMPLATE[36];
case 37:
/*
* buildContextForTemplate chef_site-newSiteCourseManual.vm
*/
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
}
buildInstructorSectionsList(state, params, context);
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("form_additional", siteInfo.additional);
context.put("form_title", siteInfo.title);
context.put("form_description", siteInfo.description);
context.put("officialAccountName", ServerConfigurationService
.getString("officialAccountName", ""));
context.put("value_uniqname", state
.getAttribute(STATE_SITE_QUEST_UNIQNAME));
int number = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("currentNumber", new Integer(number));
}
context.put("currentNumber", new Integer(number));
context.put("listSize", number>0?new Integer(number - 1):0);
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null && ((List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)).size() > 0)
{
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
List l = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
context.put("selectedProviderCourse", l);
context.put("size", new Integer(l.size() - 1));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
List l = (List) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
context.put("cmRequestedSections", l);
}
if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO))
{
context.put("editSite", Boolean.TRUE);
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (site == null) {
// v2.4 - added & modified by daisyf
if (courseManagementIsImplemented() && state.getAttribute(STATE_TERM_COURSE_LIST) != null)
{
// back to the list view of sections
context.put("back", "36");
} else {
context.put("back", "1");
}
if (state.getAttribute(STATE_AUTO_ADD) != null) {
context.put("autoAdd", Boolean.TRUE);
// context.put("back", "36");
}
}
else
{
// editing site
context.put("back", "36");
}
isFutureTermSelected(state);
context.put("isFutureTerm", state
.getAttribute(STATE_FUTURE_TERM_SELECTED));
context.put("weeksAhead", ServerConfigurationService.getString(
"roster.available.weeks.before.term.start", "0"));
return (String) getContext(data).get("template") + TEMPLATE[37];
case 42:
/*
* buildContextForTemplate chef_site-gradtoolsConfirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
toolRegistrationList = (Vector) state
.getAttribute(STATE_PROJECT_TOOL_LIST);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%%
// use
// Tool
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", new Boolean(siteInfo.include));
return (String) getContext(data).get("template") + TEMPLATE[42];
case 43:
/*
* buildContextForTemplate chef_siteInfo-editClass.vm
*
*/
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.addclasses"),
"doMenu_siteInfo_addClass"));
}
context.put("menu", bar);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
return (String) getContext(data).get("template") + TEMPLATE[43];
case 44:
/*
* buildContextForTemplate chef_siteInfo-addCourseConfirm.vm
*
*/
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
context.put("providerAddCourses", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null)
{
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int addNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue() - 1;
context.put("manualAddNumber", new Integer(addNumber));
context.put("requestFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("backIndex", "37");
} else {
context.put("backIndex", "36");
}
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[44];
// htripath - import materials from classic
case 45:
/*
* buildContextForTemplate chef_siteInfo-importMtrlMaster.vm
*
*/
return (String) getContext(data).get("template") + TEMPLATE[45];
case 46:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopy.vm
*
*/
// this is for list display in listbox
context
.put("allZipSites", state
.getAttribute(ALL_ZIP_IMPORT_SITES));
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
// zip file
// context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME));
return (String) getContext(data).get("template") + TEMPLATE[46];
case 47:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[47];
case 48:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[48];
case 49:
/*
* buildContextForTemplate chef_siteInfo-group.vm
*
*/
context.put("site", site);
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowUpdateSite(site.getId())
|| SiteService.allowUpdateGroupMembership(site.getId())) {
bar.add(new MenuEntry(rb.getString("java.newgroup"), "doGroup_new"));
}
context.put("menu", bar);
// the group list
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
// only show groups created by WSetup tool itself
Collection groups = (Collection) site.getGroups();
List groupsByWSetup = new Vector();
for (Iterator gIterator = groups.iterator(); gIterator.hasNext();) {
Group gNext = (Group) gIterator.next();
String gProp = gNext.getProperties().getProperty(
GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString())) {
groupsByWSetup.add(gNext);
}
}
if (sortedBy != null && sortedAsc != null) {
context.put("groups", new SortedIterator(groupsByWSetup
.iterator(), new SiteComparator(sortedBy, sortedAsc)));
}
return (String) getContext(data).get("template") + TEMPLATE[49];
case 50:
/*
* buildContextForTemplate chef_siteInfo-groupedit.vm
*
*/
Group g = getStateGroup(state);
if (g != null) {
context.put("group", g);
context.put("newgroup", Boolean.FALSE);
} else {
context.put("newgroup", Boolean.TRUE);
}
if (state.getAttribute(STATE_GROUP_TITLE) != null) {
context.put("title", state.getAttribute(STATE_GROUP_TITLE));
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null) {
context.put("description", state
.getAttribute(STATE_GROUP_DESCRIPTION));
}
Iterator siteMembers = new SortedIterator(getParticipantList(state)
.iterator(), new SiteComparator(SORTED_BY_PARTICIPANT_NAME,
Boolean.TRUE.toString()));
if (siteMembers != null && siteMembers.hasNext()) {
context.put("generalMembers", siteMembers);
}
Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
if (state.getAttribute(STATE_GROUP_MEMBERS) != null) {
context.put("groupMembers", new SortedIterator(groupMembersSet
.iterator(), new SiteComparator(SORTED_BY_MEMBER_NAME,
Boolean.TRUE.toString())));
}
context.put("groupMembersClone", groupMembersSet);
context.put("userDirectoryService", UserDirectoryService
.getInstance());
return (String) getContext(data).get("template") + TEMPLATE[50];
case 51:
/*
* buildContextForTemplate chef_siteInfo-groupDeleteConfirm.vm
*
*/
context.put("site", site);
context
.put("removeGroupIds", new ArrayList(Arrays
.asList((String[]) state
.getAttribute(STATE_GROUP_REMOVE))));
return (String) getContext(data).get("template") + TEMPLATE[51];
case 53: {
/*
* build context for chef_site-findCourse.vm
*/
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state
.getAttribute(STATE_CM_LEVEL_SELECTIONS);
if (cmLevels == null)
{
cmLevels = getCMLevelLabels();
}
SectionObject selectedSect = (SectionObject) state
.getAttribute(STATE_CM_SELECTED_SECTION);
List<SectionObject> requestedSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (courseManagementIsImplemented() && cms != null) {
context.put("cmsAvailable", new Boolean(true));
}
int cmLevelSize = 0;
if (cms == null || !courseManagementIsImplemented()
|| cmLevels == null || cmLevels.size() < 1) {
// TODO: redirect to manual entry: case #37
} else {
cmLevelSize = cmLevels.size();
Object levelOpts[] = state.getAttribute(STATE_CM_LEVEL_OPTS) == null?new Object[cmLevelSize]:(Object[])state.getAttribute(STATE_CM_LEVEL_OPTS);
int numSelections = 0;
if (selections != null)
numSelections = selections.size();
// execution will fall through these statements based on number of selections already made
if (numSelections == cmLevelSize - 1)
{
levelOpts[numSelections] = getCMSections((String) selections.get(numSelections-1));
}
else if (numSelections == cmLevelSize - 2)
{
levelOpts[numSelections] = getCMCourseOfferings((String) selections.get(numSelections-1), t.getEid());
}
else if (numSelections < cmLevelSize)
{
levelOpts[numSelections] = sortCmObject(cms.findCourseSets((String) cmLevels.get(numSelections==0?0:numSelections-1)));
}
// always set the top level
levelOpts[0] = sortCmObject(cms.findCourseSets((String) cmLevels.get(0)));
// clean further element inside the array
for (int i = numSelections + 1; i<cmLevelSize; i++)
{
levelOpts[i] = null;
}
context.put("cmLevelOptions", Arrays.asList(levelOpts));
state.setAttribute(STATE_CM_LEVEL_OPTS, levelOpts);
}
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int courseInd = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(courseInd - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("cmLevels", cmLevels);
context.put("cmLevelSelections", selections);
context.put("selectedCourse", selectedSect);
context.put("cmRequestedSections", requestedSections);
if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO))
{
context.put("editSite", Boolean.TRUE);
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
if (state.getAttribute(STATE_TERM_COURSE_LIST) != null)
{
context.put("backIndex", "36");
}
else
{
context.put("backIndex", "1");
}
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
context.put("backIndex", "36");
}
context.put("authzGroupService", AuthzGroupService.getInstance());
return (String) getContext(data).get("template") + TEMPLATE[53];
}
}
// should never be reached
return (String) getContext(data).get("template") + TEMPLATE[0];
} // buildContextForTemplate
/**
* Launch the Page Order Helper Tool -- for ordering, adding and customizing
* pages
*
* @see case 12
*
*/
public void doPageOrderHelper(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// pass in the siteId of the site to be ordered (so it can configure
// sites other then the current site)
SessionManager.getCurrentToolSession().setAttribute(
HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
// launch the helper
startHelper(data.getRequest(), "sakai-site-pageorder-helper");
}
// htripath: import materials from classic
/**
* Master import -- for import materials from a file
*
* @see case 45
*
*/
public void doAttachmentsMtrlFrmFile(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// state.setAttribute(FILE_UPLOAD_MAX_SIZE,
// ServerConfigurationService.getString("content.upload.max", "1"));
state.setAttribute(STATE_TEMPLATE_INDEX, "45");
} // doImportMtrlFrmFile
/**
* Handle File Upload request
*
* @see case 46
* @throws Exception
*/
public void doUpload_Mtrl_Frm_File(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
List allzipList = new Vector();
List finalzipList = new Vector();
List directcopyList = new Vector();
// see if the user uploaded a file
FileItem fileFromUpload = null;
String fileName = null;
fileFromUpload = data.getParameters().getFileItem("file");
String max_file_size_mb = ServerConfigurationService.getString(
"content.upload.max", "1");
int max_bytes = 1024 * 1024;
try {
max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024;
} catch (Exception e) {
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1024 * 1024;
}
if (fileFromUpload == null) {
// "The user submitted a file to upload but it was too big!"
addAlert(state, rb.getString("importFile.size") + " "
+ max_file_size_mb + "MB "
+ rb.getString("importFile.exceeded"));
} else if (fileFromUpload.getFileName() == null
|| fileFromUpload.getFileName().length() == 0) {
addAlert(state, rb.getString("importFile.choosefile"));
} else {
byte[] fileData = fileFromUpload.get();
if (fileData.length >= max_bytes) {
addAlert(state, rb.getString("size") + " " + max_file_size_mb
+ "MB " + rb.getString("importFile.exceeded"));
} else if (fileData.length > 0) {
if (importService.isValidArchive(fileData)) {
ImportDataSource importDataSource = importService
.parseFromFile(fileData);
Log.info("chef", "Getting import items from manifest.");
List lst = importDataSource.getItemCategories();
if (lst != null && lst.size() > 0) {
Iterator iter = lst.iterator();
while (iter.hasNext()) {
ImportMetadata importdata = (ImportMetadata) iter
.next();
// Log.info("chef","Preparing import
// item '" + importdata.getId() + "'");
if ((!importdata.isMandatory())
&& (importdata.getFileName()
.endsWith(".xml"))) {
allzipList.add(importdata);
} else {
directcopyList.add(importdata);
}
}
}
// set Attributes
state.setAttribute(ALL_ZIP_IMPORT_SITES, allzipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, finalzipList);
state.setAttribute(DIRECT_ZIP_IMPORT_SITES, directcopyList);
state.setAttribute(CLASSIC_ZIP_FILE_NAME, fileName);
state.setAttribute(IMPORT_DATA_SOURCE, importDataSource);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} else { // uploaded file is not a valid archive
}
}
}
} // doImportMtrlFrmFile
/**
* Handle addition to list request
*
* @param data
*/
public void doAdd_MtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List importSites = new ArrayList(Arrays.asList(params
.getStrings("addImportSelected")));
for (int i = 0; i < importSites.size(); i++) {
String value = (String) importSites.get(i);
fnlList.add(removeItems(value, zipList));
}
state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} // doAdd_MtrlSite
/**
* Helper class for Add and remove
*
* @param value
* @param items
* @return
*/
public ImportMetadata removeItems(String value, List items) {
ImportMetadata result = null;
for (int i = 0; i < items.size(); i++) {
ImportMetadata item = (ImportMetadata) items.get(i);
if (value.equals(item.getId())) {
result = (ImportMetadata) items.remove(i);
break;
}
}
return result;
}
/**
* Handle the request for remove
*
* @param data
*/
public void doRemove_MtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List importSites = new ArrayList(Arrays.asList(params
.getStrings("removeImportSelected")));
for (int i = 0; i < importSites.size(); i++) {
String value = (String) importSites.get(i);
zipList.add(removeItems(value, fnlList));
}
state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} // doAdd_MtrlSite
/**
* Handle the request for copy
*
* @param data
*/
public void doCopyMtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "47");
} // doCopy_MtrlSite
/**
* Handle the request for Save
*
* @param data
* @throws ImportException
*/
public void doSaveMtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List directList = (List) state.getAttribute(DIRECT_ZIP_IMPORT_SITES);
ImportDataSource importDataSource = (ImportDataSource) state
.getAttribute(IMPORT_DATA_SOURCE);
// combine the selected import items with the mandatory import items
fnlList.addAll(directList);
Log.info("chef", "doSaveMtrlSite() about to import " + fnlList.size()
+ " top level items");
Log.info("chef", "doSaveMtrlSite() the importDataSource is "
+ importDataSource.getClass().getName());
if (importDataSource instanceof SakaiArchive) {
Log.info("chef",
"doSaveMtrlSite() our data source is a Sakai format");
((SakaiArchive) importDataSource).buildSourceFolder(fnlList);
Log.info("chef", "doSaveMtrlSite() source folder is "
+ ((SakaiArchive) importDataSource).getSourceFolder());
ArchiveService.merge(((SakaiArchive) importDataSource)
.getSourceFolder(), siteId, null);
} else {
importService.doImportItems(importDataSource
.getItemsForCategories(fnlList), siteId);
}
// remove attributes
state.removeAttribute(ALL_ZIP_IMPORT_SITES);
state.removeAttribute(FINAL_ZIP_IMPORT_SITES);
state.removeAttribute(DIRECT_ZIP_IMPORT_SITES);
state.removeAttribute(CLASSIC_ZIP_FILE_NAME);
state.removeAttribute(SESSION_CONTEXT_ID);
state.removeAttribute(IMPORT_DATA_SOURCE);
state.setAttribute(STATE_TEMPLATE_INDEX, "48");
// state.setAttribute(STATE_TEMPLATE_INDEX, "28");
} // doSave_MtrlSite
public void doSaveMtrlSiteMsg(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// remove attributes
state.removeAttribute(ALL_ZIP_IMPORT_SITES);
state.removeAttribute(FINAL_ZIP_IMPORT_SITES);
state.removeAttribute(DIRECT_ZIP_IMPORT_SITES);
state.removeAttribute(CLASSIC_ZIP_FILE_NAME);
state.removeAttribute(SESSION_CONTEXT_ID);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
// htripath-end
/**
* Handle the site search request.
*/
public void doSite_search(RunData data, Context context) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read the search form field into the state object
String search = StringUtil.trimToNull(data.getParameters().getString(
FORM_SEARCH));
// set the flag to go to the prev page on the next list
if (search == null) {
state.removeAttribute(STATE_SEARCH);
} else {
state.setAttribute(STATE_SEARCH, search);
}
} // doSite_search
/**
* Handle a Search Clear request.
*/
public void doSite_search_clear(RunData data, Context context) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// clear the search
state.removeAttribute(STATE_SEARCH);
} // doSite_search_clear
private void coursesIntoContext(SessionState state, Context context,
Site site) {
List providerCourseList = getProviderCourseList(StringUtil
.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null && providerCourseList.size() > 0) {
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
String sectionTitleString = "";
for(int i = 0; i < providerCourseList.size(); i++)
{
String sectionId = (String) providerCourseList.get(i);
try
{
Section s = cms.getSection(sectionId);
sectionTitleString = (i>0)?sectionTitleString + "<br />" + s.getTitle():s.getTitle();
}
catch (Exception e)
{
M_log.warn("coursesIntoContext " + e.getMessage() + " sectionId=" + sectionId);
}
}
context.put("providedSectionTitle", sectionTitleString);
context.put("providerCourseList", providerCourseList);
}
// put manual requested courses into context
courseListFromStringIntoContext(state, context, site, STATE_CM_REQUESTED_SECTIONS, STATE_CM_REQUESTED_SECTIONS, "cmRequestedCourseList");
// put manual requested courses into context
courseListFromStringIntoContext(state, context, site, PROP_SITE_REQUEST_COURSE, SITE_MANUAL_COURSE_LIST, "manualCourseList");
}
private void courseListFromStringIntoContext(SessionState state, Context context, Site site, String site_prop_name, String state_attribute_string, String context_string) {
String courseListString = StringUtil.trimToNull(site.getProperties().getProperty(site_prop_name));
if (courseListString != null) {
List courseList = new Vector();
if (courseListString.indexOf("+") != -1) {
courseList = new ArrayList(Arrays.asList(courseListString.split("\\+")));
} else {
courseList.add(courseListString);
}
if (state_attribute_string.equals(STATE_CM_REQUESTED_SECTIONS))
{
// need to construct the list of SectionObjects
List<SectionObject> soList = new Vector();
for (int i=0; i<courseList.size();i++)
{
String courseEid = (String) courseList.get(i);
try
{
Section s = cms.getSection(courseEid);
if (s!=null)
soList.add(new SectionObject(s));
}
catch (Exception e)
{
M_log.warn(e.getMessage() + courseEid);
}
}
if (soList.size() > 0)
state.setAttribute(STATE_CM_REQUESTED_SECTIONS, soList);
}
else
{
// the list is of String objects
state.setAttribute(state_attribute_string, courseList);
}
}
context.put(context_string, state.getAttribute(state_attribute_string));
}
/**
* buildInstructorSectionsList Build the CourseListItem list for this
* Instructor for the requested Term
*
*/
private void buildInstructorSectionsList(SessionState state,
ParameterParser params, Context context) {
// Site information
// The sections of the specified term having this person as Instructor
context.put("providerCourseSectionList", state
.getAttribute("providerCourseSectionList"));
context.put("manualCourseSectionList", state
.getAttribute("manualCourseSectionList"));
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
setTermListForContext(context, state, true); //-> future terms only
context.put(STATE_TERM_COURSE_LIST, state
.getAttribute(STATE_TERM_COURSE_LIST));
context.put("tlang", rb);
} // buildInstructorSectionsList
/**
* getProviderCourseList a course site/realm id in one of three formats, for
* a single section, for multiple sections of the same course, or for a
* cross-listing having multiple courses. getProviderCourseList parses a
* realm id into year, term, campus_code, catalog_nbr, section components.
*
* @param id
* is a String representation of the course realm id (external
* id).
*/
private List getProviderCourseList(String id) {
Vector rv = new Vector();
if (id == null || id == NULL_STRING) {
return rv;
}
// Break Provider Id into course id parts
String[] courseIds = groupProvider.unpackId(id);
// Iterate through course ids
for (int i=0; i<courseIds.length; i++) {
String courseId = (String) courseIds[i];
rv.add(courseId);
}
return rv;
} // getProviderCourseList
/**
* {@inheritDoc}
*/
protected int sizeResources(SessionState state) {
int size = 0;
String search = "";
String userId = SessionManager.getCurrentSessionUserId();
// if called from the site list page
if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) {
search = StringUtil.trimToNull((String) state
.getAttribute(STATE_SEARCH));
if (SecurityService.isSuperUser()) {
// admin-type of user
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(rb.getString("java.allmy"))) {
// search for non-user sites, using
// the criteria
size = SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
null, search, null);
} else if (view.equals(rb.getString("java.my"))) {
// search for a specific user site
// for the particular user id in the
// criteria - exact match only
try {
SiteService.getSite(SiteService
.getUserSiteId(search));
size++;
} catch (IdUnusedException e) {
}
} else if (view.equalsIgnoreCase(rb
.getString("java.gradtools"))) {
// search for gradtools sites
size = SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
state
.getAttribute(GRADTOOLS_SITE_TYPES),
search, null);
} else {
// search for specific type of sites
size = SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
view, search, null);
}
}
} else {
Site userWorkspaceSite = null;
try {
userWorkspaceSite = SiteService.getSite(SiteService
.getUserSiteId(userId));
} catch (IdUnusedException e) {
M_log.warn("Cannot find user "
+ SessionManager.getCurrentSessionUserId()
+ "'s My Workspace site.");
}
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(rb.getString("java.allmy"))) {
view = null;
// add my workspace if any
if (userWorkspaceSite != null) {
if (search != null) {
if (userId.indexOf(search) != -1) {
size++;
}
} else {
size++;
}
}
size += SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
null, search, null);
} else if (view.equalsIgnoreCase(rb
.getString("java.gradtools"))) {
// search for gradtools sites
size += SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
state
.getAttribute(GRADTOOLS_SITE_TYPES),
search, null);
} else {
// search for specific type of sites
size += SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
view, search, null);
}
}
}
}
// for SiteInfo list page
else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals(
"12")) {
Collection l = (Collection) state.getAttribute(STATE_PARTICIPANT_LIST);
size = (l != null) ? l.size() : 0;
}
return size;
} // sizeResources
/**
* {@inheritDoc}
*/
protected List readResourcesPage(SessionState state, int first, int last) {
String search = StringUtil.trimToNull((String) state
.getAttribute(STATE_SEARCH));
// if called from the site list page
if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) {
// get sort type
SortType sortType = null;
String sortBy = (String) state.getAttribute(SORTED_BY);
boolean sortAsc = (new Boolean((String) state
.getAttribute(SORTED_ASC))).booleanValue();
if (sortBy.equals(SortType.TITLE_ASC.toString())) {
sortType = sortAsc ? SortType.TITLE_ASC : SortType.TITLE_DESC;
} else if (sortBy.equals(SortType.TYPE_ASC.toString())) {
sortType = sortAsc ? SortType.TYPE_ASC : SortType.TYPE_DESC;
} else if (sortBy.equals(SortType.CREATED_BY_ASC.toString())) {
sortType = sortAsc ? SortType.CREATED_BY_ASC
: SortType.CREATED_BY_DESC;
} else if (sortBy.equals(SortType.CREATED_ON_ASC.toString())) {
sortType = sortAsc ? SortType.CREATED_ON_ASC
: SortType.CREATED_ON_DESC;
} else if (sortBy.equals(SortType.PUBLISHED_ASC.toString())) {
sortType = sortAsc ? SortType.PUBLISHED_ASC
: SortType.PUBLISHED_DESC;
}
if (SecurityService.isSuperUser()) {
// admin-type of user
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(rb.getString("java.allmy"))) {
// search for non-user sites, using the
// criteria
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
null, search, null, sortType,
new PagingPosition(first, last));
} else if (view.equalsIgnoreCase(rb.getString("java.my"))) {
// search for a specific user site for
// the particular user id in the
// criteria - exact match only
List rv = new Vector();
try {
Site userSite = SiteService.getSite(SiteService
.getUserSiteId(search));
rv.add(userSite);
} catch (IdUnusedException e) {
}
return rv;
} else if (view.equalsIgnoreCase(rb
.getString("java.gradtools"))) {
// search for gradtools sites
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
state
.getAttribute(GRADTOOLS_SITE_TYPES),
search, null, sortType,
new PagingPosition(first, last));
} else {
// search for a specific site
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ANY,
view, search, null, sortType,
new PagingPosition(first, last));
}
}
} else {
List rv = new Vector();
Site userWorkspaceSite = null;
String userId = SessionManager.getCurrentSessionUserId();
try {
userWorkspaceSite = SiteService.getSite(SiteService
.getUserSiteId(userId));
} catch (IdUnusedException e) {
M_log.warn("Cannot find user "
+ SessionManager.getCurrentSessionUserId()
+ "'s My Workspace site.");
}
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(rb.getString("java.allmy"))) {
view = null;
// add my workspace if any
if (userWorkspaceSite != null) {
if (search != null) {
if (userId.indexOf(search) != -1) {
rv.add(userWorkspaceSite);
}
} else {
rv.add(userWorkspaceSite);
}
}
rv
.addAll(SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
null, search, null, sortType,
new PagingPosition(first, last)));
} else if (view.equalsIgnoreCase(rb
.getString("java.gradtools"))) {
// search for a specific user site for
// the particular user id in the
// criteria - exact match only
rv
.addAll(SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
state
.getAttribute(GRADTOOLS_SITE_TYPES),
search, null, sortType,
new PagingPosition(first, last)));
} else {
rv
.addAll(SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
view, search, null, sortType,
new PagingPosition(first, last)));
}
}
return rv;
}
}
// if in Site Info list view
else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals(
"12")) {
List participants = (state.getAttribute(STATE_PARTICIPANT_LIST) != null) ? collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)): new Vector();
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
Iterator sortedParticipants = null;
if (sortedBy != null) {
sortedParticipants = new SortedIterator(participants
.iterator(), new SiteComparator(sortedBy,
sortedAsc));
participants.clear();
while (sortedParticipants.hasNext()) {
participants.add(sortedParticipants.next());
}
}
PagingPosition page = new PagingPosition(first, last);
page.validate(participants.size());
participants = participants.subList(page.getFirst() - 1, page.getLast());
return participants;
}
return null;
} // readResourcesPage
/**
* get the selected tool ids from import sites
*/
private boolean select_import_tools(ParameterParser params,
SessionState state) {
// has the user selected any tool for importing?
boolean anyToolSelected = false;
Hashtable importTools = new Hashtable();
// the tools for current site
List selectedTools = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // String
// toolId's
for (int i = 0; i < selectedTools.size(); i++) {
// any tools chosen from import sites?
String toolId = (String) selectedTools.get(i);
if (params.getStrings(toolId) != null) {
importTools.put(toolId, new ArrayList(Arrays.asList(params
.getStrings(toolId))));
if (!anyToolSelected) {
anyToolSelected = true;
}
}
}
state.setAttribute(STATE_IMPORT_SITE_TOOL, importTools);
return anyToolSelected;
} // select_import_tools
/**
* Is it from the ENW edit page?
*
* @return ture if the process went through the ENW page; false, otherwise
*/
private boolean fromENWModifyView(SessionState state) {
boolean fromENW = false;
List oTools = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
List toolList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
for (int i = 0; i < toolList.size() && !fromENW; i++) {
String toolId = (String) toolList.get(i);
if (toolId.equals("sakai.mailbox")
|| isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) {
if (oTools == null) {
// if during site creation proces
fromENW = true;
} else if (!oTools.contains(toolId)) {
// if user is adding either EmailArchive tool, News tool or
// Web Content tool, go to the Customize page for the tool
fromENW = true;
}
}
}
return fromENW;
}
/**
* doNew_site is called when the Site list tool bar New... button is clicked
*
*/
public void doNew_site(RunData data) throws Exception {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// start clean
cleanState(state);
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes != null) {
if (siteTypes.size() == 1) {
String siteType = (String) siteTypes.get(0);
if (!siteType.equals(ServerConfigurationService.getString(
"courseSiteType", (String) state.getAttribute(STATE_COURSE_SITE_TYPE)))) {
// if only one site type is allowed and the type isn't
// course type
// skip the select site type step
setNewSiteType(state, siteType);
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
}
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
}
}
} // doNew_site
/**
* doMenu_site_delete is called when the Site list tool bar Delete button is
* clicked
*
*/
public void doMenu_site_delete(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (params.getStrings("selectedMembers") == null) {
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
String[] removals = (String[]) params.getStrings("selectedMembers");
state.setAttribute(STATE_SITE_REMOVALS, removals);
// present confirm delete template
state.setAttribute(STATE_TEMPLATE_INDEX, "8");
} // doMenu_site_delete
public void doSite_delete_confirmed(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (params.getStrings("selectedMembers") == null) {
M_log
.warn("SiteAction.doSite_delete_confirmed selectedMembers null");
state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the
// site list
return;
}
List chosenList = new ArrayList(Arrays.asList(params
.getStrings("selectedMembers"))); // Site id's of checked
// sites
if (!chosenList.isEmpty()) {
for (ListIterator i = chosenList.listIterator(); i.hasNext();) {
String id = (String) i.next();
String site_title = NULL_STRING;
try {
site_title = SiteService.getSite(id).getTitle();
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.doSite_delete_confirmed - IdUnusedException "
+ id);
addAlert(state, rb.getString("java.sitewith") + " " + id
+ " " + rb.getString("java.couldnt") + " ");
}
if (SiteService.allowRemoveSite(id)) {
try {
Site site = SiteService.getSite(id);
site_title = site.getTitle();
SiteService.removeSite(site);
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.doSite_delete_confirmed - IdUnusedException "
+ id);
addAlert(state, rb.getString("java.sitewith") + " "
+ site_title + "(" + id + ") "
+ rb.getString("java.couldnt") + " ");
} catch (PermissionException e) {
M_log
.warn("SiteAction.doSite_delete_confirmed - PermissionException, site "
+ site_title + "(" + id + ").");
addAlert(state, site_title + " "
+ rb.getString("java.dontperm") + " ");
}
} else {
M_log
.warn("SiteAction.doSite_delete_confirmed - allowRemoveSite failed for site "
+ id);
addAlert(state, site_title + " "
+ rb.getString("java.dontperm") + " ");
}
}
}
state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the site
// list
// TODO: hard coding this frame id is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
} // doSite_delete_confirmed
/**
* get the Site object based on SessionState attribute values
*
* @return Site object related to current state; null if no such Site object
* could be found
*/
protected Site getStateSite(SessionState state) {
Site site = null;
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) {
try {
site = SiteService.getSite((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
} catch (Exception ignore) {
}
}
return site;
} // getStateSite
/**
* get the Group object based on SessionState attribute values
*
* @return Group object related to current state; null if no such Group
* object could be found
*/
protected Group getStateGroup(SessionState state) {
Group group = null;
Site site = getStateSite(state);
if (site != null && state.getAttribute(STATE_GROUP_INSTANCE_ID) != null) {
try {
group = site.getGroup((String) state
.getAttribute(STATE_GROUP_INSTANCE_ID));
} catch (Exception ignore) {
}
}
return group;
} // getStateGroup
/**
* do called when "eventSubmit_do" is in the request parameters to c is
* called from site list menu entry Revise... to get a locked site as
* editable and to go to the correct template to begin DB version of writes
* changes to disk at site commit whereas XML version writes at server
* shutdown
*/
public void doGet_site(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// check form filled out correctly
if (params.getStrings("selectedMembers") == null) {
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
List chosenList = new ArrayList(Arrays.asList(params
.getStrings("selectedMembers"))); // Site id's of checked
// sites
String siteId = "";
if (!chosenList.isEmpty()) {
if (chosenList.size() != 1) {
addAlert(state, rb.getString("java.please"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
siteId = (String) chosenList.get(0);
getReviseSite(state, siteId);
state.setAttribute(SORTED_BY, SORTED_BY_PARTICIPANT_NAME);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
}
// reset the paging info
resetPaging(state);
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
state.setAttribute(STATE_PAGESIZE_SITESETUP, state
.getAttribute(STATE_PAGESIZE));
}
Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO);
if (!h.containsKey(siteId)) {
// when first entered Site Info, set the participant list size to
// 200 as default
state.setAttribute(STATE_PAGESIZE, new Integer(200));
// update
h.put(siteId, new Integer(200));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
} else {
// restore the page size in site info tool
state.setAttribute(STATE_PAGESIZE, h.get(siteId));
}
} // doGet_site
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doMenu_site_reuse(RunData data) throws Exception {
// called from chef_site-list.vm after a site has been selected from
// list
// create a new Site object based on selected Site object and put in
// state
//
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} // doMenu_site_reuse
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doMenu_site_revise(RunData data) throws Exception {
// called from chef_site-list.vm after a site has been selected from
// list
// get site as Site object, check SiteCreationStatus and SiteType of
// site, put in state, and set STATE_TEMPLATE_INDEX correctly
// set mode to state_mode_site_type
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} // doMenu_site_revise
/**
* doView_sites is called when "eventSubmit_doView_sites" is in the request
* parameters
*/
public void doView_sites(RunData data) throws Exception {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(STATE_VIEW_SELECTED, params.getString("view"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
resetPaging(state);
} // doView_sites
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doView(RunData data) throws Exception {
// called from chef_site-list.vm with a select option to build query of
// sites
//
//
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} // doView
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doSite_type(RunData data) {
/*
* for measuring how long it takes to load sections java.util.Date date =
* new java.util.Date(); M_log.debug("***1. start preparing
* section:"+date);
*/
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
int index = Integer.valueOf(params.getString("template-index"))
.intValue();
actionForTemplate("continue", index, params, state);
String type = StringUtil.trimToNull(params.getString("itemType"));
int totalSteps = 0;
if (type == null) {
addAlert(state, rb.getString("java.select") + " ");
} else {
setNewSiteType(state, type);
if (type.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
User user = UserDirectoryService.getCurrentUser();
String currentUserId = user.getEid();
String userId = params.getString("userId");
if (userId == null || "".equals(userId)) {
userId = currentUserId;
} else {
// implies we are trying to pick sections owned by other
// users. Currently "select section by user" page only
// take one user per sitte request - daisy's note 1
ArrayList<String> list = new ArrayList();
list.add(userId);
state.setAttribute(STATE_CM_AUTHORIZER_LIST, list);
}
state.setAttribute(STATE_INSTRUCTOR_SELECTED, userId);
String academicSessionEid = params.getString("selectTerm");
AcademicSession t = cms.getAcademicSession(academicSessionEid);
state.setAttribute(STATE_TERM_SELECTED, t);
if (t != null) {
List sections = prepareCourseAndSectionListing(userId, t
.getEid(), state);
isFutureTermSelected(state);
if (sections != null && sections.size() > 0) {
state.setAttribute(STATE_TERM_COURSE_LIST, sections);
state.setAttribute(STATE_TEMPLATE_INDEX, "36");
state.setAttribute(STATE_AUTO_ADD, Boolean.TRUE);
} else {
state.removeAttribute(STATE_TERM_COURSE_LIST);
Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean("wsetup.skipCourseSectionSelection", Boolean.FALSE);
if (!skipCourseSectionSelection.booleanValue() && courseManagementIsImplemented())
{
state.setAttribute(STATE_TEMPLATE_INDEX, "53");
}
else
{
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
}
}
} else { // not course type
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
totalSteps = 5;
}
} else if (type.equals("project")) {
totalSteps = 4;
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
} else if (type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) {
// if a GradTools site use pre-defined site info and exclude
// from public listing
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
User currentUser = UserDirectoryService.getCurrentUser();
siteInfo.title = rb.getString("java.grad") + " - "
+ currentUser.getId();
siteInfo.description = rb.getString("java.gradsite") + " "
+ currentUser.getDisplayName();
siteInfo.short_description = rb.getString("java.grad") + " - "
+ currentUser.getId();
siteInfo.include = false;
state.setAttribute(STATE_SITE_INFO, siteInfo);
// skip directly to confirm creation of site
state.setAttribute(STATE_TEMPLATE_INDEX, "42");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
}
}
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) == null) {
state
.setAttribute(SITE_CREATE_TOTAL_STEPS, new Integer(
totalSteps));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) == null) {
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(1));
}
} // doSite_type
/**
* Determine whether the selected term is considered of "future term"
* @param state
* @param t
*/
private void isFutureTermSelected(SessionState state) {
AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
int weeks = 0;
Calendar c = (Calendar) Calendar.getInstance().clone();
try {
weeks = Integer
.parseInt(ServerConfigurationService
.getString(
"roster.available.weeks.before.term.start",
"0"));
c.add(Calendar.DATE, weeks * 7);
} catch (Exception ignore) {
}
if (t.getStartDate() != null && c.getTimeInMillis() < t.getStartDate().getTime()) {
// if a future term is selected
state.setAttribute(STATE_FUTURE_TERM_SELECTED,
Boolean.TRUE);
} else {
state.setAttribute(STATE_FUTURE_TERM_SELECTED,
Boolean.FALSE);
}
}
public void doChange_user(RunData data) {
doSite_type(data);
} // doChange_user
/**
* cleanEditGroupParams clean the state parameters used by editing group
* process
*
*/
public void cleanEditGroupParams(SessionState state) {
state.removeAttribute(STATE_GROUP_INSTANCE_ID);
state.removeAttribute(STATE_GROUP_TITLE);
state.removeAttribute(STATE_GROUP_DESCRIPTION);
state.removeAttribute(STATE_GROUP_MEMBERS);
state.removeAttribute(STATE_GROUP_REMOVE);
} // cleanEditGroupParams
/**
* doGroup_edit
*
*/
public void doGroup_update(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
Set gMemberSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
Site site = getStateSite(state);
String title = StringUtil.trimToNull(params.getString(rb
.getString("group.title")));
state.setAttribute(STATE_GROUP_TITLE, title);
String description = StringUtil.trimToZero(params.getString(rb
.getString("group.description")));
state.setAttribute(STATE_GROUP_DESCRIPTION, description);
boolean found = false;
String option = params.getString("option");
if (option.equals("add")) {
// add selected members into it
if (params.getStrings("generallist") != null) {
List addMemberIds = new ArrayList(Arrays.asList(params
.getStrings("generallist")));
for (int i = 0; i < addMemberIds.size(); i++) {
String aId = (String) addMemberIds.get(i);
found = false;
for (Iterator iSet = gMemberSet.iterator(); !found
&& iSet.hasNext();) {
if (((Member) iSet.next()).getUserEid().equals(aId)) {
found = true;
}
}
if (!found) {
try {
User u = UserDirectoryService.getUser(aId);
gMemberSet.add(site.getMember(u.getId()));
} catch (UserNotDefinedException e) {
try {
User u2 = UserDirectoryService
.getUserByEid(aId);
gMemberSet.add(site.getMember(u2.getId()));
} catch (UserNotDefinedException ee) {
M_log.warn(this + ee.getMessage() + aId);
}
}
}
}
}
state.setAttribute(STATE_GROUP_MEMBERS, gMemberSet);
} else if (option.equals("remove")) {
// update the group member list by remove selected members from it
if (params.getStrings("grouplist") != null) {
List removeMemberIds = new ArrayList(Arrays.asList(params
.getStrings("grouplist")));
for (int i = 0; i < removeMemberIds.size(); i++) {
found = false;
for (Iterator iSet = gMemberSet.iterator(); !found
&& iSet.hasNext();) {
Member mSet = (Member) iSet.next();
if (mSet.getUserId().equals(
(String) removeMemberIds.get(i))) {
found = true;
gMemberSet.remove(mSet);
}
}
}
}
state.setAttribute(STATE_GROUP_MEMBERS, gMemberSet);
} else if (option.equals("cancel")) {
// cancel from the update the group member process
doCancel(data);
cleanEditGroupParams(state);
} else if (option.equals("save")) {
Group group = null;
if (site != null
&& state.getAttribute(STATE_GROUP_INSTANCE_ID) != null) {
try {
group = site.getGroup((String) state
.getAttribute(STATE_GROUP_INSTANCE_ID));
} catch (Exception ignore) {
}
}
if (title == null) {
addAlert(state, rb.getString("editgroup.titlemissing"));
} else {
if (group == null) {
// when adding a group, check whether the group title has
// been used already
boolean titleExist = false;
for (Iterator iGroups = site.getGroups().iterator(); !titleExist
&& iGroups.hasNext();) {
Group iGroup = (Group) iGroups.next();
if (iGroup.getTitle().equals(title)) {
// found same title
titleExist = true;
}
}
if (titleExist) {
addAlert(state, rb.getString("group.title.same"));
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
if (group == null) {
// adding new group
group = site.addGroup();
group.getProperties().addProperty(
GROUP_PROP_WSETUP_CREATED, Boolean.TRUE.toString());
}
if (group != null) {
group.setTitle(title);
group.setDescription(description);
// save the modification to group members
// remove those no longer included in the group
Set members = group.getMembers();
for (Iterator iMembers = members.iterator(); iMembers
.hasNext();) {
found = false;
String mId = ((Member) iMembers.next()).getUserId();
for (Iterator iMemberSet = gMemberSet.iterator(); !found
&& iMemberSet.hasNext();) {
if (mId.equals(((Member) iMemberSet.next())
.getUserId())) {
found = true;
}
}
if (!found) {
group.removeMember(mId);
}
}
// add those seleted members
for (Iterator iMemberSet = gMemberSet.iterator(); iMemberSet
.hasNext();) {
String memberId = ((Member) iMemberSet.next())
.getUserId();
if (group.getUserRole(memberId) == null) {
Role r = site.getUserRole(memberId);
Member m = site.getMember(memberId);
// for every member added through the "Manage
// Groups" interface, he should be defined as
// non-provided
group.addMember(memberId, r != null ? r.getId()
: "", m != null ? m.isActive() : true,
false);
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
try {
SiteService.save(site);
} catch (IdUnusedException e) {
} catch (PermissionException e) {
}
// return to group list view
state.setAttribute(STATE_TEMPLATE_INDEX, "49");
cleanEditGroupParams(state);
}
}
}
}
} // doGroup_updatemembers
/**
* doGroup_new
*
*/
public void doGroup_new(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (state.getAttribute(STATE_GROUP_TITLE) == null) {
state.setAttribute(STATE_GROUP_TITLE, "");
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) == null) {
state.setAttribute(STATE_GROUP_DESCRIPTION, "");
}
if (state.getAttribute(STATE_GROUP_MEMBERS) == null) {
state.setAttribute(STATE_GROUP_MEMBERS, new HashSet());
}
state.setAttribute(STATE_TEMPLATE_INDEX, "50");
} // doGroup_new
/**
* doGroup_edit
*
*/
public void doGroup_edit(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String groupId = data.getParameters().getString("groupId");
state.setAttribute(STATE_GROUP_INSTANCE_ID, groupId);
Site site = getStateSite(state);
if (site != null) {
Group g = site.getGroup(groupId);
if (g != null) {
if (state.getAttribute(STATE_GROUP_TITLE) == null) {
state.setAttribute(STATE_GROUP_TITLE, g.getTitle());
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) == null) {
state.setAttribute(STATE_GROUP_DESCRIPTION, g
.getDescription());
}
if (state.getAttribute(STATE_GROUP_MEMBERS) == null) {
// double check the member existance
Set gMemberSet = g.getMembers();
Set rvGMemberSet = new HashSet();
for (Iterator iSet = gMemberSet.iterator(); iSet.hasNext();) {
Member member = (Member) iSet.next();
try {
UserDirectoryService.getUser(member.getUserId());
((Set) rvGMemberSet).add(member);
} catch (UserNotDefinedException e) {
// cannot find user
M_log.warn(this + rb.getString("user.notdefined")
+ member.getUserId());
}
}
state.setAttribute(STATE_GROUP_MEMBERS, rvGMemberSet);
}
}
}
state.setAttribute(STATE_TEMPLATE_INDEX, "50");
} // doGroup_edit
/**
* doGroup_remove_prep Go to confirmation page before deleting group(s)
*
*/
public void doGroup_remove_prep(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String[] removeGroupIds = data.getParameters().getStrings(
"removeGroups");
if (removeGroupIds.length > 0) {
state.setAttribute(STATE_GROUP_REMOVE, removeGroupIds);
state.setAttribute(STATE_TEMPLATE_INDEX, "51");
}
} // doGroup_remove_prep
/**
* doGroup_remove_confirmed Delete selected groups after confirmation
*
*/
public void doGroup_remove_confirmed(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String[] removeGroupIds = (String[]) state
.getAttribute(STATE_GROUP_REMOVE);
Site site = getStateSite(state);
for (int i = 0; i < removeGroupIds.length; i++) {
if (site != null) {
Group g = site.getGroup(removeGroupIds[i]);
if (g != null) {
site.removeGroup(g);
}
}
}
try {
SiteService.save(site);
} catch (IdUnusedException e) {
addAlert(state, rb.getString("editgroup.site.notfound.alert"));
} catch (PermissionException e) {
addAlert(state, rb.getString("editgroup.site.permission.alert"));
}
if (state.getAttribute(STATE_MESSAGE) == null) {
cleanEditGroupParams(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "49");
}
} // doGroup_remove_confirmed
/**
* doMenu_edit_site_info The menu choice to enter group view
*
*/
public void doMenu_group(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset sort criteria
state.setAttribute(SORTED_BY, rb.getString("group.title"));
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
state.setAttribute(STATE_TEMPLATE_INDEX, "49");
} // doMenu_group
/**
*
*/
private void removeSection(SessionState state, ParameterParser params)
{
// v2.4 - added by daisyf
// RemoveSection - remove any selected course from a list of
// provider courses
// check if any section need to be removed
removeAnyFlagedSection(state, params);
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
List providerChosenList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
collectNewSiteInfo(siteInfo, state, params, providerChosenList);
// next step
//state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2));
}
/**
* dispatch to different functions based on the option value in the
* parameter
*/
public void doManual_add_course(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
if (option.equalsIgnoreCase("change") || option.equalsIgnoreCase("add")) {
readCourseSectionInfo(state, params);
String uniqname = StringUtil.trimToNull(params
.getString("uniqname"));
state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname);
updateSiteInfo(params, state);
if (option.equalsIgnoreCase("add")) {
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& !((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue()) {
// if a future term is selected, do not check authorization
// uniqname
if (uniqname == null) {
addAlert(state, rb.getString("java.author")
+ " "
+ ServerConfigurationService
.getString("officialAccountName")
+ ". ");
} else {
// in case of multiple instructors
List instructors = new ArrayList(Arrays.asList(uniqname.split(",")));
for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();)
{
try {
UserDirectoryService.getUserByEid(StringUtil.trimToZero((String) iInstructors.next()));
} catch (UserNotDefinedException e) {
addAlert(
state,
rb.getString("java.validAuthor1")
+ " "
+ ServerConfigurationService
.getString("officialAccountName")
+ " "
+ rb.getString("java.validAuthor2"));
}
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
if (getStateSite(state) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
}
}
updateCurrentStep(state, true);
}
} else if (option.equalsIgnoreCase("back")) {
doBack(data);
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, false);
}
} else if (option.equalsIgnoreCase("cancel")) {
if (getStateSite(state) == null) {
doCancel_create(data);
} else {
doCancel(data);
}
} else if (option.equalsIgnoreCase("removeSection"))
{
// remove selected section
removeSection(state, params);
}
} // doManual_add_course
/**
* dispatch to different functions based on the option value in the
* parameter
*/
public void doSite_information(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
if (option.equalsIgnoreCase("continue"))
{
doContinue(data);
} else if (option.equalsIgnoreCase("back")) {
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
if (getStateSite(state) == null) {
doCancel_create(data);
} else {
doCancel(data);
}
} else if (option.equalsIgnoreCase("removeSection"))
{
// remove selected section
removeSection(state, params);
}
} // doSite_information
/**
* read the input information of subject, course and section in the manual
* site creation page
*/
private void readCourseSectionInfo(SessionState state,
ParameterParser params) {
String option = params.getString("option");
int oldNumber = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
oldNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
}
// read the user input
int validInputSites = 0;
boolean validInput = true;
List multiCourseInputs = new Vector();
for (int i = 0; i < oldNumber; i++) {
List requiredFields = sectionFieldProvider.getRequiredFields();
List aCourseInputs = new Vector();
int emptyInputNum = 0;
// iterate through all required fields
for (int k = 0; k < requiredFields.size(); k++) {
SectionField sectionField = (SectionField) requiredFields
.get(k);
String fieldLabel = sectionField.getLabelKey();
String fieldInput = StringUtil.trimToZero(params
.getString(fieldLabel + i));
sectionField.setValue(fieldInput);
aCourseInputs.add(sectionField);
if (fieldInput.length() == 0) {
// is this an empty String input?
emptyInputNum++;
}
}
// is any input invalid?
if (emptyInputNum == 0) {
// valid if all the inputs are not empty
multiCourseInputs.add(validInputSites++, aCourseInputs);
} else if (emptyInputNum == requiredFields.size()) {
// ignore if all inputs are empty
if (option.equalsIgnoreCase("change"))
{
multiCourseInputs.add(validInputSites++, aCourseInputs);
}
} else {
// input invalid
validInput = false;
}
}
// how many more course/section to include in the site?
if (option.equalsIgnoreCase("change")) {
if (params.getString("number") != null) {
int newNumber = Integer.parseInt(params.getString("number"));
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(oldNumber + newNumber));
List requiredFields = sectionFieldProvider.getRequiredFields();
for (int j = 0; j < newNumber; j++) {
// add a new course input
List aCourseInputs = new Vector();
// iterate through all required fields
for (int m = 0; m < requiredFields.size(); m++) {
aCourseInputs = sectionFieldProvider.getRequiredFields();
}
multiCourseInputs.add(aCourseInputs);
}
}
}
state.setAttribute(STATE_MANUAL_ADD_COURSE_FIELDS, multiCourseInputs);
if (!option.equalsIgnoreCase("change")) {
if (!validInput || validInputSites == 0) {
// not valid input
addAlert(state, rb.getString("java.miss"));
}
// valid input, adjust the add course number
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer( validInputSites));
}
// set state attributes
state.setAttribute(FORM_ADDITIONAL, StringUtil.trimToZero(params
.getString("additional")));
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
List providerCourseList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
// store the manually requested sections in one site property
if ((providerCourseList == null || providerCourseList.size() == 0)
&& multiCourseInputs.size() > 0) {
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
String sectionEid = sectionFieldProvider.getSectionEid(t.getEid(),
(List) multiCourseInputs.get(0));
// default title
String title = sectionEid;
try {
title = cms.getSection(sectionEid).getTitle();
} catch (Exception e) {
// ignore
}
siteInfo.title = title;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
} // readCourseSectionInfo
/**
* set the site type for new site
*
* @param type
* The type String
*/
private void setNewSiteType(SessionState state, String type) {
state.setAttribute(STATE_SITE_TYPE, type);
// start out with fresh site information
SiteInfo siteInfo = new SiteInfo();
siteInfo.site_type = type;
siteInfo.published = true;
state.setAttribute(STATE_SITE_INFO, siteInfo);
// set tool registration list
setToolRegistrationList(state, type);
}
/**
* Set the state variables for tool registration list basd on site type
* @param state
* @param type
*/
private void setToolRegistrationList(SessionState state, String type) {
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET);
// get the tool id set which allows for multiple instances
Set multipleToolIdSet = new HashSet();
// get registered tools list
Set categories = new HashSet();
categories.add(type);
Set toolRegistrations = ToolManager.findTools(categories, null);
if ((toolRegistrations == null || toolRegistrations.size() == 0)
&& state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null)
{
// use default site type and try getting tools again
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
categories.clear();
categories.add(type);
toolRegistrations = ToolManager.findTools(categories, null);
}
List tools = new Vector();
SortedIterator i = new SortedIterator(toolRegistrations.iterator(),
new ToolComparator());
for (; i.hasNext();) {
// form a new Tool
Tool tr = (Tool) i.next();
MyTool newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = tr.getId();
newTool.description = tr.getDescription();
tools.add(newTool);
if (isMultipleInstancesAllowed(findOriginalToolId(state, tr.getId())))
{
// of a tool which allows multiple instances
multipleToolIdSet.add(tr.getId());
}
}
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, tools);
state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet);
}
/**
* Set the field on which to sort the list of students
*
*/
public void doSort_roster(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the field on which to sort the student list
ParameterParser params = data.getParameters();
String criterion = params.getString("criterion");
// current sorting sequence
String asc = "";
if (!criterion.equals(state.getAttribute(SORTED_BY))) {
state.setAttribute(SORTED_BY, criterion);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, asc);
} else {
// current sorting sequence
asc = (String) state.getAttribute(SORTED_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString())) {
asc = Boolean.FALSE.toString();
} else {
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_ASC, asc);
}
} // doSort_roster
/**
* Set the field on which to sort the list of sites
*
*/
public void doSort_sites(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// call this method at the start of a sort for proper paging
resetPaging(state);
// get the field on which to sort the site list
ParameterParser params = data.getParameters();
String criterion = params.getString("criterion");
// current sorting sequence
String asc = "";
if (!criterion.equals(state.getAttribute(SORTED_BY))) {
state.setAttribute(SORTED_BY, criterion);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, asc);
} else {
// current sorting sequence
asc = (String) state.getAttribute(SORTED_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString())) {
asc = Boolean.FALSE.toString();
} else {
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_ASC, asc);
}
state.setAttribute(SORTED_BY, criterion);
} // doSort_sites
/**
* doContinue is called when "eventSubmit_doContinue" is in the request
* parameters
*/
public void doContinue(RunData data) {
// Put current form data in state and continue to the next template,
// make any permanent changes
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
int index = Integer.valueOf(params.getString("template-index"))
.intValue();
// Let actionForTemplate know to make any permanent changes before
// continuing to the next template
String direction = "continue";
String option = params.getString("option");
actionForTemplate(direction, index, params, state);
if (state.getAttribute(STATE_MESSAGE) == null) {
if (index == 36 && ("add").equals(option)) {
// this is the Add extra Roster(s) case after a site is created
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
} else if (params.getString("continue") != null) {
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("continue"));
}
}
}// doContinue
/**
* handle with continue add new course site options
*
*/
public void doContinue_new_course(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = data.getParameters().getString("option");
if (option.equals("continue")) {
doContinue(data);
} else if (option.equals("cancel")) {
doCancel_create(data);
} else if (option.equals("back")) {
doBack(data);
} else if (option.equals("cancel")) {
doCancel_create(data);
}
else if (option.equalsIgnoreCase("change")) {
// change term
String termId = params.getString("selectTerm");
AcademicSession t = cms.getAcademicSession(termId);
state.setAttribute(STATE_TERM_SELECTED, t);
isFutureTermSelected(state);
} else if (option.equalsIgnoreCase("cancel_edit")) {
// cancel
doCancel(data);
} else if (option.equalsIgnoreCase("add")) {
isFutureTermSelected(state);
// continue
doContinue(data);
}
} // doContinue_new_course
/**
* doBack is called when "eventSubmit_doBack" is in the request parameters
* Pass parameter to actionForTemplate to request action for backward
* direction
*/
public void doBack(RunData data) {
// Put current form data in state and return to the previous template
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
int currentIndex = Integer.parseInt((String) state
.getAttribute(STATE_TEMPLATE_INDEX));
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("back"));
// Let actionForTemplate know not to make any permanent changes before
// continuing to the next template
String direction = "back";
actionForTemplate(direction, currentIndex, params, state);
}// doBack
/**
* doFinish is called when a site has enough information to be saved as an
* unpublished site
*/
public void doFinish(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("continue"));
int index = Integer.valueOf(params.getString("template-index"))
.intValue();
actionForTemplate("continue", index, params, state);
addNewSite(params, state);
addFeatures(state);
Site site = getStateSite(state);
// for course sites
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
String siteId = site.getId();
ResourcePropertiesEdit rp = site.getPropertiesEdit();
AcademicSession term = null;
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
term = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
rp.addProperty(PROP_SITE_TERM, term.getTitle());
rp.addProperty(PROP_SITE_TERM_EID, term.getEid());
}
// update the site and related realm based on the rosters chosen or requested
updateCourseSiteSections(state, siteId, rp, term);
}
// commit site
commitSite(site);
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
// now that the site exists, we can set the email alias when an
// Email Archive tool has been selected
String alias = StringUtil.trimToNull((String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
if (alias != null) {
String channelReference = mailArchiveChannelReference(siteId);
try {
AliasService.setAlias(alias, channelReference);
} catch (IdUsedException ee) {
addAlert(state, rb.getString("java.alias") + " " + alias
+ " " + rb.getString("java.exists"));
} catch (IdInvalidException ee) {
addAlert(state, rb.getString("java.alias") + " " + alias
+ " " + rb.getString("java.isinval"));
} catch (PermissionException ee) {
addAlert(state, rb.getString("java.addalias") + " ");
}
}
// TODO: hard coding this frame id is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
resetPaging(state);
// clean state variables
cleanState(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
}// doFinish
/**
* Update course site and related realm based on the roster chosen or requested
* @param state
* @param siteId
* @param rp
* @param term
*/
private void updateCourseSiteSections(SessionState state, String siteId, ResourcePropertiesEdit rp, AcademicSession term) {
// whether this is in the process of editing a site?
boolean editingSite = ((String)state.getAttribute(STATE_SITE_MODE)).equals(SITE_MODE_SITEINFO)?true:false;
List providerCourseList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
int manualAddNumber = 0;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
manualAddNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
}
List<SectionObject> cmRequestedSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
List<SectionObject> cmAuthorizerSections = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
String realm = SiteService.siteReference(siteId);
if ((providerCourseList != null)
&& (providerCourseList.size() != 0)) {
try {
AuthzGroup realmEdit = AuthzGroupService
.getAuthzGroup(realm);
String providerRealm = buildExternalRealm(siteId, state,
providerCourseList, StringUtil.trimToNull(realmEdit.getProviderGroupId()));
realmEdit.setProviderGroupId(providerRealm);
AuthzGroupService.save(realmEdit);
} catch (GroupNotDefinedException e) {
M_log.warn(this + " IdUnusedException, not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.realm"));
}
// catch (AuthzPermissionException e)
// {
// M_log.warn(this + " PermissionException, user does not
// have permission to edit AuthzGroup object.");
// addAlert(state, rb.getString("java.notaccess"));
// return;
// }
catch (Exception e) {
addAlert(state, this + rb.getString("java.problem"));
}
sendSiteNotification(state, providerCourseList);
}
if (manualAddNumber != 0) {
// set the manual sections to the site property
String manualSections = rp.getProperty(PROP_SITE_REQUEST_COURSE) != null?rp.getProperty(PROP_SITE_REQUEST_COURSE)+"+":"";
// manualCourseInputs is a list of a list of SectionField
List manualCourseInputs = (List) state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
// but we want to feed a list of a list of String (input of
// the required fields)
for (int j = 0; j < manualAddNumber; j++) {
manualSections = manualSections.concat(
sectionFieldProvider.getSectionEid(
term.getEid(),
(List) manualCourseInputs.get(j)))
.concat("+");
}
// trim the trailing plus sign
manualSections = trimTrailingString(manualSections, "+");
rp.addProperty(PROP_SITE_REQUEST_COURSE, manualSections);
// send request
sendSiteRequest(state, "new", manualAddNumber, manualCourseInputs, "manual");
}
if (cmRequestedSections != null
&& cmRequestedSections.size() > 0 || state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) {
// set the cmRequest sections to the site property
String cmRequestedSectionString = "";
if (!editingSite)
{
// but we want to feed a list of a list of String (input of
// the required fields)
for (int j = 0; j < cmRequestedSections.size(); j++) {
cmRequestedSectionString = cmRequestedSectionString.concat(( cmRequestedSections.get(j)).eid).concat("+");
}
// trim the trailing plus sign
cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+");
sendSiteRequest(state, "new", cmRequestedSections.size(), cmRequestedSections, "cmRequest");
}
else
{
cmRequestedSectionString = rp.getProperty(STATE_CM_REQUESTED_SECTIONS) != null ? (String) rp.getProperty(STATE_CM_REQUESTED_SECTIONS):"";
// get the selected cm section
if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null )
{
List<SectionObject> cmSelectedSections = (List) state.getAttribute(STATE_CM_SELECTED_SECTIONS);
if (cmRequestedSectionString.length() != 0)
{
cmRequestedSectionString = cmRequestedSectionString.concat("+");
}
for (int j = 0; j < cmSelectedSections.size(); j++) {
cmRequestedSectionString = cmRequestedSectionString.concat(( cmSelectedSections.get(j)).eid).concat("+");
}
// trim the trailing plus sign
cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+");
sendSiteRequest(state, "new", cmSelectedSections.size(), cmSelectedSections, "cmRequest");
}
}
// update site property
if (cmRequestedSectionString.length() > 0)
{
rp.addProperty(STATE_CM_REQUESTED_SECTIONS, cmRequestedSectionString);
}
else
{
rp.removeProperty(STATE_CM_REQUESTED_SECTIONS);
}
}
}
/**
* Trim the trailing occurance of specified string
* @param cmRequestedSectionString
* @param trailingString
* @return
*/
private String trimTrailingString(String cmRequestedSectionString, String trailingString) {
if (cmRequestedSectionString.endsWith(trailingString)) {
cmRequestedSectionString = cmRequestedSectionString.substring(0, cmRequestedSectionString.lastIndexOf(trailingString));
}
return cmRequestedSectionString;
}
/**
* buildExternalRealm creates a site/realm id in one of three formats, for a
* single section, for multiple sections of the same course, or for a
* cross-listing having multiple courses
*
* @param sectionList
* is a Vector of CourseListItem
* @param id
* The site id
*/
private String buildExternalRealm(String id, SessionState state,
List<String> providerIdList, String existingProviderIdString) {
String realm = SiteService.siteReference(id);
if (!AuthzGroupService.allowUpdate(realm)) {
addAlert(state, rb.getString("java.rosters"));
return null;
}
List<String> allProviderIdList = new Vector<String>();
// see if we need to keep existing provider settings
if (existingProviderIdString != null)
{
allProviderIdList.addAll(Arrays.asList(groupProvider.unpackId(existingProviderIdString)));
}
// update the list with newly added providers
allProviderIdList.addAll(providerIdList);
if (allProviderIdList == null || allProviderIdList.size() == 0)
return null;
String[] providers = new String[allProviderIdList.size()];
providers = (String[]) allProviderIdList.toArray(providers);
String providerId = groupProvider.packId(providers);
return providerId;
} // buildExternalRealm
/**
* Notification sent when a course site needs to be set up by Support
*
*/
private void sendSiteRequest(SessionState state, String request,
int requestListSize, List requestFields, String fromContext) {
User cUser = UserDirectoryService.getCurrentUser();
String sendEmailToRequestee = null;
StringBuilder buf = new StringBuilder();
// get the request email from configuration
String requestEmail = getSetupRequestEmailAddress();
if (requestEmail != null) {
String officialAccountName = ServerConfigurationService
.getString("officialAccountName", "");
SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
Site site = getStateSite(state);
String id = site.getId();
String title = site.getTitle();
Time time = TimeService.newTime();
String local_time = time.toStringLocalTime();
String local_date = time.toStringLocalDate();
AcademicSession term = null;
boolean termExist = false;
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
termExist = true;
term = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
}
String productionSiteName = ServerConfigurationService
.getServerName();
String from = NULL_STRING;
String to = NULL_STRING;
String headerTo = NULL_STRING;
String replyTo = NULL_STRING;
String message_subject = NULL_STRING;
String content = NULL_STRING;
String sessionUserName = cUser.getDisplayName();
String additional = NULL_STRING;
if (request.equals("new")) {
additional = siteInfo.getAdditional();
} else {
additional = (String) state.getAttribute(FORM_ADDITIONAL);
}
boolean isFutureTerm = false;
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& ((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue()) {
isFutureTerm = true;
}
// message subject
if (termExist) {
message_subject = rb.getString("java.sitereqfrom") + " "
+ sessionUserName + " " + rb.getString("java.for")
+ " " + term.getEid();
} else {
message_subject = rb.getString("java.official") + " "
+ sessionUserName;
}
// there is no offical instructor for future term sites
String requestId = (String) state
.getAttribute(STATE_SITE_QUEST_UNIQNAME);
if (!isFutureTerm) {
// To site quest account - the instructor of record's
if (requestId != null) {
// in case of multiple instructors
List instructors = new ArrayList(Arrays.asList(requestId.split(",")));
for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();)
{
String instructorId = (String) iInstructors.next();
try {
User instructor = UserDirectoryService.getUserByEid(instructorId);
// reset
buf.setLength(0);
to = instructor.getEmail();
from = requestEmail;
headerTo = to;
replyTo = requestEmail;
buf.append(rb.getString("java.hello") + " \n\n");
buf.append(rb.getString("java.receiv") + " "
+ sessionUserName + ", ");
buf.append(rb.getString("java.who") + "\n");
if (termExist) {
buf.append(term.getTitle());
}
// requested sections
if (fromContext.equals("manual"))
{
addRequestedSectionIntoNotification(state, requestFields, buf);
}
else if (fromContext.equals("cmRequest"))
{
addRequestedCMSectionIntoNotification(state, requestFields, buf);
}
buf.append("\n" + rb.getString("java.sitetitle") + "\t"
+ title + "\n");
buf.append(rb.getString("java.siteid") + "\t" + id);
buf.append("\n\n" + rb.getString("java.according")
+ " " + sessionUserName + " "
+ rb.getString("java.record"));
buf.append(" " + rb.getString("java.canyou") + " "
+ sessionUserName + " "
+ rb.getString("java.assoc") + "\n\n");
buf.append(rb.getString("java.respond") + " "
+ sessionUserName
+ rb.getString("java.appoint") + "\n\n");
buf.append(rb.getString("java.thanks") + "\n");
buf.append(productionSiteName + " "
+ rb.getString("java.support"));
content = buf.toString();
// send the email
EmailService.send(from, to, message_subject, content,
headerTo, replyTo, null);
}
catch (Exception e)
{
sendEmailToRequestee = sendEmailToRequestee == null?instructorId:sendEmailToRequestee.concat(", ").concat(instructorId);
}
}
}
}
// To Support
from = cUser.getEmail();
to = requestEmail;
headerTo = requestEmail;
replyTo = cUser.getEmail();
buf.setLength(0);
buf.append(rb.getString("java.to") + "\t\t" + productionSiteName
+ " " + rb.getString("java.supp") + "\n");
buf.append("\n" + rb.getString("java.from") + "\t"
+ sessionUserName + "\n");
if (request.equals("new")) {
buf.append(rb.getString("java.subj") + "\t"
+ rb.getString("java.sitereq") + "\n");
} else {
buf.append(rb.getString("java.subj") + "\t"
+ rb.getString("java.sitechreq") + "\n");
}
buf.append(rb.getString("java.date") + "\t" + local_date + " "
+ local_time + "\n\n");
if (request.equals("new")) {
buf.append(rb.getString("java.approval") + " "
+ productionSiteName + " "
+ rb.getString("java.coursesite") + " ");
} else {
buf.append(rb.getString("java.approval2") + " "
+ productionSiteName + " "
+ rb.getString("java.coursesite") + " ");
}
if (termExist) {
buf.append(term.getTitle());
}
if (requestListSize > 1) {
buf.append(" " + rb.getString("java.forthese") + " "
+ requestListSize + " " + rb.getString("java.sections")
+ "\n\n");
} else {
buf.append(" " + rb.getString("java.forthis") + "\n\n");
}
// requested sections
if (fromContext.equals("manual"))
{
addRequestedSectionIntoNotification(state, requestFields, buf);
}
else if (fromContext.equals("cmRequest"))
{
addRequestedCMSectionIntoNotification(state, requestFields, buf);
}
buf.append(rb.getString("java.name") + "\t" + sessionUserName
+ " (" + officialAccountName + " " + cUser.getEid()
+ ")\n");
buf.append(rb.getString("java.email") + "\t" + replyTo + "\n\n");
buf.append(rb.getString("java.sitetitle") + "\t" + title + "\n");
buf.append(rb.getString("java.siteid") + "\t" + id + "\n");
buf.append(rb.getString("java.siteinstr") + "\n" + additional
+ "\n\n");
if (!isFutureTerm) {
if (sendEmailToRequestee == null) {
buf.append(rb.getString("java.authoriz") + " " + requestId
+ " " + rb.getString("java.asreq"));
} else {
buf.append(rb.getString("java.thesiteemail") + " "
+ sendEmailToRequestee + " " + rb.getString("java.asreq"));
}
}
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo,
replyTo, null);
// To the Instructor
from = requestEmail;
to = cUser.getEmail();
headerTo = to;
replyTo = to;
buf.setLength(0);
buf.append(rb.getString("java.isbeing") + " ");
buf.append(rb.getString("java.meantime") + "\n\n");
buf.append(rb.getString("java.copy") + "\n\n");
buf.append(content);
buf.append("\n" + rb.getString("java.wish") + " " + requestEmail);
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo,
replyTo, null);
state.setAttribute(REQUEST_SENT, new Boolean(true));
} // if
} // sendSiteRequest
private void addRequestedSectionIntoNotification(SessionState state, List requestFields, StringBuilder buf) {
// what are the required fields shown in the UI
List requiredFields = state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null ?(List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS):new Vector();
for (int i = 0; i < requiredFields.size(); i++) {
List requiredFieldList = (List) requestFields
.get(i);
for (int j = 0; j < requiredFieldList.size(); j++) {
SectionField requiredField = (SectionField) requiredFieldList
.get(j);
buf.append(requiredField.getLabelKey() + "\t"
+ requiredField.getValue() + "\n");
}
}
}
private void addRequestedCMSectionIntoNotification(SessionState state, List cmRequestedSections, StringBuilder buf) {
// what are the required fields shown in the UI
for (int i = 0; i < cmRequestedSections.size(); i++) {
SectionObject so = (SectionObject) cmRequestedSections.get(i);
buf.append(so.getTitle() + "(" + so.getEid()
+ ")" + so.getCategory() + "\n");
}
}
/**
* Notification sent when a course site is set up automatcally
*
*/
private void sendSiteNotification(SessionState state, List notifySites) {
// get the request email from configuration
String requestEmail = getSetupRequestEmailAddress();
if (requestEmail != null) {
// send emails
Site site = getStateSite(state);
String id = site.getId();
String title = site.getTitle();
Time time = TimeService.newTime();
String local_time = time.toStringLocalTime();
String local_date = time.toStringLocalDate();
String term_name = "";
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
term_name = ((AcademicSession) state
.getAttribute(STATE_TERM_SELECTED)).getEid();
}
String message_subject = rb.getString("java.official") + " "
+ UserDirectoryService.getCurrentUser().getDisplayName()
+ " " + rb.getString("java.for") + " " + term_name;
String from = NULL_STRING;
String to = NULL_STRING;
String headerTo = NULL_STRING;
String replyTo = NULL_STRING;
String sender = UserDirectoryService.getCurrentUser()
.getDisplayName();
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
try {
userId = UserDirectoryService.getUserEid(userId);
} catch (UserNotDefinedException e) {
M_log.warn(this + rb.getString("user.notdefined") + " "
+ userId);
}
// To Support
from = UserDirectoryService.getCurrentUser().getEmail();
to = requestEmail;
headerTo = requestEmail;
replyTo = UserDirectoryService.getCurrentUser().getEmail();
StringBuilder buf = new StringBuilder();
buf.append("\n" + rb.getString("java.fromwork") + " "
+ ServerConfigurationService.getServerName() + " "
+ rb.getString("java.supp") + ":\n\n");
buf.append(rb.getString("java.off") + " '" + title + "' (id " + id
+ "), " + rb.getString("java.wasset") + " ");
buf.append(sender + " (" + userId + ", "
+ rb.getString("java.email2") + " " + replyTo + ") ");
buf.append(rb.getString("java.on") + " " + local_date + " "
+ rb.getString("java.at") + " " + local_time + " ");
buf.append(rb.getString("java.for") + " " + term_name + ", ");
int nbr_sections = notifySites.size();
if (nbr_sections > 1) {
buf.append(rb.getString("java.withrost") + " "
+ Integer.toString(nbr_sections) + " "
+ rb.getString("java.sections") + "\n\n");
} else {
buf.append(" " + rb.getString("java.withrost2") + "\n\n");
}
for (int i = 0; i < nbr_sections; i++) {
String course = (String) notifySites.get(i);
buf.append(rb.getString("java.course2") + " " + course + "\n");
}
String content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo,
replyTo, null);
} // if
} // sendSiteNotification
/**
* doCancel called when "eventSubmit_doCancel_create" is in the request
* parameters to c
*/
public void doCancel_create(RunData data) {
// Don't put current form data in state, just return to the previous
// template
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
removeAddClassContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} // doCancel_create
/**
* doCancel called when "eventSubmit_doCancel" is in the request parameters
* to c int index = Integer.valueOf(params.getString
* ("template-index")).intValue();
*/
public void doCancel(RunData data) {
// Don't put current form data in state, just return to the previous
// template
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.removeAttribute(STATE_MESSAGE);
String currentIndex = (String) state.getAttribute(STATE_TEMPLATE_INDEX);
String backIndex = params.getString("back");
state.setAttribute(STATE_TEMPLATE_INDEX, backIndex);
if (currentIndex.equals("4")) {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
state.removeAttribute(STATE_MESSAGE);
removeEditToolState(state);
} else if (currentIndex.equals("5")) {
// remove related state variables
removeAddParticipantContext(state);
params = data.getParameters();
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("back"));
} else if (currentIndex.equals("13") || currentIndex.equals("14")) {
// clean state attributes
state.removeAttribute(FORM_SITEINFO_TITLE);
state.removeAttribute(FORM_SITEINFO_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SKIN);
state.removeAttribute(FORM_SITEINFO_INCLUDE);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} else if (currentIndex.equals("15")) {
params = data.getParameters();
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("cancelIndex"));
removeEditToolState(state);
}
// htripath: added 'currentIndex.equals("45")' for import from file
// cancel
else if (currentIndex.equals("19") || currentIndex.equals("20")
|| currentIndex.equals("21") || currentIndex.equals("22")
|| currentIndex.equals("45")) {
// from adding participant pages
// remove related state variables
removeAddParticipantContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} else if (currentIndex.equals("3")) {
// from adding class
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} else if (currentIndex.equals("27") || currentIndex.equals("28")) {
// from import
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
// worksite setup
if (getStateSite(state) == null) {
// in creating new site process
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else {
// in editing site process
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
// site info
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
} else if (currentIndex.equals("26")) {
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)
&& getStateSite(state) == null) {
// from creating site
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else {
// from revising site
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
removeEditToolState(state);
} else if (currentIndex.equals("37") || currentIndex.equals("44") || currentIndex.equals("53") || currentIndex.equals("36")) {
// cancel back to edit class view
state.removeAttribute(STATE_TERM_SELECTED);
removeAddClassContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "43");
}
} // doCancel
/**
* doMenu_customize is called when "eventSubmit_doBack" is in the request
* parameters Pass parameter to actionForTemplate to request action for
* backward direction
*/
public void doMenu_customize(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "15");
}// doMenu_customize
/**
* doBack_to_list cancels an outstanding site edit, cleans state and returns
* to the site list
*
*/
public void doBack_to_list(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site site = getStateSite(state);
if (site != null) {
Hashtable h = (Hashtable) state
.getAttribute(STATE_PAGESIZE_SITEINFO);
h.put(site.getId(), state.getAttribute(STATE_PAGESIZE));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
}
// restore the page size for Worksite setup tool
if (state.getAttribute(STATE_PAGESIZE_SITESETUP) != null) {
state.setAttribute(STATE_PAGESIZE, state
.getAttribute(STATE_PAGESIZE_SITESETUP));
state.removeAttribute(STATE_PAGESIZE_SITESETUP);
}
cleanState(state);
setupFormNamesAndConstants(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} // doBack_to_list
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doAdd_custom_link(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if ((params.getString("name")) == null
|| (params.getString("url") == null)) {
Tool tr = ToolManager.getTool("sakai.iframe");
Site site = getStateSite(state);
SitePage page = site.addPage();
page.setTitle(params.getString("name")); // the visible label on
// the tool menu
ToolConfiguration tool = page.addTool();
tool.setTool("sakai.iframe", tr);
tool.setTitle(params.getString("name"));
commitSite(site);
} else {
addAlert(state, rb.getString("java.reqmiss"));
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("template-index"));
}
} // doAdd_custom_link
/**
* doAdd_remove_features is called when Make These Changes is clicked in
* chef_site-addRemoveFeatures
*/
public void doAdd_remove_features(RunData data) {
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
// dispatch
if (option.startsWith("add_")) {
// this could be format of originalToolId plus number of multiplication
String addToolId = option.substring("add_".length(), option.length());
// find the original tool id
String originToolId = findOriginalToolId(state, addToolId);
if (originToolId != null)
{
Tool tool = ToolManager.getTool(originToolId);
if (tool != null)
{
updateSelectedToolList(state, params, false);
insertTool(state, originToolId, tool.getTitle(), tool.getDescription(), Integer.parseInt(params.getString("num_"+ addToolId)));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
}
} else if (option.equalsIgnoreCase("save")) {
getFeatures(params, state, "15");
} else if (option.equalsIgnoreCase("continue")) {
updateSelectedToolList(state, params, false);
// continue
doContinue(data);
} else if (option.equalsIgnoreCase("Back")) {
// back
doBack(data);
} else if (option.equalsIgnoreCase("Cancel")) {
// cancel
doCancel(data);
}
} // doAdd_remove_features
/**
* toolId might be of form original tool id concatenated with number
* find whether there is an counterpart in the the multipleToolIdSet
* @param state
* @param toolId
* @return
*/
private String findOriginalToolId(SessionState state, String toolId) {
// treat home tool differently
if (toolId.equals(HOME_TOOL_ID))
{
return toolId;
}
else
{
Set categories = new HashSet();
categories.add((String) state.getAttribute(STATE_SITE_TYPE));
Set toolRegistrationList = ToolManager.findTools(categories, null);
String originToolId = null;
if (toolRegistrationList != null)
{
for (Iterator i=toolRegistrationList.iterator(); originToolId == null && i.hasNext();)
{
Tool tool = (Tool) i.next();
if (toolId.indexOf(tool.getId()) != -1)
{
originToolId = tool.getId();
}
}
}
return originToolId;
}
}
/**
* Read from tool registration whether multiple registration is allowed for this tool
* @param toolId
* @return
*/
private boolean isMultipleInstancesAllowed(String toolId)
{
Tool tool = ToolManager.getTool(toolId);
if (tool != null)
{
Properties tProperties = tool.getRegisteredConfig();
return (tProperties.containsKey("allowMultipleInstances")
&& tProperties.getProperty("allowMultipleInstances").equalsIgnoreCase(Boolean.TRUE.toString()))?true:false;
}
return false;
}
/**
* doSave_revised_features
*/
public void doSave_revised_features(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
getRevisedFeatures(params, state);
Site site = getStateSite(state);
String id = site.getId();
// now that the site exists, we can set the email alias when an Email
// Archive tool has been selected
String alias = StringUtil.trimToNull((String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
if (alias != null) {
String channelReference = mailArchiveChannelReference(id);
try {
AliasService.setAlias(alias, channelReference);
} catch (IdUsedException ee) {
} catch (IdInvalidException ee) {
addAlert(state, rb.getString("java.alias") + " " + alias + " "
+ rb.getString("java.isinval"));
} catch (PermissionException ee) {
addAlert(state, rb.getString("java.addalias") + " ");
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// clean state variables
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP);
state.setAttribute(STATE_SITE_INSTANCE_ID, id);
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("continue"));
}
// refresh the whole page
scheduleTopRefresh();
} // doSave_revised_features
/**
* doMenu_add_participant
*/
public void doMenu_add_participant(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
} // doMenu_add_participant
/**
* doMenu_siteInfo_addParticipant
*/
public void doMenu_siteInfo_addParticipant(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
}
} // doMenu_siteInfo_addParticipant
/**
* doMenu_siteInfo_cancel_access
*/
public void doMenu_siteInfo_cancel_access(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} // doMenu_siteInfo_cancel_access
/**
* doMenu_siteInfo_import
*/
public void doMenu_siteInfo_import(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "28");
}
} // doMenu_siteInfo_import
/**
* doMenu_siteInfo_editClass
*/
public void doMenu_siteInfo_editClass(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "43");
} // doMenu_siteInfo_editClass
/**
* doMenu_siteInfo_addClass
*/
public void doMenu_siteInfo_addClass(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site site = getStateSite(state);
String termEid = site.getProperties().getProperty(PROP_SITE_TERM_EID);
if (termEid == null)
{
// no term eid stored, need to get term eid from the term title
String termTitle = site.getProperties().getProperty(PROP_SITE_TERM);
List asList = cms.getAcademicSessions();
if (termTitle != null && asList != null)
{
boolean found = false;
for (int i = 0; i<asList.size() && !found; i++)
{
AcademicSession as = (AcademicSession) asList.get(i);
if (as.getTitle().equals(termTitle))
{
termEid = as.getEid();
site.getPropertiesEdit().addProperty(PROP_SITE_TERM_EID, termEid);
try
{
SiteService.save(site);
}
catch (Exception e)
{
M_log.warn(this + e.getMessage() + site.getId());
}
found=true;
}
}
}
}
state.setAttribute(STATE_TERM_SELECTED, cms.getAcademicSession(termEid));
try
{
List sections = prepareCourseAndSectionListing(UserDirectoryService.getCurrentUser().getEid(), cms.getAcademicSession(termEid).getEid(), state);
isFutureTermSelected(state);
if (sections != null && sections.size() > 0)
state.setAttribute(STATE_TERM_COURSE_LIST, sections);
}
catch (Exception e)
{
M_log.warn(e.getMessage() + termEid);
}
state.setAttribute(STATE_TEMPLATE_INDEX, "36");
} // doMenu_siteInfo_addClass
/**
* doMenu_siteInfo_duplicate
*/
public void doMenu_siteInfo_duplicate(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "29");
}
} // doMenu_siteInfo_import
/**
* doMenu_edit_site_info
*
*/
public void doMenu_edit_site_info(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site Site = getStateSite(state);
ResourceProperties siteProperties = Site.getProperties();
state.setAttribute(FORM_SITEINFO_TITLE, Site.getTitle());
String site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (site_type != null && !site_type.equalsIgnoreCase("myworkspace")) {
state.setAttribute(FORM_SITEINFO_INCLUDE, Boolean.valueOf(
Site.isPubView()).toString());
}
state.setAttribute(FORM_SITEINFO_DESCRIPTION, Site.getDescription());
state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION, Site
.getShortDescription());
state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl());
if (Site.getIconUrl() != null) {
state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl());
}
// site contact information
String contactName = siteProperties.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null) {
String creatorId = siteProperties
.getProperty(ResourceProperties.PROP_CREATOR);
try {
User u = UserDirectoryService.getUser(creatorId);
String email = u.getEmail();
if (email != null) {
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
} catch (UserNotDefinedException e) {
}
}
if (contactName != null) {
state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName);
}
if (contactEmail != null) {
state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, contactEmail);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
}
} // doMenu_edit_site_info
/**
* doMenu_edit_site_tools
*
*/
public void doMenu_edit_site_tools(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "4");
}
} // doMenu_edit_site_tools
/**
* doMenu_edit_site_access
*
*/
public void doMenu_edit_site_access(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} // doMenu_edit_site_access
/**
* Back to worksite setup's list view
*
*/
public void doBack_to_site_list(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_SITE_TYPE);
state.removeAttribute(STATE_SITE_INSTANCE_ID);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} // doBack_to_site_list
/**
* doSave_site_info
*
*/
public void doSave_siteInfo(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site Site = getStateSite(state);
ResourcePropertiesEdit siteProperties = Site.getPropertiesEdit();
String site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteTitleEditable(state, site_type))
{
Site.setTitle((String) state.getAttribute(FORM_SITEINFO_TITLE));
}
Site.setDescription((String) state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
Site.setShortDescription((String) state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
if (site_type != null) {
if (site_type.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
// set icon url for course
String skin = (String) state.getAttribute(FORM_SITEINFO_SKIN);
setAppearance(state, Site, skin);
} else {
// set icon url for others
String iconUrl = (String) state
.getAttribute(FORM_SITEINFO_ICON_URL);
Site.setIconUrl(iconUrl);
}
}
// site contact information
String contactName = (String) state
.getAttribute(FORM_SITEINFO_CONTACT_NAME);
if (contactName != null) {
siteProperties.addProperty(PROP_SITE_CONTACT_NAME, contactName);
}
String contactEmail = (String) state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL);
if (contactEmail != null) {
siteProperties.addProperty(PROP_SITE_CONTACT_EMAIL, contactEmail);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
try {
SiteService.save(Site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
// clean state attributes
state.removeAttribute(FORM_SITEINFO_TITLE);
state.removeAttribute(FORM_SITEINFO_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SKIN);
state.removeAttribute(FORM_SITEINFO_INCLUDE);
state.removeAttribute(FORM_SITEINFO_CONTACT_NAME);
state.removeAttribute(FORM_SITEINFO_CONTACT_EMAIL);
// back to site info view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
// refresh the whole page
scheduleTopRefresh();
}
} // doSave_siteInfo
/**
* Check to see whether the site's title is editable or not
* @param state
* @param site_type
* @return
*/
private boolean siteTitleEditable(SessionState state, String site_type) {
return site_type != null
&& (!site_type.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))
|| (state.getAttribute(TITLE_EDITABLE_SITE_TYPE) != null
&& ((List) state.getAttribute(TITLE_EDITABLE_SITE_TYPE)).contains(site_type)));
}
/**
* init
*
*/
private void init(VelocityPortlet portlet, RunData data, SessionState state) {
state.setAttribute(STATE_ACTION, "SiteAction");
setupFormNamesAndConstants(state);
if (state.getAttribute(STATE_PAGESIZE_SITEINFO) == null) {
state.setAttribute(STATE_PAGESIZE_SITEINFO, new Hashtable());
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
String siteId = ToolManager.getCurrentPlacement().getContext();
getReviseSite(state, siteId);
Hashtable h = (Hashtable) state
.getAttribute(STATE_PAGESIZE_SITEINFO);
if (!h.containsKey(siteId)) {
// update
h.put(siteId, new Integer(200));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
state.setAttribute(STATE_PAGESIZE, new Integer(200));
}
}
if (state.getAttribute(STATE_SITE_TYPES) == null) {
PortletConfig config = portlet.getPortletConfig();
// all site types (SITE_DEFAULT_LIST overrides tool config)
String t = StringUtil.trimToNull(SITE_DEFAULT_LIST);
if ( t == null )
t = StringUtil.trimToNull(config.getInitParameter("siteTypes"));
if (t != null) {
List types = new ArrayList(Arrays.asList(t.split(",")));
if (cms == null)
{
// if there is no CourseManagementService, disable the process of creating course site
String courseType = ServerConfigurationService.getString("courseSiteType", (String) state.getAttribute(STATE_COURSE_SITE_TYPE));
types.remove(courseType);
}
state.setAttribute(STATE_SITE_TYPES, types);
} else {
state.setAttribute(STATE_SITE_TYPES, new Vector());
}
}
} // init
public void doNavigate_to_site(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String siteId = StringUtil.trimToNull(data.getParameters().getString(
"option"));
if (siteId != null) {
getReviseSite(state, siteId);
} else {
doBack_to_list(data);
}
} // doNavigate_to_site
/**
* Get site information for revise screen
*/
private void getReviseSite(SessionState state, String siteId) {
if (state.getAttribute(STATE_SELECTED_USER_LIST) == null) {
state.setAttribute(STATE_SELECTED_USER_LIST, new Vector());
}
List sites = (List) state.getAttribute(STATE_SITES);
try {
Site site = SiteService.getSite(siteId);
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
if (sites != null) {
int pos = -1;
for (int index = 0; index < sites.size() && pos == -1; index++) {
if (((Site) sites.get(index)).getId().equals(siteId)) {
pos = index;
}
}
// has any previous site in the list?
if (pos > 0) {
state.setAttribute(STATE_PREV_SITE, sites.get(pos - 1));
} else {
state.removeAttribute(STATE_PREV_SITE);
}
// has any next site in the list?
if (pos < sites.size() - 1) {
state.setAttribute(STATE_NEXT_SITE, sites.get(pos + 1));
} else {
state.removeAttribute(STATE_NEXT_SITE);
}
}
String type = site.getType();
if (type == null) {
if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) {
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
}
state.setAttribute(STATE_SITE_TYPE, type);
} catch (IdUnusedException e) {
M_log.warn(this + e.toString());
}
// one site has been selected
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} // getReviseSite
/**
* doUpdate_participant
*
*/
public void doUpdate_participant(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
Site s = getStateSite(state);
String realmId = SiteService.siteReference(s.getId());
if (AuthzGroupService.allowUpdate(realmId)
|| SiteService.allowUpdateSiteMembership(s.getId())) {
try {
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId);
// does the site has maintain type user(s) before updating
// participants?
String maintainRoleString = realmEdit.getMaintainRole();
boolean hadMaintainUser = !realmEdit.getUsersHasRole(
maintainRoleString).isEmpty();
// update participant roles
List participants = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST));
// remove all roles and then add back those that were checked
for (int i = 0; i < participants.size(); i++) {
String id = null;
// added participant
Participant participant = (Participant) participants.get(i);
id = participant.getUniqname();
if (id != null) {
// get the newly assigned role
String inputRoleField = "role" + id;
String roleId = params.getString(inputRoleField);
// only change roles when they are different than before
if (roleId != null) {
// get the grant active status
boolean activeGrant = true;
String activeGrantField = "activeGrant" + id;
if (params.getString(activeGrantField) != null) {
activeGrant = params
.getString(activeGrantField)
.equalsIgnoreCase("true") ? true
: false;
}
boolean fromProvider = !participant.isRemoveable();
if (fromProvider && !roleId.equals(participant.getRole())) {
fromProvider = false;
}
realmEdit.addMember(id, roleId, activeGrant,
fromProvider);
}
}
}
// remove selected users
if (params.getStrings("selectedUser") != null) {
List removals = new ArrayList(Arrays.asList(params
.getStrings("selectedUser")));
state.setAttribute(STATE_SELECTED_USER_LIST, removals);
for (int i = 0; i < removals.size(); i++) {
String rId = (String) removals.get(i);
try {
User user = UserDirectoryService.getUser(rId);
realmEdit.removeMember(user.getId());
} catch (UserNotDefinedException e) {
M_log.warn(this + " IdUnusedException " + rId
+ ". ");
}
}
}
if (hadMaintainUser
&& realmEdit.getUsersHasRole(maintainRoleString)
.isEmpty()) {
// if after update, the "had maintain type user" status
// changed, show alert message and don't save the update
addAlert(state, rb
.getString("sitegen.siteinfolist.nomaintainuser")
+ maintainRoleString + ".");
} else {
// post event about the participant update
EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_SITE_MEMBERSHIP, realmEdit.getId(),false));
AuthzGroupService.save(realmEdit);
// then update all related group realms for the role
doUpdate_related_group_participants(s, realmId);
}
} catch (GroupNotDefinedException e) {
addAlert(state, rb.getString("java.problem2"));
M_log.warn(this + " IdUnusedException " + s.getTitle() + "("
+ realmId + "). ");
} catch (AuthzPermissionException e) {
addAlert(state, rb.getString("java.changeroles"));
M_log.warn(this + " PermissionException " + s.getTitle() + "("
+ realmId + "). ");
}
}
} // doUpdate_participant
/**
* update realted group realm setting according to parent site realm changes
* @param s
* @param realmId
*/
private void doUpdate_related_group_participants(Site s, String realmId) {
Collection groups = s.getGroups();
if (groups != null)
{
for (Iterator iGroups = groups.iterator(); iGroups.hasNext();)
{
Group g = (Group) iGroups.next();
try
{
Set gMembers = g.getMembers();
for (Iterator iGMembers = gMembers.iterator(); iGMembers.hasNext();)
{
Member gMember = (Member) iGMembers.next();
String gMemberId = gMember.getUserId();
Member siteMember = s.getMember(gMemberId);
if ( siteMember == null)
{
// user has been removed from the site
g.removeMember(gMemberId);
}
else
{
// if there is a difference between the role setting, remove the entry from group and add it back with correct role, all are marked "not provided"
if (!g.getUserRole(gMemberId).equals(siteMember.getRole()))
{
g.removeMember(gMemberId);
g.addMember(gMemberId, siteMember.getRole().getId(), siteMember.isActive(), false);
}
}
}
// commit
// post event about the participant update
EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_GROUP_MEMBERSHIP, g.getId(),false));
SiteService.save(s);
}
catch (Exception ee)
{
M_log.warn(this + ee.getMessage() + g.getId());
}
}
}
}
/**
* doUpdate_site_access
*
*/
public void doUpdate_site_access(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site sEdit = getStateSite(state);
ParameterParser params = data.getParameters();
String publishUnpublish = params.getString("publishunpublish");
String include = params.getString("include");
String joinable = params.getString("joinable");
if (sEdit != null) {
// editing existing site
// publish site or not
if (publishUnpublish != null
&& publishUnpublish.equalsIgnoreCase("publish")) {
sEdit.setPublished(true);
} else {
sEdit.setPublished(false);
}
// site public choice
if (include != null) {
// if there is pubview input, use it
sEdit.setPubView(include.equalsIgnoreCase("true") ? true
: false);
} else if (state.getAttribute(STATE_SITE_TYPE) != null) {
String type = (String) state.getAttribute(STATE_SITE_TYPE);
List publicSiteTypes = (List) state
.getAttribute(STATE_PUBLIC_SITE_TYPES);
List privateSiteTypes = (List) state
.getAttribute(STATE_PRIVATE_SITE_TYPES);
if (publicSiteTypes.contains(type)) {
// sites are always public
sEdit.setPubView(true);
} else if (privateSiteTypes.contains(type)) {
// site are always private
sEdit.setPubView(false);
}
} else {
sEdit.setPubView(false);
}
// publish site or not
if (joinable != null && joinable.equalsIgnoreCase("true")) {
state.setAttribute(STATE_JOINABLE, Boolean.TRUE);
sEdit.setJoinable(true);
String joinerRole = StringUtil.trimToNull(params
.getString("joinerRole"));
if (joinerRole != null) {
state.setAttribute(STATE_JOINERROLE, joinerRole);
sEdit.setJoinerRole(joinerRole);
} else {
state.setAttribute(STATE_JOINERROLE, "");
addAlert(state, rb.getString("java.joinsite") + " ");
}
} else {
state.setAttribute(STATE_JOINABLE, Boolean.FALSE);
state.removeAttribute(STATE_JOINERROLE);
sEdit.setJoinable(false);
sEdit.setJoinerRole(null);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
commitSite(sEdit);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
// TODO: hard coding this frame id is fragile, portal dependent,
// and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
state.removeAttribute(STATE_JOINABLE);
state.removeAttribute(STATE_JOINERROLE);
}
} else {
// adding new site
if (state.getAttribute(STATE_SITE_INFO) != null) {
SiteInfo siteInfo = (SiteInfo) state
.getAttribute(STATE_SITE_INFO);
if (publishUnpublish != null
&& publishUnpublish.equalsIgnoreCase("publish")) {
siteInfo.published = true;
} else {
siteInfo.published = false;
}
// site public choice
if (include != null) {
siteInfo.include = include.equalsIgnoreCase("true") ? true
: false;
} else if (StringUtil.trimToNull(siteInfo.site_type) != null) {
String type = StringUtil.trimToNull(siteInfo.site_type);
List publicSiteTypes = (List) state
.getAttribute(STATE_PUBLIC_SITE_TYPES);
List privateSiteTypes = (List) state
.getAttribute(STATE_PRIVATE_SITE_TYPES);
if (publicSiteTypes.contains(type)) {
// sites are always public
siteInfo.include = true;
} else if (privateSiteTypes.contains(type)) {
// site are always private
siteInfo.include = false;
}
} else {
siteInfo.include = false;
}
// joinable site or not
if (joinable != null && joinable.equalsIgnoreCase("true")) {
siteInfo.joinable = true;
String joinerRole = StringUtil.trimToNull(params
.getString("joinerRole"));
if (joinerRole != null) {
siteInfo.joinerRole = joinerRole;
} else {
addAlert(state, rb.getString("java.joinsite") + " ");
}
} else {
siteInfo.joinable = false;
siteInfo.joinerRole = null;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "10");
updateCurrentStep(state, true);
}
}
} // doUpdate_site_access
/**
* /* Actions for vm templates under the "chef_site" root. This method is
* called by doContinue. Each template has a hidden field with the value of
* template-index that becomes the value of index for the switch statement
* here. Some cases not implemented.
*/
private void actionForTemplate(String direction, int index,
ParameterParser params, SessionState state) {
// Continue - make any permanent changes, Back - keep any data entered
// on the form
boolean forward = direction.equals("continue") ? true : false;
SiteInfo siteInfo = new SiteInfo();
switch (index) {
case 0:
/*
* actionForTemplate chef_site-list.vm
*
*/
break;
case 1:
/*
* actionForTemplate chef_site-type.vm
*
*/
break;
case 2:
/*
* actionForTemplate chef_site-newSiteInformation.vm
*
*/
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
// defaults to be true
siteInfo.include = true;
state.setAttribute(STATE_SITE_INFO, siteInfo);
updateSiteInfo(params, state);
// alerts after clicking Continue but not Back
if (forward) {
if (StringUtil.trimToNull(siteInfo.title) == null) {
addAlert(state, rb.getString("java.reqfields"));
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
return;
}
}
updateSiteAttributes(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, forward);
}
break;
case 3:
/*
* actionForTemplate chef_site-newSiteFeatures.vm
*
*/
if (forward) {
getFeatures(params, state, "18");
}
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, forward);
}
break;
case 4:
/*
* actionForTemplate chef_site-addRemoveFeature.vm
*
*/
break;
case 5:
/*
* actionForTemplate chef_site-addParticipant.vm
*
*/
if (forward) {
checkAddParticipant(params, state);
} else {
// remove related state variables
removeAddParticipantContext(state);
}
break;
case 8:
/*
* actionForTemplate chef_site-siteDeleteConfirm.vm
*
*/
break;
case 10:
/*
* actionForTemplate chef_site-newSiteConfirm.vm
*
*/
if (!forward) {
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, false);
}
}
break;
case 12:
/*
* actionForTemplate chef_site_siteInfo-list.vm
*
*/
break;
case 13:
/*
* actionForTemplate chef_site_siteInfo-editInfo.vm
*
*/
if (forward) {
Site Site = getStateSite(state);
if (siteTitleEditable(state, Site.getType()))
{
// site titel is editable and could not be null
String title = StringUtil.trimToNull(params
.getString("title"));
state.setAttribute(FORM_SITEINFO_TITLE, title);
if (title == null) {
addAlert(state, rb.getString("java.specify") + " ");
}
}
String description = StringUtil.trimToNull(params
.getString("description"));
state.setAttribute(FORM_SITEINFO_DESCRIPTION, description);
String short_description = StringUtil.trimToNull(params
.getString("short_description"));
state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION,
short_description);
String skin = params.getString("skin");
if (skin != null) {
// if there is a skin input for course site
skin = StringUtil.trimToNull(skin);
state.setAttribute(FORM_SITEINFO_SKIN, skin);
} else {
// if ther is a icon input for non-course site
String icon = StringUtil.trimToNull(params
.getString("icon"));
if (icon != null) {
if (icon.endsWith(PROTOCOL_STRING)) {
addAlert(state, rb.getString("alert.protocol"));
}
state.setAttribute(FORM_SITEINFO_ICON_URL, icon);
} else {
state.removeAttribute(FORM_SITEINFO_ICON_URL);
}
}
// site contact information
String contactName = StringUtil.trimToZero(params
.getString("siteContactName"));
state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName);
String email = StringUtil.trimToZero(params
.getString("siteContactEmail"));
String[] parts = email.split("@");
if (email.length() > 0
&& (email.indexOf("@") == -1 || parts.length != 2
|| parts[0].length() == 0 || !Validator
.checkEmailLocal(parts[0]))) {
// invalid email
addAlert(state, email + " " + rb.getString("java.invalid")
+ rb.getString("java.theemail"));
}
state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, email);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "14");
}
}
break;
case 14:
/*
* actionForTemplate chef_site_siteInfo-editInfoConfirm.vm
*
*/
break;
case 15:
/*
* actionForTemplate chef_site_siteInfo-addRemoveFeatureConfirm.vm
*
*/
break;
case 18:
/*
* actionForTemplate chef_siteInfo-editAccess.vm
*
*/
if (!forward) {
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, false);
}
}
case 19:
/*
* actionForTemplate chef_site-addParticipant-sameRole.vm
*
*/
String roleId = StringUtil.trimToNull(params
.getString("selectRole"));
if (roleId == null && forward) {
addAlert(state, rb.getString("java.pleasesel") + " ");
} else {
state.setAttribute("form_selectedRole", params
.getString("selectRole"));
}
break;
case 20:
/*
* actionForTemplate chef_site-addParticipant-differentRole.vm
*
*/
if (forward) {
getSelectedRoles(state, params, STATE_ADD_PARTICIPANTS);
}
break;
case 21:
/*
* actionForTemplate chef_site-addParticipant-notification.vm '
*/
if (params.getString("notify") == null) {
if (forward)
addAlert(state, rb.getString("java.pleasechoice") + " ");
} else {
state.setAttribute("form_selectedNotify", new Boolean(params
.getString("notify")));
}
break;
case 22:
/*
* actionForTemplate chef_site-addParticipant-confirm.vm
*
*/
break;
case 24:
/*
* actionForTemplate
* chef_site-siteInfo-editAccess-globalAccess-confirm.vm
*
*/
break;
case 26:
/*
* actionForTemplate chef_site-modifyENW.vm
*
*/
updateSelectedToolList(state, params, forward);
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, forward);
}
break;
case 27:
/*
* actionForTemplate chef_site-importSites.vm
*
*/
if (forward) {
Site existingSite = getStateSite(state);
if (existingSite != null) {
// revising a existing site's tool
if (select_import_tools(params, state)) {
Hashtable importTools = (Hashtable) state
.getAttribute(STATE_IMPORT_SITE_TOOL);
List selectedTools = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
importToolIntoSite(selectedTools, importTools,
existingSite);
existingSite = getStateSite(state); // refresh site for
// WC and News
if (state.getAttribute(STATE_MESSAGE) == null) {
commitSite(existingSite);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
}
} else {
// show alert and remain in current page
addAlert(state, rb.getString("java.toimporttool"));
}
} else {
// new site
select_import_tools(params, state);
}
} else {
// read form input about import tools
select_import_tools(params, state);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, forward);
}
break;
case 28:
/*
* actionForTemplate chef_siteinfo-import.vm
*
*/
if (forward) {
if (params.getStrings("importSites") == null) {
addAlert(state, rb.getString("java.toimport") + " ");
state.removeAttribute(STATE_IMPORT_SITES);
} else {
List importSites = new ArrayList(Arrays.asList(params
.getStrings("importSites")));
Hashtable sites = new Hashtable();
for (index = 0; index < importSites.size(); index++) {
try {
Site s = SiteService.getSite((String) importSites
.get(index));
sites.put(s, new Vector());
} catch (IdUnusedException e) {
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
}
break;
case 29:
/*
* actionForTemplate chef_siteinfo-duplicate.vm
*
*/
if (forward) {
if (state.getAttribute(SITE_DUPLICATED) == null) {
if (StringUtil.trimToNull(params.getString("title")) == null) {
addAlert(state, rb.getString("java.dupli") + " ");
} else {
String title = params.getString("title");
state.setAttribute(SITE_DUPLICATED_NAME, title);
try {
String oSiteId = (String) state
.getAttribute(STATE_SITE_INSTANCE_ID);
String nSiteId = IdManager.createUuid();
Site site = SiteService.addSite(nSiteId,
getStateSite(state));
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
try {
site = SiteService.getSite(nSiteId);
// set title
site.setTitle(title);
// import tool content
List pageList = site.getPages();
if (!((pageList == null) || (pageList.size() == 0))) {
for (ListIterator i = pageList
.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
List pageToolList = page.getTools();
String toolId = ((ToolConfiguration) pageToolList
.get(0)).getTool().getId();
if (toolId
.equalsIgnoreCase("sakai.resources")) {
// handle
// resource
// tool
// specially
transferCopyEntities(
toolId,
ContentHostingService
.getSiteCollection(oSiteId),
ContentHostingService
.getSiteCollection(nSiteId));
} else {
// other
// tools
transferCopyEntities(toolId,
oSiteId, nSiteId);
}
}
}
} catch (Exception e1) {
// if goes here, IdService
// or SiteService has done
// something wrong.
M_log.warn(this + "Exception" + e1 + ":"
+ nSiteId + "when duplicating site");
}
if (site.getType().equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
// for course site, need to
// read in the input for
// term information
String termId = StringUtil.trimToNull(params
.getString("selectTerm"));
if (termId != null) {
AcademicSession term = cms.getAcademicSession(termId);
if (term != null) {
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.addProperty(PROP_SITE_TERM, term.getTitle());
rp.addProperty(PROP_SITE_TERM_EID, term.getEid());
} else {
M_log.warn("termId=" + termId + " not found");
}
}
}
try {
SiteService.save(site);
if (site.getType().equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE)))
{
// also remove the provider id attribute if any
String realm = SiteService.siteReference(site.getId());
try
{
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realm);
realmEdit.setProviderGroupId(null);
AuthzGroupService.save(realmEdit);
} catch (GroupNotDefinedException e) {
M_log.warn(this + " IdUnusedException, not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.realm"));
} catch (Exception e) {
addAlert(state, this + rb.getString("java.problem"));
}
}
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
// TODO: hard coding this frame id
// is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
state.setAttribute(SITE_DUPLICATED, Boolean.TRUE);
} catch (IdInvalidException e) {
addAlert(state, rb.getString("java.siteinval"));
} catch (IdUsedException e) {
addAlert(state, rb.getString("java.sitebeenused")
+ " ");
} catch (PermissionException e) {
addAlert(state, rb.getString("java.allowcreate")
+ " ");
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// site duplication confirmed
state.removeAttribute(SITE_DUPLICATED);
state.removeAttribute(SITE_DUPLICATED_NAME);
// return to the list view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
}
break;
case 33:
break;
case 36:
/*
* actionForTemplate chef_site-newSiteCourse.vm
*/
if (forward) {
List providerChosenList = new Vector();
if (params.getStrings("providerCourseAdd") == null) {
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (params.getString("manualAdds") == null) {
addAlert(state, rb.getString("java.manual") + " ");
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// The list of courses selected from provider listing
if (params.getStrings("providerCourseAdd") != null) {
providerChosenList = new ArrayList(Arrays.asList(params
.getStrings("providerCourseAdd"))); // list of
// course
// ids
String userId = (String) state
.getAttribute(STATE_INSTRUCTOR_SELECTED);
String currentUserId = (String) state
.getAttribute(STATE_CM_CURRENT_USERID);
if (userId == null
|| (userId != null && userId
.equals(currentUserId))) {
state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN,
providerChosenList);
state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS);
state.removeAttribute(FORM_ADDITIONAL);
state.removeAttribute(STATE_CM_AUTHORIZER_LIST);
} else {
// STATE_CM_AUTHORIZER_SECTIONS are SectionObject,
// so need to prepare it
// also in this page, u can pick either section from
// current user OR
// sections from another users but not both. -
// daisy's note 1 for now
// till we are ready to add more complexity
List sectionObjectList = prepareSectionObject(
providerChosenList, userId);
state.setAttribute(STATE_CM_AUTHORIZER_SECTIONS,
sectionObjectList);
state
.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
// set special instruction & we will keep
// STATE_CM_AUTHORIZER_LIST
String additional = StringUtil.trimToZero(params
.getString("additional"));
state.setAttribute(FORM_ADDITIONAL, additional);
}
}
collectNewSiteInfo(siteInfo, state, params,
providerChosenList);
}
// next step
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2));
}
break;
case 38:
break;
case 39:
break;
case 42:
/*
* actionForTemplate chef_site-gradtoolsConfirm.vm
*
*/
break;
case 43:
/*
* actionForTemplate chef_site-editClass.vm
*
*/
if (forward) {
if (params.getStrings("providerClassDeletes") == null
&& params.getStrings("manualClassDeletes") == null
&& params.getStrings("cmRequestedClassDeletes") == null
&& !direction.equals("back")) {
addAlert(state, rb.getString("java.classes"));
}
if (params.getStrings("providerClassDeletes") != null) {
// build the deletions list
List providerCourseList = (List) state
.getAttribute(SITE_PROVIDER_COURSE_LIST);
List providerCourseDeleteList = new ArrayList(Arrays
.asList(params.getStrings("providerClassDeletes")));
for (ListIterator i = providerCourseDeleteList
.listIterator(); i.hasNext();) {
providerCourseList.remove((String) i.next());
}
state.setAttribute(SITE_PROVIDER_COURSE_LIST,
providerCourseList);
}
if (params.getStrings("manualClassDeletes") != null) {
// build the deletions list
List manualCourseList = (List) state
.getAttribute(SITE_MANUAL_COURSE_LIST);
List manualCourseDeleteList = new ArrayList(Arrays
.asList(params.getStrings("manualClassDeletes")));
for (ListIterator i = manualCourseDeleteList.listIterator(); i
.hasNext();) {
manualCourseList.remove((String) i.next());
}
state.setAttribute(SITE_MANUAL_COURSE_LIST,
manualCourseList);
}
if (params.getStrings("cmRequestedClassDeletes") != null) {
// build the deletions list
List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS);
List<String> cmRequestedCourseDeleteList = new ArrayList(Arrays.asList(params.getStrings("cmRequestedClassDeletes")));
for (ListIterator i = cmRequestedCourseDeleteList.listIterator(); i
.hasNext();) {
String sectionId = (String) i.next();
try
{
SectionObject so = new SectionObject(cms.getSection(sectionId));
SectionObject soFound = null;
for (Iterator j = cmRequestedCourseList.iterator(); soFound == null && j.hasNext();)
{
SectionObject k = (SectionObject) j.next();
if (k.eid.equals(sectionId))
{
soFound = k;
}
}
if (soFound != null) cmRequestedCourseList.remove(soFound);
}
catch (Exception e)
{
M_log.warn(e.getMessage() + sectionId);
}
}
state.setAttribute(STATE_CM_REQUESTED_SECTIONS, cmRequestedCourseList);
}
updateCourseClasses(state, new Vector(), new Vector());
}
break;
case 44:
if (forward) {
AcademicSession a = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
Site site = getStateSite(state);
ResourcePropertiesEdit pEdit = site.getPropertiesEdit();
// update the course site property and realm based on the selection
updateCourseSiteSections(state, site.getId(), pEdit, a);
try
{
SiteService.save(site);
}
catch (Exception e)
{
M_log.warn(e.getMessage() + site.getId());
}
removeAddClassContext(state);
}
break;
case 49:
if (!forward) {
state.removeAttribute(SORTED_BY);
state.removeAttribute(SORTED_ASC);
}
break;
}
}// actionFor Template
/**
* update current step index within the site creation wizard
*
* @param state
* The SessionState object
* @param forward
* Moving forward or backward?
*/
private void updateCurrentStep(SessionState state, boolean forward) {
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) {
int currentStep = ((Integer) state
.getAttribute(SITE_CREATE_CURRENT_STEP)).intValue();
if (forward) {
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(
currentStep + 1));
} else {
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(
currentStep - 1));
}
}
}
/**
* remove related state variable for adding class
*
* @param state
* SessionState object
*/
private void removeAddClassContext(SessionState state) {
// remove related state variables
state.removeAttribute(STATE_ADD_CLASS_MANUAL);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
state.removeAttribute(STATE_AUTO_ADD);
state.removeAttribute(SITE_CREATE_TOTAL_STEPS);
state.removeAttribute(SITE_CREATE_CURRENT_STEP);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_CM_REQUESTED_SECTIONS);
state.removeAttribute(STATE_CM_SELECTED_SECTIONS);
sitePropertiesIntoState(state);
} // removeAddClassContext
private void updateCourseClasses(SessionState state, List notifyClasses,
List requestClasses) {
List providerCourseSectionList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
List manualCourseSectionList = (List) state.getAttribute(SITE_MANUAL_COURSE_LIST);
List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS);
Site site = getStateSite(state);
String id = site.getId();
String realmId = SiteService.siteReference(id);
if ((providerCourseSectionList == null)
|| (providerCourseSectionList.size() == 0)) {
// no section access so remove Provider Id
try {
AuthzGroup realmEdit1 = AuthzGroupService
.getAuthzGroup(realmId);
realmEdit1.setProviderGroupId(NULL_STRING);
AuthzGroupService.save(realmEdit1);
} catch (GroupNotDefinedException e) {
M_log.warn(this + " IdUnusedException, " + site.getTitle()
+ "(" + realmId
+ ") not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.cannotedit"));
return;
} catch (AuthzPermissionException e) {
M_log
.warn(this
+ " PermissionException, user does not have permission to edit AuthzGroup object "
+ site.getTitle() + "(" + realmId + "). ");
addAlert(state, rb.getString("java.notaccess"));
return;
}
}
if ((providerCourseSectionList != null)
&& (providerCourseSectionList.size() != 0)) {
// section access so rewrite Provider Id, don't need the current realm provider String
String externalRealm = buildExternalRealm(id, state,
providerCourseSectionList, null);
try {
AuthzGroup realmEdit2 = AuthzGroupService
.getAuthzGroup(realmId);
realmEdit2.setProviderGroupId(externalRealm);
AuthzGroupService.save(realmEdit2);
} catch (GroupNotDefinedException e) {
M_log.warn(this + " IdUnusedException, " + site.getTitle()
+ "(" + realmId
+ ") not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.cannotclasses"));
return;
} catch (AuthzPermissionException e) {
M_log
.warn(this
+ " PermissionException, user does not have permission to edit AuthzGroup object "
+ site.getTitle() + "(" + realmId + "). ");
addAlert(state, rb.getString("java.notaccess"));
return;
}
}
// the manual request course into properties
setSiteSectionProperty(manualCourseSectionList, site, PROP_SITE_REQUEST_COURSE);
// the cm request course into properties
setSiteSectionProperty(cmRequestedCourseList, site, STATE_CM_REQUESTED_SECTIONS);
// clean the related site groups
// if the group realm provider id is not listed for the site, remove the related group
for (Iterator iGroups = site.getGroups().iterator(); iGroups.hasNext();)
{
Group group = (Group) iGroups.next();
try
{
AuthzGroup gRealm = AuthzGroupService.getAuthzGroup(group.getReference());
String gProviderId = StringUtil.trimToNull(gRealm.getProviderGroupId());
if (gProviderId != null)
{
if ((manualCourseSectionList== null && cmRequestedCourseList == null)
|| (manualCourseSectionList != null && !manualCourseSectionList.contains(gProviderId) && cmRequestedCourseList == null)
|| (manualCourseSectionList == null && cmRequestedCourseList != null && !cmRequestedCourseList.contains(gProviderId))
|| (manualCourseSectionList != null && !manualCourseSectionList.contains(gProviderId) && cmRequestedCourseList != null && !cmRequestedCourseList.contains(gProviderId)))
{
AuthzGroupService.removeAuthzGroup(group.getReference());
}
}
}
catch (Exception e)
{
M_log.warn(this + ".updateCourseClasses: cannot remove authzgroup : " + group.getReference());
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
commitSite(site);
} else {
}
if (requestClasses != null && requestClasses.size() > 0
&& state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
try {
// send out class request notifications
sendSiteRequest(state, "change",
((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue(),
(List<SectionObject>) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS),
"manual");
} catch (Exception e) {
M_log.warn(this + e.toString());
}
}
if (notifyClasses != null && notifyClasses.size() > 0) {
try {
// send out class access confirmation notifications
sendSiteNotification(state, notifyClasses);
} catch (Exception e) {
M_log.warn(this + e.toString());
}
}
} // updateCourseClasses
private void setSiteSectionProperty(List courseSectionList, Site site, String propertyName) {
if ((courseSectionList != null) && (courseSectionList.size() != 0)) {
// store the requested sections in one site property
String sections = "";
for (int j = 0; j < courseSectionList.size();) {
sections = sections
+ (String) courseSectionList.get(j);
j++;
if (j < courseSectionList.size()) {
sections = sections + "+";
}
}
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.addProperty(propertyName, sections);
} else {
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.removeProperty(propertyName);
}
}
/**
* Sets selected roles for multiple users
*
* @param params
* The ParameterParser object
* @param listName
* The state variable
*/
private void getSelectedRoles(SessionState state, ParameterParser params,
String listName) {
Hashtable pSelectedRoles = (Hashtable) state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
if (pSelectedRoles == null) {
pSelectedRoles = new Hashtable();
}
List userList = (List) state.getAttribute(listName);
for (int i = 0; i < userList.size(); i++) {
String userId = null;
if (listName.equalsIgnoreCase(STATE_ADD_PARTICIPANTS)) {
userId = ((Participant) userList.get(i)).getUniqname();
} else if (listName.equalsIgnoreCase(STATE_SELECTED_USER_LIST)) {
userId = (String) userList.get(i);
}
if (userId != null) {
String rId = StringUtil.trimToNull(params.getString("role"
+ userId));
if (rId == null) {
addAlert(state, rb.getString("java.rolefor") + " " + userId
+ ". ");
pSelectedRoles.remove(userId);
} else {
pSelectedRoles.put(userId, rId);
}
}
}
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, pSelectedRoles);
} // getSelectedRoles
/**
* dispatch function for changing participants roles
*/
public void doSiteinfo_edit_role(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
// dispatch
if (option.equalsIgnoreCase("same_role_true")) {
state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.TRUE);
state.setAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE, params
.getString("role_to_all"));
} else if (option.equalsIgnoreCase("same_role_false")) {
state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.FALSE);
state.removeAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE);
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) == null) {
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES,
new Hashtable());
}
} else if (option.equalsIgnoreCase("continue")) {
doContinue(data);
} else if (option.equalsIgnoreCase("back")) {
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
doCancel(data);
}
} // doSiteinfo_edit_globalAccess
/**
* dispatch function for changing site global access
*/
public void doSiteinfo_edit_globalAccess(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
// dispatch
if (option.equalsIgnoreCase("joinable")) {
state.setAttribute("form_joinable", Boolean.TRUE);
state.setAttribute("form_joinerRole", getStateSite(state)
.getJoinerRole());
} else if (option.equalsIgnoreCase("unjoinable")) {
state.setAttribute("form_joinable", Boolean.FALSE);
state.removeAttribute("form_joinerRole");
} else if (option.equalsIgnoreCase("continue")) {
doContinue(data);
} else if (option.equalsIgnoreCase("cancel")) {
doCancel(data);
}
} // doSiteinfo_edit_globalAccess
/**
* save changes to site global access
*/
public void doSiteinfo_save_globalAccess(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site s = getStateSite(state);
boolean joinable = ((Boolean) state.getAttribute("form_joinable"))
.booleanValue();
s.setJoinable(joinable);
if (joinable) {
// set the joiner role
String joinerRole = (String) state.getAttribute("form_joinerRole");
s.setJoinerRole(joinerRole);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// release site edit
commitSite(s);
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} // doSiteinfo_save_globalAccess
/**
* updateSiteAttributes
*
*/
private void updateSiteAttributes(SessionState state) {
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
} else {
M_log
.warn("SiteAction.updateSiteAttributes STATE_SITE_INFO == null");
return;
}
Site site = getStateSite(state);
if (site != null) {
if (StringUtil.trimToNull(siteInfo.title) != null) {
site.setTitle(siteInfo.title);
}
if (siteInfo.description != null) {
site.setDescription(siteInfo.description);
}
site.setPublished(siteInfo.published);
setAppearance(state, site, siteInfo.iconUrl);
site.setJoinable(siteInfo.joinable);
if (StringUtil.trimToNull(siteInfo.joinerRole) != null) {
site.setJoinerRole(siteInfo.joinerRole);
}
// Make changes and then put changed site back in state
String id = site.getId();
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
if (SiteService.allowUpdateSite(id)) {
try {
SiteService.getSite(id);
state.setAttribute(STATE_SITE_INSTANCE_ID, id);
} catch (IdUnusedException e) {
M_log.warn("SiteAction.commitSite IdUnusedException "
+ siteInfo.getTitle() + "(" + id + ") not found");
}
}
// no permission
else {
addAlert(state, rb.getString("java.makechanges"));
M_log.warn("SiteAction.commitSite PermissionException "
+ siteInfo.getTitle() + "(" + id + ")");
}
}
} // updateSiteAttributes
/**
* %%% legacy properties, to be removed
*/
private void updateSiteInfo(ParameterParser params, SessionState state) {
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
siteInfo.site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (params.getString("title") != null) {
siteInfo.title = params.getString("title");
}
if (params.getString("description") != null) {
siteInfo.description = params.getString("description");
}
if (params.getString("short_description") != null) {
siteInfo.short_description = params.getString("short_description");
}
if (params.getString("additional") != null) {
siteInfo.additional = params.getString("additional");
}
if (params.getString("iconUrl") != null) {
siteInfo.iconUrl = params.getString("iconUrl");
} else {
siteInfo.iconUrl = params.getString("skin");
}
if (params.getString("joinerRole") != null) {
siteInfo.joinerRole = params.getString("joinerRole");
}
if (params.getString("joinable") != null) {
boolean joinable = params.getBoolean("joinable");
siteInfo.joinable = joinable;
if (!joinable)
siteInfo.joinerRole = NULL_STRING;
}
if (params.getString("itemStatus") != null) {
siteInfo.published = Boolean
.valueOf(params.getString("itemStatus")).booleanValue();
}
// site contact information
String name = StringUtil
.trimToZero(params.getString("siteContactName"));
siteInfo.site_contact_name = name;
String email = StringUtil.trimToZero(params
.getString("siteContactEmail"));
if (email != null) {
String[] parts = email.split("@");
if (email.length() > 0
&& (email.indexOf("@") == -1 || parts.length != 2
|| parts[0].length() == 0 || !Validator
.checkEmailLocal(parts[0]))) {
// invalid email
addAlert(state, email + " " + rb.getString("java.invalid")
+ rb.getString("java.theemail"));
}
siteInfo.site_contact_email = email;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
} // updateSiteInfo
/**
* getExternalRealmId
*
*/
private String getExternalRealmId(SessionState state) {
String realmId = SiteService.siteReference((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
String rv = null;
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
rv = realm.getProviderGroupId();
} catch (GroupNotDefinedException e) {
M_log.warn("SiteAction.getExternalRealmId, site realm not found");
}
return rv;
} // getExternalRealmId
/**
* getParticipantList
*
*/
private Collection getParticipantList(SessionState state) {
List members = new Vector();
String realmId = SiteService.siteReference((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
List providerCourseList = null;
providerCourseList = getProviderCourseList(StringUtil
.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null && providerCourseList.size() > 0) {
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
}
Collection participants = prepareParticipants(realmId, providerCourseList);
state.setAttribute(STATE_PARTICIPANT_LIST, participants);
return participants;
} // getParticipantList
private Collection prepareParticipants(String realmId, List providerCourseList) {
Map participantsMap = new ConcurrentHashMap();
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
realm.getProviderGroupId();
// iterate through the provider list first
for (Iterator i=providerCourseList.iterator(); i.hasNext();)
{
String providerCourseEid = (String) i.next();
try
{
Section section = cms.getSection(providerCourseEid);
if (section != null)
{
// in case of Section eid
EnrollmentSet enrollmentSet = section.getEnrollmentSet();
addParticipantsFromEnrollmentSet(participantsMap, realm, providerCourseEid, enrollmentSet, section.getTitle());
// add memberships
Set memberships = cms.getSectionMemberships(providerCourseEid);
addParticipantsFromMemberships(participantsMap, realm, providerCourseEid, memberships, section.getTitle());
}
}
catch (IdNotFoundException e)
{
M_log.warn("SiteAction prepareParticipants " + e.getMessage() + " sectionId=" + providerCourseEid);
}
}
// now for those not provided users
Set grants = realm.getMembers();
for (Iterator i = grants.iterator(); i.hasNext();) {
Member g = (Member) i.next();
try {
User user = UserDirectoryService.getUserByEid(g.getUserEid());
String userId = user.getId();
if (!participantsMap.containsKey(userId))
{
Participant participant;
if (participantsMap.containsKey(userId))
{
participant = (Participant) participantsMap.get(userId);
}
else
{
participant = new Participant();
}
participant.name = user.getSortName();
participant.uniqname = userId;
participant.role = g.getRole()!=null?g.getRole().getId():"";
participant.removeable = true;
participant.active = g.isActive();
participantsMap.put(userId, participant);
}
} catch (UserNotDefinedException e) {
// deal with missing user quietly without throwing a
// warning message
M_log.warn(e.getMessage());
}
}
} catch (GroupNotDefinedException ee) {
M_log.warn(this + " IdUnusedException " + realmId);
}
return participantsMap.values();
}
/**
* Add participant from provider-defined membership set
* @param participants
* @param realm
* @param providerCourseEid
* @param memberships
*/
private void addParticipantsFromMemberships(Map participantsMap, AuthzGroup realm, String providerCourseEid, Set memberships, String sectionTitle) {
if (memberships != null)
{
for (Iterator mIterator = memberships.iterator();mIterator.hasNext();)
{
Membership m = (Membership) mIterator.next();
try
{
User user = UserDirectoryService.getUserByEid(m.getUserId());
String userId = user.getId();
Member member = realm.getMember(userId);
if (member != null && member.isProvided())
{
// get or add provided participant
Participant participant;
if (participantsMap.containsKey(userId))
{
participant = (Participant) participantsMap.get(userId);
if (!participant.getSectionEidList().contains(sectionTitle)) {
participant.section = participant.section.concat(", <br />" + sectionTitle);
}
}
else
{
participant = new Participant();
participant.credits = "";
participant.name = user.getSortName();
participant.providerRole = member.getRole()!=null?member.getRole().getId():"";
participant.regId = "";
participant.removeable = false;
participant.role = member.getRole()!=null?member.getRole().getId():"";
participant.addSectionEidToList(sectionTitle);
participant.uniqname = userId;
participant.active=member.isActive();
}
participantsMap.put(userId, participant);
}
} catch (UserNotDefinedException exception) {
// deal with missing user quietly without throwing a
// warning message
M_log.warn(exception);
}
}
}
}
/**
* Add participant from provider-defined enrollment set
* @param participants
* @param realm
* @param providerCourseEid
* @param enrollmentSet
*/
private void addParticipantsFromEnrollmentSet(Map participantsMap, AuthzGroup realm, String providerCourseEid, EnrollmentSet enrollmentSet, String sectionTitle) {
if (enrollmentSet != null)
{
Set enrollments = cms.getEnrollments(enrollmentSet.getEid());
if (enrollments != null)
{
for (Iterator eIterator = enrollments.iterator();eIterator.hasNext();)
{
Enrollment e = (Enrollment) eIterator.next();
try
{
User user = UserDirectoryService.getUserByEid(e.getUserId());
String userId = user.getId();
Member member = realm.getMember(userId);
if (member != null && member.isProvided())
{
try
{
// get or add provided participant
Participant participant;
if (participantsMap.containsKey(userId))
{
participant = (Participant) participantsMap.get(userId);
//does this section contain the eid already
if (!participant.getSectionEidList().contains(sectionTitle)) {
participant.addSectionEidToList(sectionTitle);
}
participant.credits = participant.credits.concat(", <br />" + e.getCredits());
}
else
{
participant = new Participant();
participant.credits = e.getCredits();
participant.name = user.getSortName();
participant.providerRole = member.getRole()!=null?member.getRole().getId():"";
participant.regId = "";
participant.removeable = false;
participant.role = member.getRole()!=null?member.getRole().getId():"";
participant.addSectionEidToList(sectionTitle);
participant.uniqname = userId;
participant.active = member.isActive();
}
participantsMap.put(userId, participant);
}
catch (Exception ee)
{
M_log.warn(ee.getMessage());
}
}
} catch (UserNotDefinedException exception) {
// deal with missing user quietly without throwing a
// warning message
M_log.warn(exception.getMessage());
}
}
}
}
}
/**
* getRoles
*
*/
private List getRoles(SessionState state) {
List roles = new Vector();
String realmId = SiteService.siteReference((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
roles.addAll(realm.getRoles());
Collections.sort(roles);
} catch (GroupNotDefinedException e) {
M_log.warn("SiteAction.getRoles IdUnusedException " + realmId);
}
return roles;
} // getRoles
private void addSynopticTool(SitePage page, String toolId,
String toolTitle, String layoutHint) {
// Add synoptic announcements tool
ToolConfiguration tool = page.addTool();
Tool reg = ToolManager.getTool(toolId);
tool.setTool(toolId, reg);
tool.setTitle(toolTitle);
tool.setLayoutHints(layoutHint);
}
private void getRevisedFeatures(ParameterParser params, SessionState state) {
Site site = getStateSite(state);
// get the list of Worksite Setup configured pages
List wSetupPageList = (List) state
.getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST);
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
WorksiteSetupPage wSetupPage = new WorksiteSetupPage();
WorksiteSetupPage wSetupHome = new WorksiteSetupPage();
List pageList = new Vector();
// declare some flags used in making decisions about Home, whether to
// add, remove, or do nothing
boolean homeInChosenList = false;
boolean homeInWSetupPageList = false;
List chosenList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// if features were selected, diff wSetupPageList and chosenList to get
// page adds and removes
// boolean values for adding synoptic views
boolean hasAnnouncement = false;
boolean hasSchedule = false;
boolean hasChat = false;
boolean hasDiscussion = false;
boolean hasEmail = false;
boolean hasNewSiteInfo = false;
boolean hasMessageCenter = false;
// Special case - Worksite Setup Home comes from a hardcoded checkbox on
// the vm template rather than toolRegistrationList
// see if Home was chosen
for (ListIterator j = chosenList.listIterator(); j.hasNext();) {
String choice = (String) j.next();
if (choice.equalsIgnoreCase(HOME_TOOL_ID)) {
homeInChosenList = true;
} else if (choice.equals("sakai.mailbox")) {
hasEmail = true;
String alias = StringUtil.trimToNull((String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
if (alias != null) {
if (!Validator.checkEmailLocal(alias)) {
addAlert(state, rb.getString("java.theemail"));
} else {
try {
String channelReference = mailArchiveChannelReference(site
.getId());
// first, clear any alias set to this channel
AliasService.removeTargetAliases(channelReference); // check
// to
// see
// whether
// the
// alias
// has
// been
// used
try {
String target = AliasService.getTarget(alias);
if (target != null) {
addAlert(state, rb
.getString("java.emailinuse")
+ " ");
}
} catch (IdUnusedException ee) {
try {
AliasService.setAlias(alias,
channelReference);
} catch (IdUsedException exception) {
} catch (IdInvalidException exception) {
} catch (PermissionException exception) {
}
}
} catch (PermissionException exception) {
}
}
}
} else if (choice.equals("sakai.announcements")) {
hasAnnouncement = true;
} else if (choice.equals("sakai.schedule")) {
hasSchedule = true;
} else if (choice.equals("sakai.chat")) {
hasChat = true;
} else if (choice.equals("sakai.discussion")) {
hasDiscussion = true;
} else if (choice.equals("sakai.messages") || choice.equals("sakai.forums") || choice.equals("sakai.messagecenter")) {
hasMessageCenter = true;
}
}
// see if Home and/or Help in the wSetupPageList (can just check title
// here, because we checked patterns before adding to the list)
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) {
wSetupPage = (WorksiteSetupPage) i.next();
if (wSetupPage.getToolId().equals(HOME_TOOL_ID)) {
homeInWSetupPageList = true;
}
}
if (homeInChosenList) {
SitePage page = null;
// Were the synoptic views of Announcement, Discussioin, Chat
// existing before the editing
boolean hadAnnouncement = false, hadDiscussion = false, hadChat = false, hadSchedule = false, hadMessageCenter = false;
if (homeInWSetupPageList) {
if (!SiteService.isUserSite(site.getId())) {
// for non-myworkspace site, if Home is chosen and Home is
// in the wSetupPageList, remove synoptic tools
WorksiteSetupPage homePage = new WorksiteSetupPage();
for (ListIterator i = wSetupPageList.listIterator(); i
.hasNext();) {
WorksiteSetupPage comparePage = (WorksiteSetupPage) i
.next();
if ((comparePage.getToolId()).equals(HOME_TOOL_ID)) {
homePage = comparePage;
}
}
page = site.getPage(homePage.getPageId());
List toolList = page.getTools();
List removeToolList = new Vector();
// get those synoptic tools
for (ListIterator iToolList = toolList.listIterator(); iToolList
.hasNext();) {
ToolConfiguration tool = (ToolConfiguration) iToolList
.next();
Tool t = tool.getTool();
if (t!= null)
{
if (t.getId().equals("sakai.synoptic.announcement")) {
hadAnnouncement = true;
if (!hasAnnouncement) {
removeToolList.add(tool);// if Announcement
// tool isn't
// selected, remove
// the synotic
// Announcement
}
}
else if (t.getId().equals(TOOL_ID_SUMMARY_CALENDAR)) {
hadSchedule = true;
if (!hasSchedule || !notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR)) {
// if Schedule tool isn't selected, or the summary calendar tool is stealthed or hidden, remove the synotic Schedule
removeToolList.add(tool);
}
}
else if (t.getId().equals("sakai.synoptic.discussion")) {
hadDiscussion = true;
if (!hasDiscussion) {
removeToolList.add(tool);// if Discussion
// tool isn't
// selected, remove
// the synoptic
// Discussion
}
}
else if (t.getId().equals("sakai.synoptic.chat")) {
hadChat = true;
if (!hasChat) {
removeToolList.add(tool);// if Chat tool
// isn't selected,
// remove the
// synoptic Chat
}
}
else if (t.getId().equals("sakai.synoptic.messagecenter")) {
hadMessageCenter = true;
if (!hasMessageCenter) {
removeToolList.add(tool);// if Messages and/or Forums tools
// isn't selected,
// remove the
// synoptic Message Center tool
}
}
}
}
// remove those synoptic tools
for (ListIterator rToolList = removeToolList.listIterator(); rToolList
.hasNext();) {
page.removeTool((ToolConfiguration) rToolList.next());
}
}
} else {
// if Home is chosen and Home is not in wSetupPageList, add Home
// to site and wSetupPageList
page = site.addPage();
page.setTitle(rb.getString("java.home"));
wSetupHome.pageId = page.getId();
wSetupHome.pageTitle = page.getTitle();
wSetupHome.toolId = HOME_TOOL_ID;
wSetupPageList.add(wSetupHome);
// Add worksite information tool
ToolConfiguration tool = page.addTool();
Tool reg = ToolManager.getTool("sakai.iframe.site");
tool.setTool("sakai.iframe.site", reg);
tool.setTitle(reg.getTitle());
tool.setLayoutHints("0,0");
}
if (!SiteService.isUserSite(site.getId())) {
// add synoptical tools to home tool in non-myworkspace site
try {
if (hasAnnouncement && !hadAnnouncement) {
// Add synoptic announcements tool
addSynopticTool(page, "sakai.synoptic.announcement", rb
.getString("java.recann"), "0,1");
}
if (hasDiscussion && !hadDiscussion) {
// Add synoptic discussion tool
addSynopticTool(page, "sakai.synoptic.discussion", rb
.getString("java.recdisc"), "1,1");
}
if (hasChat && !hadChat) {
// Add synoptic chat tool
addSynopticTool(page, "sakai.synoptic.chat", rb
.getString("java.recent"), "2,1");
}
if (hasSchedule && !hadSchedule) {
// Add synoptic schedule tool if not stealth or hidden
if (notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR))
addSynopticTool(page, TOOL_ID_SUMMARY_CALENDAR, rb
.getString("java.reccal"), "3,1");
}
if (hasMessageCenter && !hadMessageCenter) {
// Add synoptic Message Center
addSynopticTool(page, "sakai.synoptic.messagecenter", rb
.getString("java.recmsg"), "4,1");
}
if (hasAnnouncement || hasDiscussion || hasChat
|| hasSchedule || hasMessageCenter) {
page.setLayout(SitePage.LAYOUT_DOUBLE_COL);
} else {
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
}
} catch (Exception e) {
M_log.warn("SiteAction getRevisedFeatures Exception: " + e.getMessage());
}
}
} // add Home
// if Home is in wSetupPageList and not chosen, remove Home feature from
// wSetupPageList and site
if (!homeInChosenList && homeInWSetupPageList) {
// remove Home from wSetupPageList
WorksiteSetupPage removePage = new WorksiteSetupPage();
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) {
WorksiteSetupPage comparePage = (WorksiteSetupPage) i.next();
if (comparePage.getToolId().equals(HOME_TOOL_ID)) {
removePage = comparePage;
}
}
SitePage siteHome = site.getPage(removePage.getPageId());
site.removePage(siteHome);
wSetupPageList.remove(removePage);
}
// declare flags used in making decisions about whether to add, remove,
// or do nothing
boolean inChosenList;
boolean inWSetupPageList;
Set categories = new HashSet();
categories.add((String) state.getAttribute(STATE_SITE_TYPE));
Set toolRegistrationList = ToolManager.findTools(categories, null);
// first looking for any tool for removal
Vector removePageIds = new Vector();
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) {
wSetupPage = (WorksiteSetupPage) k.next();
String pageToolId = wSetupPage.getToolId();
// use page id + tool id for multiple tool instances
if (isMultipleInstancesAllowed(findOriginalToolId(state, pageToolId))) {
pageToolId = wSetupPage.getPageId() + pageToolId;
}
inChosenList = false;
for (ListIterator j = chosenList.listIterator(); j.hasNext();) {
String toolId = (String) j.next();
if (pageToolId.equals(toolId)) {
inChosenList = true;
}
}
if (!inChosenList) {
removePageIds.add(wSetupPage.getPageId());
}
}
for (int i = 0; i < removePageIds.size(); i++) {
// if the tool exists in the wSetupPageList, remove it from the site
String removeId = (String) removePageIds.get(i);
SitePage sitePage = site.getPage(removeId);
site.removePage(sitePage);
// and remove it from wSetupPageList
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) {
wSetupPage = (WorksiteSetupPage) k.next();
if (!wSetupPage.getPageId().equals(removeId)) {
wSetupPage = null;
}
}
if (wSetupPage != null) {
wSetupPageList.remove(wSetupPage);
}
}
// then looking for any tool to add
for (ListIterator j = orderToolIds(state,
(String) state.getAttribute(STATE_SITE_TYPE), chosenList)
.listIterator(); j.hasNext();) {
String toolId = (String) j.next();
// Is the tool in the wSetupPageList?
inWSetupPageList = false;
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) {
wSetupPage = (WorksiteSetupPage) k.next();
String pageToolId = wSetupPage.getToolId();
// use page Id + toolId for multiple tool instances
if (isMultipleInstancesAllowed(findOriginalToolId(state, pageToolId))) {
pageToolId = wSetupPage.getPageId() + pageToolId;
}
if (pageToolId.equals(toolId)) {
inWSetupPageList = true;
// but for tool of multiple instances, need to change the title
if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) {
SitePage pEdit = (SitePage) site
.getPage(wSetupPage.pageId);
pEdit.setTitle((String) multipleToolIdTitleMap.get(toolId));
List toolList = pEdit.getTools();
for (ListIterator jTool = toolList.listIterator(); jTool
.hasNext();) {
ToolConfiguration tool = (ToolConfiguration) jTool
.next();
String tId = tool.getTool().getId();
if (isMultipleInstancesAllowed(findOriginalToolId(state, tId))) {
// set tool title
tool.setTitle((String) multipleToolIdTitleMap.get(toolId));
}
}
}
}
}
if (inWSetupPageList) {
// if the tool already in the list, do nothing so to save the
// option settings
} else {
// if in chosen list but not in wSetupPageList, add it to the
// site (one tool on a page)
// if Site Info tool is being newly added
if (toolId.equals("sakai.siteinfo")) {
hasNewSiteInfo = true;
}
Tool toolRegFound = null;
for (Iterator i = toolRegistrationList.iterator(); i.hasNext();) {
Tool toolReg = (Tool) i.next();
if ((toolId.indexOf("assignment") != -1 && toolId
.equals(toolReg.getId()))
|| (toolId.indexOf("assignment") == -1 && toolId
.indexOf(toolReg.getId()) != -1)) {
toolRegFound = toolReg;
}
}
if (toolRegFound != null) {
// we know such a tool, so add it
WorksiteSetupPage addPage = new WorksiteSetupPage();
SitePage page = site.addPage();
addPage.pageId = page.getId();
if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) {
// set tool title
page.setTitle((String) multipleToolIdTitleMap.get(toolId));
} else {
// other tools with default title
page.setTitle(toolRegFound.getTitle());
}
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool(toolRegFound.getId(), toolRegFound);
addPage.toolId = toolId;
wSetupPageList.add(addPage);
// set tool title
if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) {
// set tool title
tool.setTitle((String) multipleToolIdTitleMap.get(toolId));
} else {
tool.setTitle(toolRegFound.getTitle());
}
}
}
} // for
if (homeInChosenList) {
// Order tools - move Home to the top - first find it
SitePage homePage = null;
pageList = site.getPages();
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
if (rb.getString("java.home").equals(page.getTitle()))// if
// ("Home".equals(page.getTitle()))
{
homePage = page;
break;
}
}
}
// if found, move it
if (homePage != null) {
// move home from it's index to the first position
int homePosition = pageList.indexOf(homePage);
for (int n = 0; n < homePosition; n++) {
homePage.moveUp();
}
}
}
// if Site Info is newly added, more it to the last
if (hasNewSiteInfo) {
SitePage siteInfoPage = null;
pageList = site.getPages();
String[] toolIds = { "sakai.siteinfo" };
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); siteInfoPage == null
&& i.hasNext();) {
SitePage page = (SitePage) i.next();
int s = page.getTools(toolIds).size();
if (s > 0) {
siteInfoPage = page;
}
}
}
// if found, move it
if (siteInfoPage != null) {
// move home from it's index to the first position
int siteInfoPosition = pageList.indexOf(siteInfoPage);
for (int n = siteInfoPosition; n < pageList.size(); n++) {
siteInfoPage.moveDown();
}
}
}
// if there is no email tool chosen
if (!hasEmail) {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
// commit
commitSite(site);
} // getRevisedFeatures
/**
* Is the tool stealthed or hidden
* @param toolId
* @return
*/
private boolean notStealthOrHiddenTool(String toolId) {
return (ToolManager.getTool(toolId) != null
&& !ServerConfigurationService
.getString(
"[email protected]")
.contains(toolId)
&& !ServerConfigurationService
.getString(
"[email protected]")
.contains(toolId));
}
/**
* getFeatures gets features for a new site
*
*/
private void getFeatures(ParameterParser params, SessionState state, String continuePageIndex) {
List idsSelected = new Vector();
List existTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null? new Vector():(List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
// to reset the state variable of the multiple tool instances
Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET):new HashSet();
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
boolean goToToolConfigPage = false;
boolean homeSelected = false;
// Add new pages and tools, if any
if (params.getStrings("selectedTools") == null) {
addAlert(state, rb.getString("atleastonetool"));
} else {
List l = new ArrayList(Arrays.asList(params
.getStrings("selectedTools"))); // toolId's & titles of
// chosen tools
for (int i = 0; i < l.size(); i++) {
String toolId = (String) l.get(i);
if (toolId.equals(HOME_TOOL_ID)) {
homeSelected = true;
} else if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId)))
{
// if user is adding either EmailArchive tool, News tool
// or Web Content tool, go to the Customize page for the
// tool
if (!existTools.contains(toolId)) {
goToToolConfigPage = true;
multipleToolIdSet.add(toolId);
multipleToolIdTitleMap.put(toolId, ToolManager.getTool(toolId).getTitle());
}
if (toolId.equals("sakai.mailbox")) {
// get the email alias when an Email Archive tool
// has been selected
String channelReference = mailArchiveChannelReference((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
List aliases = AliasService.getAliases(
channelReference, 1, 1);
if (aliases.size() > 0) {
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS,
((Alias) aliases.get(0)).getId());
}
}
}
idsSelected.add(toolId);
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(
homeSelected));
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List of ToolRegistration toolId's
// in case of import
String importString = params.getString("import");
if (importString != null
&& importString.equalsIgnoreCase(Boolean.TRUE.toString())) {
state.setAttribute(STATE_IMPORT, Boolean.TRUE);
List importSites = new Vector();
if (params.getStrings("importSites") != null) {
importSites = new ArrayList(Arrays.asList(params
.getStrings("importSites")));
}
if (importSites.size() == 0) {
addAlert(state, rb.getString("java.toimport") + " ");
} else {
Hashtable sites = new Hashtable();
for (int index = 0; index < importSites.size(); index++) {
try {
Site s = SiteService.getSite((String) importSites
.get(index));
if (!sites.containsKey(s)) {
sites.put(s, new Vector());
}
} catch (IdUnusedException e) {
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
} else {
state.removeAttribute(STATE_IMPORT);
}
// of
// ToolRegistration
// toolId's
if (state.getAttribute(STATE_MESSAGE) == null) {
if (state.getAttribute(STATE_IMPORT) != null) {
// go to import tool page
state.setAttribute(STATE_TEMPLATE_INDEX, "27");
} else if (goToToolConfigPage) {
// go to the configuration page for multiple instances of tools
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
} else {
// go to next page
state.setAttribute(STATE_TEMPLATE_INDEX, continuePageIndex);
}
state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet);
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
}
} // getFeatures
/**
* addFeatures adds features to a new site
*
*/
private void addFeatures(SessionState state) {
List toolRegistrationList = (Vector) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET);
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
Site site = getStateSite(state);
List pageList = new Vector();
int moves = 0;
boolean hasHome = false;
boolean hasAnnouncement = false;
boolean hasSchedule = false;
boolean hasChat = false;
boolean hasDiscussion = false;
boolean hasSiteInfo = false;
boolean hasMessageCenter = false;
List chosenList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// tools to be imported from other sites?
Hashtable importTools = null;
if (state.getAttribute(STATE_IMPORT_SITE_TOOL) != null) {
importTools = (Hashtable) state.getAttribute(STATE_IMPORT_SITE_TOOL);
}
// for tools other than home
if (chosenList.contains(HOME_TOOL_ID)) {
// add home tool later
hasHome = true;
}
// order the id list
chosenList = orderToolIds(state, site.getType(), chosenList);
if (chosenList.size() > 0) {
Tool toolRegFound = null;
for (ListIterator i = chosenList.listIterator(); i.hasNext();) {
String toolId = (String) i.next();
// find the tool in the tool registration list
toolRegFound = null;
for (int j = 0; j < toolRegistrationList.size()
&& toolRegFound == null; j++) {
MyTool tool = (MyTool) toolRegistrationList.get(j);
if ((toolId.indexOf("assignment") != -1 && toolId
.equals(tool.getId()))
|| (toolId.indexOf("assignment") == -1 && toolId
.indexOf(tool.getId()) != -1)) {
toolRegFound = ToolManager.getTool(tool.getId());
}
}
if (toolRegFound != null) {
String originToolId = findOriginalToolId(state, toolId);
if (isMultipleInstancesAllowed(originToolId)) {
if (originToolId != null)
{
// adding multiple tool instance
String title = (String) multipleToolIdTitleMap.get(toolId);
SitePage page = site.addPage();
page.setTitle(title); // the visible label on the tool
// menu
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool(originToolId, ToolManager
.getTool(originToolId));
tool.setTitle(title);
tool.setLayoutHints("0,0");
}
} else {
SitePage page = site.addPage();
page.setTitle(toolRegFound.getTitle()); // the visible
// label on the
// tool menu
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool(toolRegFound.getId(), toolRegFound);
tool.setLayoutHints("0,0");
} // Other features
}
// booleans for synoptic views
if (toolId.equals("sakai.announcements")) {
hasAnnouncement = true;
} else if (toolId.equals("sakai.schedule")) {
hasSchedule = true;
} else if (toolId.equals("sakai.chat")) {
hasChat = true;
} else if (toolId.equals("sakai.discussion")) {
hasDiscussion = true;
} else if (toolId.equals("sakai.siteinfo")) {
hasSiteInfo = true;
} else if (toolId.equals("sakai.messages") || toolId.equals("sakai.forums") || toolId.equals("sakai.messagecenter")) {
hasMessageCenter = true;
}
} // for
// add home tool
if (hasHome) {
// Home is a special case, with several tools on the page.
// "home" is hard coded in chef_site-addRemoveFeatures.vm.
try {
SitePage page = site.addPage();
page.setTitle(rb.getString("java.home")); // the visible
// label on the
// tool menu
if (hasAnnouncement || hasDiscussion || hasChat
|| hasSchedule) {
page.setLayout(SitePage.LAYOUT_DOUBLE_COL);
} else {
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
}
// Add worksite information tool
ToolConfiguration tool = page.addTool();
Tool wsInfoTool = ToolManager.getTool("sakai.iframe.site");
tool.setTool("sakai.iframe.site", wsInfoTool);
tool.setTitle(wsInfoTool != null?wsInfoTool.getTitle():"");
tool.setLayoutHints("0,0");
if (hasAnnouncement) {
// Add synoptic announcements tool
tool = page.addTool();
tool.setTool("sakai.synoptic.announcement", ToolManager
.getTool("sakai.synoptic.announcement"));
tool.setTitle(rb.getString("java.recann"));
tool.setLayoutHints("0,1");
}
if (hasDiscussion) {
// Add synoptic announcements tool
tool = page.addTool();
tool.setTool("sakai.synoptic.discussion", ToolManager
.getTool("sakai.synoptic.discussion"));
tool.setTitle("Recent Discussion Items");
tool.setLayoutHints("1,1");
}
if (hasChat) {
// Add synoptic chat tool
tool = page.addTool();
tool.setTool("sakai.synoptic.chat", ToolManager
.getTool("sakai.synoptic.chat"));
tool.setTitle("Recent Chat Messages");
tool.setLayoutHints("2,1");
}
if (hasSchedule && notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR)) {
// Add synoptic schedule tool
tool = page.addTool();
tool.setTool(TOOL_ID_SUMMARY_CALENDAR, ToolManager
.getTool(TOOL_ID_SUMMARY_CALENDAR));
tool.setTitle(rb.getString("java.reccal"));
tool.setLayoutHints("3,1");
}
if (hasMessageCenter) {
// Add synoptic Message Center tool
tool = page.addTool();
tool.setTool("sakai.synoptic.messagecenter", ToolManager
.getTool("sakai.synoptic.messagecenter"));
tool.setTitle(rb.getString("java.recmsg"));
tool.setLayoutHints("4,1");
}
} catch (Exception e) {
M_log.warn("SiteAction addFeatures Exception:" + e.getMessage());
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, Boolean.TRUE);
// Order tools - move Home to the top
pageList = site.getPages();
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
if ((page.getTitle()).equals(rb.getString("java.home"))) {
moves = pageList.indexOf(page);
for (int n = 0; n < moves; n++) {
page.moveUp();
}
}
}
}
} // Home feature
// move Site Info tool, if selected, to the end of tool list
if (hasSiteInfo) {
SitePage siteInfoPage = null;
pageList = site.getPages();
String[] toolIds = { "sakai.siteinfo" };
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); siteInfoPage == null
&& i.hasNext();) {
SitePage page = (SitePage) i.next();
int s = page.getTools(toolIds).size();
if (s > 0) {
siteInfoPage = page;
}
}
}
// if found, move it
if (siteInfoPage != null) {
// move home from it's index to the first position
int siteInfoPosition = pageList.indexOf(siteInfoPage);
for (int n = siteInfoPosition; n < pageList.size(); n++) {
siteInfoPage.moveDown();
}
}
} // Site Info
}
// commit
commitSite(site);
// import
importToolIntoSite(chosenList, importTools, site);
} // addFeatures
// import tool content into site
private void importToolIntoSite(List toolIds, Hashtable importTools,
Site site) {
if (importTools != null) {
// import resources first
boolean resourcesImported = false;
for (int i = 0; i < toolIds.size() && !resourcesImported; i++) {
String toolId = (String) toolIds.get(i);
if (toolId.equalsIgnoreCase("sakai.resources")
&& importTools.containsKey(toolId)) {
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
String fromSiteCollectionId = ContentHostingService
.getSiteCollection(fromSiteId);
String toSiteCollectionId = ContentHostingService
.getSiteCollection(toSiteId);
transferCopyEntities(toolId, fromSiteCollectionId,
toSiteCollectionId);
resourcesImported = true;
}
}
}
// ijmport other tools then
for (int i = 0; i < toolIds.size(); i++) {
String toolId = (String) toolIds.get(i);
if (!toolId.equalsIgnoreCase("sakai.resources")
&& importTools.containsKey(toolId)) {
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
transferCopyEntities(toolId, fromSiteId, toSiteId);
}
}
}
}
} // importToolIntoSite
public void saveSiteStatus(SessionState state, boolean published) {
Site site = getStateSite(state);
site.setPublished(published);
} // saveSiteStatus
public void commitSite(Site site, boolean published) {
site.setPublished(published);
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
} // commitSite
public void commitSite(Site site) {
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
}// commitSite
private boolean isValidDomain(String email) {
String invalidNonOfficialAccountString = ServerConfigurationService
.getString("invalidNonOfficialAccountString", null);
if (invalidNonOfficialAccountString != null) {
String[] invalidDomains = invalidNonOfficialAccountString.split(",");
for (int i = 0; i < invalidDomains.length; i++) {
String domain = invalidDomains[i].trim();
if (email.toLowerCase().indexOf(domain.toLowerCase()) != -1) {
return false;
}
}
}
return true;
}
private void checkAddParticipant(ParameterParser params, SessionState state) {
// get the participants to be added
int i;
Vector pList = new Vector();
HashSet existingUsers = new HashSet();
Site site = null;
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
try {
site = SiteService.getSite(siteId);
} catch (IdUnusedException e) {
addAlert(state, rb.getString("java.specif") + " " + siteId);
}
// accept officialAccounts and/or nonOfficialAccount account names
String officialAccounts = "";
String nonOfficialAccounts = "";
// check that there is something with which to work
officialAccounts = StringUtil.trimToNull((params
.getString("officialAccount")));
nonOfficialAccounts = StringUtil.trimToNull(params
.getString("nonOfficialAccount"));
state.setAttribute("officialAccountValue", officialAccounts);
state.setAttribute("nonOfficialAccountValue", nonOfficialAccounts);
// if there is no uniquname or nonOfficialAccount entered
if (officialAccounts == null && nonOfficialAccounts == null) {
addAlert(state, rb.getString("java.guest"));
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
return;
}
String at = "@";
if (officialAccounts != null) {
// adding officialAccounts
String[] officialAccountArray = officialAccounts
.split("\r\n");
for (i = 0; i < officialAccountArray.length; i++) {
String officialAccount = StringUtil.trimToNull(officialAccountArray[i].replaceAll("[\t\r\n]", ""));
// if there is some text, try to use it
if (officialAccount != null) {
// automaticially add nonOfficialAccount account
Participant participant = new Participant();
try {
//Changed user lookup to satisfy BSP-1010 (jholtzman)
User u = null;
// First try looking for the user by their email address
Collection usersWithEmail = UserDirectoryService.findUsersByEmail(officialAccount);
if(usersWithEmail != null) {
if(usersWithEmail.size() == 0) {
// If the collection is empty, we didn't find any users with this email address
M_log.info("Unable to find users with email " + officialAccount);
} else if (usersWithEmail.size() == 1) {
// We found one user with this email address. Use it.
u = (User)usersWithEmail.iterator().next();
} else if (usersWithEmail.size() > 1) {
// If we have multiple users with this email address, pick one and log this error condition
// TODO Should we not pick a user? Throw an exception?
M_log.warn("Found multiple user with email " + officialAccount);
u = (User)usersWithEmail.iterator().next();
}
}
// We didn't find anyone via email address, so try getting the user by EID
if(u == null) {
u = UserDirectoryService.getUserByEid(officialAccount);
}
if (u != null)
{
M_log.info("found user with eid " + officialAccount);
if (site != null && site.getUserRole(u.getId()) != null) {
// user already exists in the site, cannot be added
// again
existingUsers.add(officialAccount);
} else {
participant.name = u.getDisplayName();
participant.uniqname = u.getEid();
participant.active = true;
pList.add(participant);
}
}
} catch (UserNotDefinedException e) {
addAlert(state, officialAccount + " " + rb.getString("java.username") + " ");
}
}
}
} // officialAccounts
if (nonOfficialAccounts != null) {
String[] nonOfficialAccountArray = nonOfficialAccounts.split("\r\n");
for (i = 0; i < nonOfficialAccountArray.length; i++) {
String nonOfficialAccount = StringUtil.trimToNull(nonOfficialAccountArray[i].replaceAll("[ \t\r\n]", ""));
// remove the trailing dots
while (nonOfficialAccount != null && nonOfficialAccount.endsWith(".")) {
nonOfficialAccount = nonOfficialAccount.substring(0,
nonOfficialAccount.length() - 1);
}
if (nonOfficialAccount != null && nonOfficialAccount.length() > 0) {
String[] parts = nonOfficialAccount.split(at);
if (nonOfficialAccount.indexOf(at) == -1) {
// must be a valid email address
addAlert(state, nonOfficialAccount + " "
+ rb.getString("java.emailaddress"));
} else if ((parts.length != 2) || (parts[0].length() == 0)) {
// must have both id and address part
addAlert(state, nonOfficialAccount + " "
+ rb.getString("java.notemailid"));
} else if (!Validator.checkEmailLocal(parts[0])) {
addAlert(state, nonOfficialAccount + " "
+ rb.getString("java.emailaddress")
+ rb.getString("java.theemail"));
} else if (nonOfficialAccount != null
&& !isValidDomain(nonOfficialAccount)) {
// wrong string inside nonOfficialAccount id
addAlert(state, nonOfficialAccount + " "
+ rb.getString("java.emailaddress") + " ");
} else {
Participant participant = new Participant();
try {
// if the nonOfficialAccount user already exists
User u = UserDirectoryService
.getUserByEid(nonOfficialAccount);
if (site != null
&& site.getUserRole(u.getId()) != null) {
// user already exists in the site, cannot be
// added again
existingUsers.add(nonOfficialAccount);
} else {
participant.name = u.getDisplayName();
participant.uniqname = nonOfficialAccount;
participant.active = true;
pList.add(participant);
}
} catch (UserNotDefinedException e) {
// if the nonOfficialAccount user is not in the system
// yet
participant.name = nonOfficialAccount;
participant.uniqname = nonOfficialAccount; // TODO:
// what
// would
// the
// UDS
// case
// this
// name
// to?
// -ggolden
participant.active = true;
pList.add(participant);
}
}
} // if
} //
} // nonOfficialAccounts
boolean same_role = true;
if (params.getString("same_role") == null) {
addAlert(state, rb.getString("java.roletype") + " ");
} else {
same_role = params.getString("same_role").equals("true") ? true
: false;
state.setAttribute("form_same_role", new Boolean(same_role));
}
if (state.getAttribute(STATE_MESSAGE) != null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
} else {
if (same_role) {
state.setAttribute(STATE_TEMPLATE_INDEX, "19");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "20");
}
}
// remove duplicate or existing user from participant list
pList = removeDuplicateParticipants(pList, state);
state.setAttribute(STATE_ADD_PARTICIPANTS, pList);
// if the add participant list is empty after above removal, stay in the
// current page
if (pList.size() == 0) {
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
}
// add alert for attempting to add existing site user(s)
if (!existingUsers.isEmpty()) {
int count = 0;
String accounts = "";
for (Iterator eIterator = existingUsers.iterator(); eIterator
.hasNext();) {
if (count == 0) {
accounts = (String) eIterator.next();
} else {
accounts = accounts + ", " + (String) eIterator.next();
}
count++;
}
addAlert(state, rb.getString("add.existingpart.1") + accounts
+ rb.getString("add.existingpart.2"));
}
return;
} // checkAddParticipant
private Vector removeDuplicateParticipants(List pList, SessionState state) {
// check the uniqness of list member
Set s = new HashSet();
Set uniqnameSet = new HashSet();
Vector rv = new Vector();
for (int i = 0; i < pList.size(); i++) {
Participant p = (Participant) pList.get(i);
if (!uniqnameSet.contains(p.getUniqname())) {
// no entry for the account yet
rv.add(p);
uniqnameSet.add(p.getUniqname());
} else {
// found duplicates
s.add(p.getUniqname());
}
}
if (!s.isEmpty()) {
int count = 0;
String accounts = "";
for (Iterator i = s.iterator(); i.hasNext();) {
if (count == 0) {
accounts = (String) i.next();
} else {
accounts = accounts + ", " + (String) i.next();
}
count++;
}
if (count == 1) {
addAlert(state, rb.getString("add.duplicatedpart.single")
+ accounts + ".");
} else {
addAlert(state, rb.getString("add.duplicatedpart") + accounts
+ ".");
}
}
return rv;
}
public void doAdd_participant(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String siteTitle = getStateSite(state).getTitle();
String nonOfficialAccountLabel = ServerConfigurationService.getString(
"nonOfficialAccountLabel", "");
Hashtable selectedRoles = (Hashtable) state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
boolean notify = false;
if (state.getAttribute("form_selectedNotify") != null) {
notify = ((Boolean) state.getAttribute("form_selectedNotify"))
.booleanValue();
}
boolean same_role = ((Boolean) state.getAttribute("form_same_role"))
.booleanValue();
Hashtable eIdRoles = new Hashtable();
List addParticipantList = (List) state
.getAttribute(STATE_ADD_PARTICIPANTS);
for (int i = 0; i < addParticipantList.size(); i++) {
Participant p = (Participant) addParticipantList.get(i);
String eId = p.getEid();
// role defaults to same role
String role = (String) state.getAttribute("form_selectedRole");
if (!same_role) {
// if all added participants have different role
role = (String) selectedRoles.get(eId);
}
boolean officialAccount = eId.indexOf(EMAIL_CHAR) == -1;
if (officialAccount) {
// if this is a officialAccount
// update the hashtable
eIdRoles.put(eId, role);
} else {
// if this is an nonOfficialAccount
try {
UserDirectoryService.getUserByEid(eId);
} catch (UserNotDefinedException e) {
// if there is no such user yet, add the user
try {
UserEdit uEdit = UserDirectoryService
.addUser(null, eId);
// set email address
uEdit.setEmail(eId);
// set the guest user type
uEdit.setType("guest");
// set password to a positive random number
Random generator = new Random(System
.currentTimeMillis());
Integer num = new Integer(generator
.nextInt(Integer.MAX_VALUE));
if (num.intValue() < 0)
num = new Integer(num.intValue() * -1);
String pw = num.toString();
uEdit.setPassword(pw);
// and save
UserDirectoryService.commitEdit(uEdit);
boolean notifyNewUserEmail = (ServerConfigurationService
.getString("notifyNewUserEmail", Boolean.TRUE
.toString()))
.equalsIgnoreCase(Boolean.TRUE.toString());
if (notifyNewUserEmail) {
userNotificationProvider.notifyNewUserEmail(uEdit, pw, siteTitle);
}
} catch (UserIdInvalidException ee) {
addAlert(state, nonOfficialAccountLabel + " id " + eId
+ " " + rb.getString("java.isinval"));
M_log.warn(this
+ " UserDirectoryService addUser exception "
+ e.getMessage());
} catch (UserAlreadyDefinedException ee) {
addAlert(state, "The " + nonOfficialAccountLabel + " "
+ eId + " " + rb.getString("java.beenused"));
M_log.warn(this
+ " UserDirectoryService addUser exception "
+ e.getMessage());
} catch (UserPermissionException ee) {
addAlert(state, rb.getString("java.haveadd") + " "
+ eId);
M_log.warn(this
+ " UserDirectoryService addUser exception "
+ e.getMessage());
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
eIdRoles.put(eId, role);
}
}
}
// batch add and updates the successful added list
List addedParticipantEIds = addUsersRealm(state, eIdRoles, notify,
false);
// update the not added user list
String notAddedOfficialAccounts = NULL_STRING;
String notAddedNonOfficialAccounts = NULL_STRING;
for (Iterator iEIds = eIdRoles.keySet().iterator(); iEIds.hasNext();) {
String iEId = (String) iEIds.next();
if (!addedParticipantEIds.contains(iEId)) {
if (iEId.indexOf(EMAIL_CHAR) == -1) {
// no email in eid
notAddedOfficialAccounts = notAddedOfficialAccounts
.concat(iEId + "\n");
} else {
// email in eid
notAddedNonOfficialAccounts = notAddedNonOfficialAccounts
.concat(iEId + "\n");
}
}
}
if (addedParticipantEIds.size() != 0
&& (!notAddedOfficialAccounts.equals(NULL_STRING) || !notAddedNonOfficialAccounts.equals(NULL_STRING))) {
// at lease one officialAccount account or an nonOfficialAccount
// account added, and there are also failures
addAlert(state, rb.getString("java.allusers"));
}
if (notAddedOfficialAccounts.equals(NULL_STRING)
&& notAddedNonOfficialAccounts.equals(NULL_STRING)) {
// all account has been added successfully
removeAddParticipantContext(state);
} else {
state.setAttribute("officialAccountValue",
notAddedOfficialAccounts);
state.setAttribute("nonOfficialAccountValue",
notAddedNonOfficialAccounts);
}
if (state.getAttribute(STATE_MESSAGE) != null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "22");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
return;
} // doAdd_participant
/**
* remove related state variable for adding participants
*
* @param state
* SessionState object
*/
private void removeAddParticipantContext(SessionState state) {
// remove related state variables
state.removeAttribute("form_selectedRole");
state.removeAttribute("officialAccountValue");
state.removeAttribute("nonOfficialAccountValue");
state.removeAttribute("form_same_role");
state.removeAttribute("form_selectedNotify");
state.removeAttribute(STATE_ADD_PARTICIPANTS);
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
} // removeAddParticipantContext
private String getSetupRequestEmailAddress() {
String from = ServerConfigurationService.getString("setup.request",
null);
if (from == null) {
from = "postmaster@".concat(ServerConfigurationService
.getServerName());
M_log.warn(this + " - no 'setup.request' in configuration, using: "+ from);
}
return from;
}
/*
* Given a list of user eids, add users to realm If the user account does
* not exist yet inside the user directory, assign role to it @return A list
* of eids for successfully added users
*/
private List addUsersRealm(SessionState state, Hashtable eIdRoles,
boolean notify, boolean nonOfficialAccount) {
// return the list of user eids for successfully added user
List addedUserEIds = new Vector();
StringBuilder message = new StringBuilder();
if (eIdRoles != null && !eIdRoles.isEmpty()) {
// get the current site
Site sEdit = getStateSite(state);
if (sEdit != null) {
// get realm object
String realmId = sEdit.getReference();
try {
AuthzGroup realmEdit = AuthzGroupService
.getAuthzGroup(realmId);
for (Iterator eIds = eIdRoles.keySet().iterator(); eIds
.hasNext();) {
String eId = (String) eIds.next();
String role = (String) eIdRoles.get(eId);
try {
User user = UserDirectoryService.getUserByEid(eId);
if (AuthzGroupService.allowUpdate(realmId)
|| SiteService
.allowUpdateSiteMembership(sEdit
.getId())) {
realmEdit.addMember(user.getId(), role, true,
false);
addedUserEIds.add(eId);
// send notification
if (notify) {
String emailId = user.getEmail();
String userName = user.getDisplayName();
// send notification email
if (this.userNotificationProvider == null)
{
M_log.warn("notification provider is null!");
}
else
{
userNotificationProvider.notifyAddedParticipant(nonOfficialAccount, user, sEdit.getTitle());
}
}
}
} catch (UserNotDefinedException e) {
message.append(eId + " "
+ rb.getString("java.account") + " \n");
} // try
} // for
try {
AuthzGroupService.save(realmEdit);
} catch (GroupNotDefinedException ee) {
message.append(rb.getString("java.realm") + realmId);
} catch (AuthzPermissionException ee) {
message.append(rb.getString("java.permeditsite")
+ realmId);
}
} catch (GroupNotDefinedException eee) {
message.append(rb.getString("java.realm") + realmId);
} catch (Exception eee) {
M_log.warn("SiteActionaddUsersRealm " + eee.getMessage() + " realmId=" + realmId);
}
}
}
if (message.length() != 0) {
addAlert(state, message.toString());
} // if
return addedUserEIds;
} // addUsersRealm
/**
* addNewSite is called when the site has enough information to create a new
* site
*
*/
private void addNewSite(ParameterParser params, SessionState state) {
if (getStateSite(state) != null) {
// There is a Site in state already, so use it rather than creating
// a new Site
return;
}
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
String id = StringUtil.trimToNull(siteInfo.getSiteId());
if (id == null) {
// get id
id = IdManager.createUuid();
siteInfo.site_id = id;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (state.getAttribute(STATE_MESSAGE) == null) {
try {
Site site = SiteService.addSite(id, siteInfo.site_type);
String title = StringUtil.trimToNull(siteInfo.title);
String description = siteInfo.description;
setAppearance(state, site, siteInfo.iconUrl);
site.setDescription(description);
if (title != null) {
site.setTitle(title);
}
site.setType(siteInfo.site_type);
ResourcePropertiesEdit rp = site.getPropertiesEdit();
site.setShortDescription(siteInfo.short_description);
site.setPubView(siteInfo.include);
site.setJoinable(siteInfo.joinable);
site.setJoinerRole(siteInfo.joinerRole);
site.setPublished(siteInfo.published);
// site contact information
rp.addProperty(PROP_SITE_CONTACT_NAME,
siteInfo.site_contact_name);
rp.addProperty(PROP_SITE_CONTACT_EMAIL,
siteInfo.site_contact_email);
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
// commit newly added site in order to enable related realm
commitSite(site);
} catch (IdUsedException e) {
addAlert(state, rb.getString("java.sitewithid") + " " + id
+ " " + rb.getString("java.exists"));
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("template-index"));
return;
} catch (IdInvalidException e) {
addAlert(state, rb.getString("java.thesiteid") + " " + id + " "
+ rb.getString("java.notvalid"));
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("template-index"));
return;
} catch (PermissionException e) {
addAlert(state, rb.getString("java.permission") + " " + id
+ ".");
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("template-index"));
return;
}
}
} // addNewSite
/**
* %%% legacy properties, to be cleaned up
*
*/
private void sitePropertiesIntoState(SessionState state) {
try {
Site site = getStateSite(state);
SiteInfo siteInfo = new SiteInfo();
if (site != null)
{
// set from site attributes
siteInfo.title = site.getTitle();
siteInfo.description = site.getDescription();
siteInfo.iconUrl = site.getIconUrl();
siteInfo.infoUrl = site.getInfoUrl();
siteInfo.joinable = site.isJoinable();
siteInfo.joinerRole = site.getJoinerRole();
siteInfo.published = site.isPublished();
siteInfo.include = site.isPubView();
siteInfo.short_description = site.getShortDescription();
}
siteInfo.additional = "";
state.setAttribute(STATE_SITE_TYPE, siteInfo.site_type);
state.setAttribute(STATE_SITE_INFO, siteInfo);
} catch (Exception e) {
M_log.warn("SiteAction.sitePropertiesIntoState " + e.getMessage());
}
} // sitePropertiesIntoState
/**
* pageMatchesPattern returns true if a SitePage matches a WorkSite Setup
* pattern
*
*/
private boolean pageMatchesPattern(SessionState state, SitePage page) {
List pageToolList = page.getTools();
// if no tools on the page, return false
if (pageToolList == null || pageToolList.size() == 0) {
return false;
}
// for the case where the page has one tool
ToolConfiguration toolConfiguration = (ToolConfiguration) pageToolList
.get(0);
// don't compare tool properties, which may be changed using Options
List toolList = new Vector();
int count = pageToolList.size();
boolean match = false;
// check Worksite Setup Home pattern
if (page.getTitle() != null
&& page.getTitle().equals(rb.getString("java.home"))) {
return true;
} // Home
else if (page.getTitle() != null
&& page.getTitle().equals(rb.getString("java.help"))) {
// if the count of tools on the page doesn't match, return false
if (count != 1) {
return false;
}
// if the page layout doesn't match, return false
if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) {
return false;
}
// if tooId isn't sakai.contactSupport, return false
if (!(toolConfiguration.getTool().getId())
.equals("sakai.contactSupport")) {
return false;
}
return true;
} // Help
else if (page.getTitle() != null && page.getTitle().equals("Chat")) {
// if the count of tools on the page doesn't match, return false
if (count != 1) {
return false;
}
// if the page layout doesn't match, return false
if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) {
return false;
}
// if the tool doesn't match, return false
if (!(toolConfiguration.getTool().getId()).equals("sakai.chat")) {
return false;
}
// if the channel doesn't match value for main channel, return false
String channel = toolConfiguration.getPlacementConfig()
.getProperty("channel");
if (channel == null) {
return false;
}
if (!(channel.equals(NULL_STRING))) {
return false;
}
return true;
} // Chat
else {
// if the count of tools on the page doesn't match, return false
if (count != 1) {
return false;
}
// if the page layout doesn't match, return false
if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) {
return false;
}
toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
if (pageToolList != null || pageToolList.size() != 0) {
// if tool attributes don't match, return false
match = false;
for (ListIterator i = toolList.listIterator(); i.hasNext();) {
MyTool tool = (MyTool) i.next();
if (toolConfiguration.getTitle() != null) {
if (toolConfiguration.getTool() != null
&& toolConfiguration.getTool().getId().indexOf(
tool.getId()) != -1) {
match = true;
}
}
}
if (!match) {
return false;
}
}
} // Others
return true;
} // pageMatchesPattern
/**
* siteToolsIntoState is the replacement for siteToolsIntoState_ Make a list
* of pages and tools that match WorkSite Setup configurations into state
*/
private void siteToolsIntoState(SessionState state) {
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
String wSetupTool = NULL_STRING;
List wSetupPageList = new Vector();
Site site = getStateSite(state);
List pageList = site.getPages();
// Put up tool lists filtered by category
String type = site.getType();
if (type == null) {
if (SiteService.isUserSite(site.getId())) {
type = "myworkspace";
} else if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) {
// for those sites without type, use the tool set for default
// site type
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
}
if (type == null) {
M_log.warn(this + ": - unknown STATE_SITE_TYPE");
} else {
state.setAttribute(STATE_SITE_TYPE, type);
}
// set tool registration list
setToolRegistrationList(state, type);
List toolRegList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
// for the selected tools
boolean check_home = false;
Vector idSelected = new Vector();
if (!((pageList == null) || (pageList.size() == 0))) {
for (ListIterator i = pageList.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
// collect the pages consistent with Worksite Setup patterns
if (pageMatchesPattern(state, page)) {
if (page.getTitle().equals(rb.getString("java.home"))) {
wSetupTool = HOME_TOOL_ID;
check_home = true;
}
else
{
List pageToolList = page.getTools();
wSetupTool = ((ToolConfiguration) pageToolList.get(0)).getTool().getId();
if (isMultipleInstancesAllowed(findOriginalToolId(state, wSetupTool)))
{
String mId = page.getId() + wSetupTool;
idSelected.add(mId);
multipleToolIdTitleMap.put(mId, page.getTitle());
MyTool newTool = new MyTool();
newTool.title = ToolManager.getTool(wSetupTool).getTitle();
newTool.id = mId;
newTool.selected = false;
boolean hasThisMultipleTool = false;
int j = 0;
for (; j < toolRegList.size() && !hasThisMultipleTool; j++) {
MyTool t = (MyTool) toolRegList.get(j);
if (t.getId().equals(wSetupTool)) {
hasThisMultipleTool = true;
newTool.description = t.getDescription();
}
}
if (hasThisMultipleTool) {
toolRegList.add(j - 1, newTool);
} else {
toolRegList.add(newTool);
}
}
else
{
idSelected.add(wSetupTool);
}
}
WorksiteSetupPage wSetupPage = new WorksiteSetupPage();
wSetupPage.pageId = page.getId();
wSetupPage.pageTitle = page.getTitle();
wSetupPage.toolId = wSetupTool;
wSetupPageList.add(wSetupPage);
}
}
}
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(check_home));
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idSelected); // List
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolRegList);
// of
// ToolRegistration
// toolId's
state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST,idSelected); // List of ToolRegistration toolId's
state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME, Boolean.valueOf(check_home));
state.setAttribute(STATE_WORKSITE_SETUP_PAGE_LIST, wSetupPageList);
} // siteToolsIntoState
/**
* reset the state variables used in edit tools mode
*
* @state The SessionState object
*/
private void removeEditToolState(SessionState state) {
state.removeAttribute(STATE_TOOL_HOME_SELECTED);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // List
// of
// ToolRegistration
// toolId's
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // List
// of
// ToolRegistration
// toolId's
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_WORKSITE_SETUP_PAGE_LIST);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET);
//state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP);
}
private List orderToolIds(SessionState state, String type, List toolIdList) {
List rv = new Vector();
if (state.getAttribute(STATE_TOOL_HOME_SELECTED) != null
&& ((Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED))
.booleanValue()) {
rv.add(HOME_TOOL_ID);
}
// look for null site type
if (type != null && toolIdList != null) {
Set categories = new HashSet();
categories.add(type);
Set tools = ToolManager.findTools(categories, null);
SortedIterator i = new SortedIterator(tools.iterator(),
new ToolComparator());
for (; i.hasNext();) {
String tool_id = ((Tool) i.next()).getId();
for (ListIterator j = toolIdList.listIterator(); j.hasNext();) {
String toolId = (String) j.next();
if (toolId.indexOf("assignment") != -1
&& toolId.equals(tool_id)
|| toolId.indexOf("assignment") == -1
&& toolId.indexOf(tool_id) != -1) {
rv.add(toolId);
}
}
}
}
return rv;
} // orderToolIds
private void setupFormNamesAndConstants(SessionState state) {
TimeBreakdown timeBreakdown = (TimeService.newTime()).breakdownLocal();
String mycopyright = COPYRIGHT_SYMBOL + " " + timeBreakdown.getYear()
+ ", " + UserDirectoryService.getCurrentUser().getDisplayName()
+ ". All Rights Reserved. ";
state.setAttribute(STATE_MY_COPYRIGHT, mycopyright);
state.setAttribute(STATE_SITE_INSTANCE_ID, null);
state.setAttribute(STATE_INITIALIZED, Boolean.TRUE.toString());
SiteInfo siteInfo = new SiteInfo();
Participant participant = new Participant();
participant.name = NULL_STRING;
participant.uniqname = NULL_STRING;
participant.active = true;
state.setAttribute(STATE_SITE_INFO, siteInfo);
state.setAttribute("form_participantToAdd", participant);
state.setAttribute(FORM_ADDITIONAL, NULL_STRING);
// legacy
state.setAttribute(FORM_HONORIFIC, "0");
state.setAttribute(FORM_REUSE, "0");
state.setAttribute(FORM_RELATED_CLASS, "0");
state.setAttribute(FORM_RELATED_PROJECT, "0");
state.setAttribute(FORM_INSTITUTION, "0");
// sundry form variables
state.setAttribute(FORM_PHONE, "");
state.setAttribute(FORM_EMAIL, "");
state.setAttribute(FORM_SUBJECT, "");
state.setAttribute(FORM_DESCRIPTION, "");
state.setAttribute(FORM_TITLE, "");
state.setAttribute(FORM_NAME, "");
state.setAttribute(FORM_SHORT_DESCRIPTION, "");
} // setupFormNamesAndConstants
/**
* setupSkins
*
*/
private void setupIcons(SessionState state) {
List icons = new Vector();
String[] iconNames = null;
String[] iconUrls = null;
String[] iconSkins = null;
// get icon information
if (ServerConfigurationService.getStrings("iconNames") != null) {
iconNames = ServerConfigurationService.getStrings("iconNames");
}
if (ServerConfigurationService.getStrings("iconUrls") != null) {
iconUrls = ServerConfigurationService.getStrings("iconUrls");
}
if (ServerConfigurationService.getStrings("iconSkins") != null) {
iconSkins = ServerConfigurationService.getStrings("iconSkins");
}
if ((iconNames != null) && (iconUrls != null) && (iconSkins != null)
&& (iconNames.length == iconUrls.length)
&& (iconNames.length == iconSkins.length)) {
for (int i = 0; i < iconNames.length; i++) {
MyIcon s = new MyIcon(StringUtil.trimToNull((String) iconNames[i]),
StringUtil.trimToNull((String) iconUrls[i]), StringUtil
.trimToNull((String) iconSkins[i]));
icons.add(s);
}
}
state.setAttribute(STATE_ICONS, icons);
}
private void setAppearance(SessionState state, Site edit, String iconUrl) {
// set the icon
edit.setIconUrl(iconUrl);
if (iconUrl == null) {
// this is the default case - no icon, no (default) skin
edit.setSkin(null);
return;
}
// if this icon is in the config appearance list, find a skin to set
List icons = (List) state.getAttribute(STATE_ICONS);
for (Iterator i = icons.iterator(); i.hasNext();) {
Object icon = (Object) i.next();
if (icon instanceof MyIcon && !StringUtil.different(((MyIcon) icon).getUrl(), iconUrl)) {
edit.setSkin(((MyIcon) icon).getSkin());
return;
}
}
}
/**
* A dispatch funtion when selecting course features
*/
public void doAdd_features(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
// to reset the state variable of the multiple tool instances
Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET):new HashSet();
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
// dispatch
if (option.startsWith("add_")) {
// this could be format of originalToolId plus number of multiplication
String addToolId = option.substring("add_".length(), option.length());
// find the original tool id
String originToolId = findOriginalToolId(state, addToolId);
if (originToolId != null)
{
Tool tool = ToolManager.getTool(originToolId);
if (tool != null)
{
updateSelectedToolList(state, params, false);
insertTool(state, originToolId, tool.getTitle(), tool.getDescription(), Integer.parseInt(params.getString("num_"+ addToolId)));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
}
} else if (option.equalsIgnoreCase("import")) {
// import or not
updateSelectedToolList(state, params, false);
String importSites = params.getString("import");
if (importSites != null
&& importSites.equalsIgnoreCase(Boolean.TRUE.toString())) {
state.setAttribute(STATE_IMPORT, Boolean.TRUE);
if (importSites.equalsIgnoreCase(Boolean.TRUE.toString())) {
state.removeAttribute(STATE_IMPORT);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
}
} else {
state.removeAttribute(STATE_IMPORT);
}
} else if (option.equalsIgnoreCase("continue")) {
// continue
updateSelectedToolList(state, params, false);
doContinue(data);
} else if (option.equalsIgnoreCase("back")) {
// back
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
// cancel
doCancel_create(data);
}
} // doAdd_features
/**
* update the selected tool list
*
* @param params
* The ParameterParser object
* @param verifyData
* Need to verify input data or not
*/
private void updateSelectedToolList(SessionState state,
ParameterParser params, boolean verifyData) {
List selectedTools = new ArrayList(Arrays.asList(params
.getStrings("selectedTools")));
Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET);
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
boolean has_home = false;
String emailId = null;
for (int i = 0; i < selectedTools.size(); i++)
{
String id = (String) selectedTools.get(i);
if (id.equalsIgnoreCase(HOME_TOOL_ID)) {
has_home = true;
}
else if (findOriginalToolId(state, id) != null)
{
String title = StringUtil.trimToNull(params
.getString("title_" + id));
if (title != null)
{
// save the titles entered
multipleToolIdTitleMap.put(id, title);
}
} else if (id.equalsIgnoreCase("sakai.mailbox")) {
// if Email archive tool is selected, check the email alias
emailId = StringUtil.trimToNull(params.getString("emailId"));
if (verifyData) {
if (emailId == null) {
addAlert(state, rb.getString("java.emailarchive") + " ");
} else {
if (!Validator.checkEmailLocal(emailId)) {
addAlert(state, rb.getString("java.theemail"));
} else {
// check to see whether the alias has been used by
// other sites
try {
String target = AliasService.getTarget(emailId);
if (target != null) {
if (state
.getAttribute(STATE_SITE_INSTANCE_ID) != null) {
String siteId = (String) state
.getAttribute(STATE_SITE_INSTANCE_ID);
String channelReference = mailArchiveChannelReference(siteId);
if (!target.equals(channelReference)) {
// the email alias is not used by
// current site
addAlert(state, rb.getString("java.emailinuse") + " ");
}
} else {
addAlert(state, rb.getString("java.emailinuse") + " ");
}
}
} catch (IdUnusedException ee) {
}
}
}
}
}
}
// update the state objects
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(has_home));
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, emailId);
} // updateSelectedToolList
/**
* find the tool in the tool list and insert another tool instance to the list
* @param state
* @param toolId
* @param defaultTitle
* @param defaultDescription
* @param insertTimes
*/
private void insertTool(SessionState state, String toolId, String defaultTitle, String defaultDescription, int insertTimes) {
// the list of available tools
List toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
List oTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null? new Vector():(List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
int toolListedTimes = 0;
int index = 0;
int insertIndex = 0;
while (index < toolList.size()) {
MyTool tListed = (MyTool) toolList.get(index);
if (tListed.getId().indexOf(toolId) != -1 && !oTools.contains(tListed.getId())) {
toolListedTimes++;
}
if (toolListedTimes > 0 && insertIndex == 0) {
// update the insert index
insertIndex = index;
}
index++;
}
List toolSelected = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// insert multiple tools
for (int i = 0; i < insertTimes; i++) {
toolSelected.add(toolId + toolListedTimes);
// We need to insert a specific tool entry only if all the specific
// tool entries have been selected
MyTool newTool = new MyTool();
newTool.title = defaultTitle;
newTool.id = toolId + toolListedTimes;
newTool.description = defaultDescription;
toolList.add(insertIndex, newTool);
toolListedTimes++;
// add title
multipleToolIdTitleMap.put(newTool.id, defaultTitle);
}
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolList);
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolSelected);
} // insertTool
/**
*
* set selected participant role Hashtable
*/
private void setSelectedParticipantRoles(SessionState state) {
List selectedUserIds = (List) state
.getAttribute(STATE_SELECTED_USER_LIST);
List participantList = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST));
List selectedParticipantList = new Vector();
Hashtable selectedParticipantRoles = new Hashtable();
if (!selectedUserIds.isEmpty() && participantList != null) {
for (int i = 0; i < participantList.size(); i++) {
String id = "";
Object o = (Object) participantList.get(i);
if (o.getClass().equals(Participant.class)) {
// get participant roles
id = ((Participant) o).getUniqname();
selectedParticipantRoles.put(id, ((Participant) o)
.getRole());
}
if (selectedUserIds.contains(id)) {
selectedParticipantList.add(participantList.get(i));
}
}
}
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES,
selectedParticipantRoles);
state
.setAttribute(STATE_SELECTED_PARTICIPANTS,
selectedParticipantList);
} // setSelectedParticipantRol3es
/**
* the SiteComparator class
*/
private class SiteComparator implements Comparator {
Collator collator = Collator.getInstance();
/**
* the criteria
*/
String m_criterion = null;
String m_asc = null;
/**
* constructor
*
* @param criteria
* The sort criteria string
* @param asc
* The sort order string. TRUE_STRING if ascending; "false"
* otherwise.
*/
public SiteComparator(String criterion, String asc) {
m_criterion = criterion;
m_asc = asc;
} // constructor
/**
* implementing the Comparator compare function
*
* @param o1
* The first object
* @param o2
* The second object
* @return The compare result. 1 is o1 < o2; -1 otherwise
*/
public int compare(Object o1, Object o2) {
int result = -1;
if (m_criterion == null)
m_criterion = SORTED_BY_TITLE;
/** *********** for sorting site list ****************** */
if (m_criterion.equals(SORTED_BY_TITLE)) {
// sorted by the worksite title
String s1 = ((Site) o1).getTitle();
String s2 = ((Site) o2).getTitle();
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_DESCRIPTION)) {
// sorted by the site short description
String s1 = ((Site) o1).getShortDescription();
String s2 = ((Site) o2).getShortDescription();
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_TYPE)) {
// sorted by the site type
String s1 = ((Site) o1).getType();
String s2 = ((Site) o2).getType();
result = compareString(s1, s2);
} else if (m_criterion.equals(SortType.CREATED_BY_ASC.toString())) {
// sorted by the site creator
String s1 = ((Site) o1).getProperties().getProperty(
"CHEF:creator");
String s2 = ((Site) o2).getProperties().getProperty(
"CHEF:creator");
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_STATUS)) {
// sort by the status, published or unpublished
int i1 = ((Site) o1).isPublished() ? 1 : 0;
int i2 = ((Site) o2).isPublished() ? 1 : 0;
if (i1 > i2) {
result = 1;
} else {
result = -1;
}
} else if (m_criterion.equals(SORTED_BY_JOINABLE)) {
// sort by whether the site is joinable or not
boolean b1 = ((Site) o1).isJoinable();
boolean b2 = ((Site) o2).isJoinable();
result = compareBoolean(b1, b2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_NAME)) {
// sort by whether the site is joinable or not
String s1 = null;
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getName();
}
String s2 = null;
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getName();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_UNIQNAME)) {
// sort by whether the site is joinable or not
String s1 = null;
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getUniqname();
}
String s2 = null;
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getUniqname();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_ROLE)) {
String s1 = "";
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getRole();
}
String s2 = "";
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getRole();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_COURSE)) {
// sort by whether the site is joinable or not
String s1 = null;
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getSection();
}
String s2 = null;
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getSection();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_ID)) {
String s1 = null;
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getRegId();
}
String s2 = null;
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getRegId();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_CREDITS)) {
String s1 = null;
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getCredits();
}
String s2 = null;
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getCredits();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_STATUS)) {
boolean a1 = true;
if (o1.getClass().equals(Participant.class)) {
a1 = ((Participant) o1).isActive();
}
boolean a2 = true;
if (o2.getClass().equals(Participant.class)) {
a2 = ((Participant) o2).isActive();
}
// let the active users show first when sort ascendingly
result = -compareBoolean(a1, a2);
} else if (m_criterion.equals(SORTED_BY_CREATION_DATE)) {
// sort by the site's creation date
Time t1 = null;
Time t2 = null;
// get the times
try {
t1 = ((Site) o1).getProperties().getTimeProperty(
ResourceProperties.PROP_CREATION_DATE);
} catch (EntityPropertyNotDefinedException e) {
} catch (EntityPropertyTypeException e) {
}
try {
t2 = ((Site) o2).getProperties().getTimeProperty(
ResourceProperties.PROP_CREATION_DATE);
} catch (EntityPropertyNotDefinedException e) {
} catch (EntityPropertyTypeException e) {
}
if (t1 == null) {
result = -1;
} else if (t2 == null) {
result = 1;
} else if (t1.before(t2)) {
result = -1;
} else {
result = 1;
}
} else if (m_criterion.equals(rb.getString("group.title"))) {
// sorted by the group title
String s1 = ((Group) o1).getTitle();
String s2 = ((Group) o2).getTitle();
result = compareString(s1, s2);
} else if (m_criterion.equals(rb.getString("group.number"))) {
// sorted by the group title
int n1 = ((Group) o1).getMembers().size();
int n2 = ((Group) o2).getMembers().size();
result = (n1 > n2) ? 1 : -1;
} else if (m_criterion.equals(SORTED_BY_MEMBER_NAME)) {
// sorted by the member name
String s1 = null;
String s2 = null;
try {
s1 = UserDirectoryService
.getUser(((Member) o1).getUserId()).getSortName();
} catch (Exception ignore) {
}
try {
s2 = UserDirectoryService
.getUser(((Member) o2).getUserId()).getSortName();
} catch (Exception ignore) {
}
result = compareString(s1, s2);
}
if (m_asc == null)
m_asc = Boolean.TRUE.toString();
// sort ascending or descending
if (m_asc.equals(Boolean.FALSE.toString())) {
result = -result;
}
return result;
} // compare
private int compareBoolean(boolean b1, boolean b2) {
int result;
if (b1 == b2) {
result = 0;
} else if (b1 == true) {
result = 1;
} else {
result = -1;
}
return result;
}
private int compareString(String s1, String s2) {
int result;
if (s1 == null && s2 == null) {
result = 0;
} else if (s2 == null) {
result = 1;
} else if (s1 == null) {
result = -1;
} else {
result = collator.compare(s1, s2);
}
return result;
}
} // SiteComparator
private class ToolComparator implements Comparator {
/**
* implementing the Comparator compare function
*
* @param o1
* The first object
* @param o2
* The second object
* @return The compare result. 1 is o1 < o2; 0 is o1.equals(o2); -1
* otherwise
*/
public int compare(Object o1, Object o2) {
try {
return ((Tool) o1).getTitle().compareTo(((Tool) o2).getTitle());
} catch (Exception e) {
}
return -1;
} // compare
} // ToolComparator
public class MyIcon {
protected String m_name = null;
protected String m_url = null;
protected String m_skin = null;
public MyIcon(String name, String url, String skin) {
m_name = name;
m_url = url;
m_skin = skin;
}
public String getName() {
return m_name;
}
public String getUrl() {
return m_url;
}
public String getSkin() {
return m_skin;
}
}
// a utility class for working with ToolConfigurations and ToolRegistrations
// %%% convert featureList from IdAndText to Tool so getFeatures item.id =
// chosen-feature.id is a direct mapping of data
public class MyTool {
public String id = NULL_STRING;
public String title = NULL_STRING;
public String description = NULL_STRING;
public boolean selected = false;
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public boolean getSelected() {
return selected;
}
}
/*
* WorksiteSetupPage is a utility class for working with site pages
* configured by Worksite Setup
*
*/
public class WorksiteSetupPage {
public String pageId = NULL_STRING;
public String pageTitle = NULL_STRING;
public String toolId = NULL_STRING;
public String getPageId() {
return pageId;
}
public String getPageTitle() {
return pageTitle;
}
public String getToolId() {
return toolId;
}
} // WorksiteSetupPage
/**
* Participant in site access roles
*
*/
public class Participant {
public String name = NULL_STRING;
// Note: uniqname is really a user ID
public String uniqname = NULL_STRING;
public String role = NULL_STRING;
/** role from provider */
public String providerRole = NULL_STRING;
/** The member credits */
protected String credits = NULL_STRING;
/** The section */
public String section = NULL_STRING;
private Set sectionEidList;
/** The regestration id */
public String regId = NULL_STRING;
/** removeable if not from provider */
public boolean removeable = true;
/** the status, active vs. inactive */
public boolean active = true;
public String getName() {
return name;
}
public String getUniqname() {
return uniqname;
}
public String getRole() {
return role;
} // cast to Role
public String getProviderRole() {
return providerRole;
}
public boolean isRemoveable() {
return removeable;
}
public boolean isActive() {
return active;
}
// extra info from provider
public String getCredits() {
return credits;
} // getCredits
public String getSection() {
if (sectionEidList == null)
return "";
StringBuilder sb = new StringBuilder();
Iterator it = sectionEidList.iterator();
for (int i = 0; i < sectionEidList.size(); i ++) {
String sectionEid = (String)it.next();
if (i < 0)
sb.append(",<br />");
sb.append(sectionEid);
}
return sb.toString();
} // getSection
public Set getSectionEidList() {
if (sectionEidList == null)
sectionEidList = new HashSet();
return sectionEidList;
}
public void addSectionEidToList(String eid) {
if (sectionEidList == null)
sectionEidList = new HashSet();
sectionEidList.add(eid);
}
public String getRegId() {
return regId;
} // getRegId
/**
* Access the user eid, if we can find it - fall back to the id if not.
*
* @return The user eid.
*/
public String getEid() {
try {
return UserDirectoryService.getUserEid(uniqname);
} catch (UserNotDefinedException e) {
return uniqname;
}
}
/**
* Access the user display id, if we can find it - fall back to the id
* if not.
*
* @return The user display id.
*/
public String getDisplayId() {
try {
User user = UserDirectoryService.getUser(uniqname);
return user.getDisplayId();
} catch (UserNotDefinedException e) {
return uniqname;
}
}
} // Participant
public class SiteInfo {
public String site_id = NULL_STRING; // getId of Resource
public String external_id = NULL_STRING; // if matches site_id
// connects site with U-M
// course information
public String site_type = "";
public String iconUrl = NULL_STRING;
public String infoUrl = NULL_STRING;
public boolean joinable = false;
public String joinerRole = NULL_STRING;
public String title = NULL_STRING; // the short name of the site
public String short_description = NULL_STRING; // the short (20 char)
// description of the
// site
public String description = NULL_STRING; // the longer description of
// the site
public String additional = NULL_STRING; // additional information on
// crosslists, etc.
public boolean published = false;
public boolean include = true; // include the site in the Sites index;
// default is true.
public String site_contact_name = NULL_STRING; // site contact name
public String site_contact_email = NULL_STRING; // site contact email
public String getSiteId() {
return site_id;
}
public String getSiteType() {
return site_type;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getIconUrl() {
return iconUrl;
}
public String getInfoUrll() {
return infoUrl;
}
public boolean getJoinable() {
return joinable;
}
public String getJoinerRole() {
return joinerRole;
}
public String getAdditional() {
return additional;
}
public boolean getPublished() {
return published;
}
public boolean getInclude() {
return include;
}
public String getSiteContactName() {
return site_contact_name;
}
public String getSiteContactEmail() {
return site_contact_email;
}
} // SiteInfo
// dissertation tool related
/**
* doFinish_grad_tools is called when creation of a Grad Tools site is
* confirmed
*/
public void doFinish_grad_tools(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// set up for the coming template
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("continue"));
int index = Integer.valueOf(params.getString("template-index"))
.intValue();
actionForTemplate("continue", index, params, state);
// add the pre-configured Grad Tools tools to a new site
addGradToolsFeatures(state);
// TODO: hard coding this frame id is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
resetPaging(state);
}// doFinish_grad_tools
/**
* addGradToolsFeatures adds features to a new Grad Tools student site
*
*/
private void addGradToolsFeatures(SessionState state) {
Site edit = null;
Site template = null;
// get a unique id
String id = IdManager.createUuid();
// get the Grad Tools student site template
try {
template = SiteService.getSite(SITE_GTS_TEMPLATE);
} catch (Exception e) {
if (Log.isWarnEnabled())
M_log.warn("addGradToolsFeatures template " + e);
}
if (template != null) {
// create a new site based on the template
try {
edit = SiteService.addSite(id, template);
} catch (Exception e) {
if (Log.isWarnEnabled())
M_log.warn("addGradToolsFeatures add/edit site " + e);
}
// set the tab, etc.
if (edit != null) {
SiteInfo siteInfo = (SiteInfo) state
.getAttribute(STATE_SITE_INFO);
edit.setShortDescription(siteInfo.short_description);
edit.setTitle(siteInfo.title);
edit.setPublished(true);
edit.setPubView(false);
edit.setType(SITE_TYPE_GRADTOOLS_STUDENT);
// ResourcePropertiesEdit rpe = edit.getPropertiesEdit();
try {
SiteService.save(edit);
} catch (Exception e) {
if (Log.isWarnEnabled())
M_log.warn("addGradToolsFeartures commitEdit " + e);
}
// now that the site and realm exist, we can set the email alias
// set the GradToolsStudent site alias as:
// gradtools-uniqname@servername
String alias = "gradtools-"
+ SessionManager.getCurrentSessionUserId();
String channelReference = mailArchiveChannelReference(id);
try {
AliasService.setAlias(alias, channelReference);
} catch (IdUsedException ee) {
addAlert(state, rb.getString("java.alias") + " " + alias
+ " " + rb.getString("java.exists"));
} catch (IdInvalidException ee) {
addAlert(state, rb.getString("java.alias") + " " + alias
+ " " + rb.getString("java.isinval"));
} catch (PermissionException ee) {
M_log.warn(SessionManager.getCurrentSessionUserId()
+ " does not have permission to add alias. ");
}
}
}
} // addGradToolsFeatures
/**
* handle with add site options
*
*/
public void doAdd_site_option(RunData data) {
String option = data.getParameters().getString("option");
if (option.equals("finish")) {
doFinish(data);
} else if (option.equals("cancel")) {
doCancel_create(data);
} else if (option.equals("back")) {
doBack(data);
}
} // doAdd_site_option
/**
* handle with duplicate site options
*
*/
public void doDuplicate_site_option(RunData data) {
String option = data.getParameters().getString("option");
if (option.equals("duplicate")) {
doContinue(data);
} else if (option.equals("cancel")) {
doCancel(data);
} else if (option.equals("finish")) {
doContinue(data);
}
} // doDuplicate_site_option
/**
* Special check against the Dissertation service, which might not be
* here...
*
* @return
*/
protected boolean isGradToolsCandidate(String userId) {
// DissertationService.isCandidate(userId) - but the hard way
Object service = ComponentManager
.get("org.sakaiproject.api.app.dissertation.DissertationService");
if (service == null)
return false;
// the method signature
Class[] signature = new Class[1];
signature[0] = String.class;
// the method name
String methodName = "isCandidate";
// find a method of this class with this name and signature
try {
Method method = service.getClass().getMethod(methodName, signature);
// the parameters
Object[] args = new Object[1];
args[0] = userId;
// make the call
Boolean rv = (Boolean) method.invoke(service, args);
return rv.booleanValue();
} catch (Throwable t) {
}
return false;
}
/**
* User has a Grad Tools student site
*
* @return
*/
protected boolean hasGradToolsStudentSite(String userId) {
boolean has = false;
int n = 0;
try {
n = SiteService.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
SITE_TYPE_GRADTOOLS_STUDENT, null, null);
if (n > 0)
has = true;
} catch (Exception e) {
if (Log.isWarnEnabled())
M_log.warn("hasGradToolsStudentSite " + e);
}
return has;
}// hasGradToolsStudentSite
/**
* Get the mail archive channel reference for the main container placement
* for this site.
*
* @param siteId
* The site id.
* @return The mail archive channel reference for this site.
*/
protected String mailArchiveChannelReference(String siteId) {
Object m = ComponentManager
.get("org.sakaiproject.mailarchive.api.MailArchiveService");
if (m != null) {
return "/mailarchive"+Entity.SEPARATOR+"channel"+Entity.SEPARATOR+siteId+Entity.SEPARATOR+SiteService.MAIN_CONTAINER;
} else {
return "";
}
}
/**
* Transfer a copy of all entites from another context for any entity
* producer that claims this tool id.
*
* @param toolId
* The tool id.
* @param fromContext
* The context to import from.
* @param toContext
* The context to import into.
*/
protected void transferCopyEntities(String toolId, String fromContext,
String toContext) {
// TODO: used to offer to resources first - why? still needed? -ggolden
// offer to all EntityProducers
for (Iterator i = EntityManager.getEntityProducers().iterator(); i
.hasNext();) {
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer) {
try {
EntityTransferrer et = (EntityTransferrer) ep;
// if this producer claims this tool id
if (ArrayUtil.contains(et.myToolIds(), toolId)) {
et.transferCopyEntities(fromContext, toContext,
new Vector());
}
} catch (Throwable t) {
M_log.warn(
"Error encountered while asking EntityTransfer to transferCopyEntities from: "
+ fromContext + " to: " + toContext, t);
}
}
}
}
/**
* @return Get a list of all tools that support the import (transfer copy)
* option
*/
protected Set importTools() {
HashSet rv = new HashSet();
// offer to all EntityProducers
for (Iterator i = EntityManager.getEntityProducers().iterator(); i
.hasNext();) {
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer) {
EntityTransferrer et = (EntityTransferrer) ep;
String[] tools = et.myToolIds();
if (tools != null) {
for (int t = 0; t < tools.length; t++) {
rv.add(tools[t]);
}
}
}
}
return rv;
}
/**
* @param state
* @return Get a list of all tools that should be included as options for
* import
*/
protected List getToolsAvailableForImport(SessionState state) {
// The Web Content and News tools do not follow the standard rules for
// import
// Even if the current site does not contain the tool, News and WC will
// be
// an option if the imported site contains it
boolean displayWebContent = false;
boolean displayNews = false;
Set importSites = ((Hashtable) state.getAttribute(STATE_IMPORT_SITES))
.keySet();
Iterator sitesIter = importSites.iterator();
while (sitesIter.hasNext()) {
Site site = (Site) sitesIter.next();
if (site.getToolForCommonId("sakai.iframe") != null)
displayWebContent = true;
if (site.getToolForCommonId("sakai.news") != null)
displayNews = true;
}
List toolsOnImportList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
if (displayWebContent && !toolsOnImportList.contains("sakai.iframe"))
toolsOnImportList.add("sakai.iframe");
if (displayNews && !toolsOnImportList.contains("sakai.news"))
toolsOnImportList.add("sakai.news");
return toolsOnImportList;
} // getToolsAvailableForImport
private void setTermListForContext(Context context, SessionState state,
boolean upcomingOnly) {
List terms;
if (upcomingOnly) {
terms = cms != null?cms.getCurrentAcademicSessions():null;
} else { // get all
terms = cms != null?cms.getAcademicSessions():null;
}
if (terms != null && terms.size() > 0) {
context.put("termList", terms);
}
} // setTermListForContext
private void setSelectedTermForContext(Context context, SessionState state,
String stateAttribute) {
if (state.getAttribute(stateAttribute) != null) {
context.put("selectedTerm", state.getAttribute(stateAttribute));
}
} // setSelectedTermForContext
/**
* rewrote for 2.4
*
* @param userId
* @param academicSessionEid
* @param courseOfferingHash
* @param sectionHash
*/
private void prepareCourseAndSectionMap(String userId,
String academicSessionEid, HashMap courseOfferingHash,
HashMap sectionHash) {
// looking for list of courseOffering and sections that should be
// included in
// the selection list. The course offering must be offered
// 1. in the specific academic Session
// 2. that the specified user has right to attach its section to a
// course site
// map = (section.eid, sakai rolename)
if (groupProvider == null)
{
M_log.warn("Group provider not found");
return;
}
Map map = groupProvider.getGroupRolesForUser(userId);
if (map == null)
return;
Set keys = map.keySet();
Set roleSet = getRolesAllowedToAttachSection();
for (Iterator i = keys.iterator(); i.hasNext();) {
String sectionEid = (String) i.next();
String role = (String) map.get(sectionEid);
if (includeRole(role, roleSet)) {
Section section = null;
getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section);
}
}
// now consider those user with affiliated sections
List affiliatedSectionEids = affiliatedSectionProvider.getAffiliatedSectionEids(userId, academicSessionEid);
if (affiliatedSectionEids != null)
{
for (int k = 0; k < affiliatedSectionEids.size(); k++) {
String sectionEid = (String) affiliatedSectionEids.get(k);
Section section = null;
getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section);
}
}
} // prepareCourseAndSectionMap
private void getCourseOfferingAndSectionMap(String academicSessionEid, HashMap courseOfferingHash, HashMap sectionHash, String sectionEid, Section section) {
try {
section = cms.getSection(sectionEid);
} catch (IdNotFoundException e) {
M_log.warn(e.getMessage());
}
if (section != null) {
String courseOfferingEid = section.getCourseOfferingEid();
CourseOffering courseOffering = cms
.getCourseOffering(courseOfferingEid);
String sessionEid = courseOffering.getAcademicSession()
.getEid();
if (academicSessionEid.equals(sessionEid)) {
// a long way to the conclusion that yes, this course
// offering
// should be included in the selected list. Sigh...
// -daisyf
ArrayList sectionList = (ArrayList) sectionHash
.get(courseOffering.getEid());
if (sectionList == null) {
sectionList = new ArrayList();
}
sectionList.add(new SectionObject(section));
sectionHash.put(courseOffering.getEid(), sectionList);
courseOfferingHash.put(courseOffering.getEid(),
courseOffering);
}
}
}
/**
* for 2.4
*
* @param role
* @return
*/
private boolean includeRole(String role, Set roleSet) {
boolean includeRole = false;
for (Iterator i = roleSet.iterator(); i.hasNext();) {
String r = (String) i.next();
if (r.equals(role)) {
includeRole = true;
break;
}
}
return includeRole;
} // includeRole
protected Set getRolesAllowedToAttachSection() {
// Use !site.template.[site_type]
String azgId = "!site.template.course";
AuthzGroup azgTemplate;
try {
azgTemplate = AuthzGroupService.getAuthzGroup(azgId);
} catch (GroupNotDefinedException e) {
M_log.warn("Could not find authz group " + azgId);
return new HashSet();
}
Set roles = azgTemplate.getRolesIsAllowed("site.upd");
roles.addAll(azgTemplate.getRolesIsAllowed("realm.upd"));
return roles;
} // getRolesAllowedToAttachSection
/**
* Here, we will preapre two HashMap: 1. courseOfferingHash stores
* courseOfferingId and CourseOffering 2. sectionHash stores
* courseOfferingId and a list of its Section We sorted the CourseOffering
* by its eid & title and went through them one at a time to construct the
* CourseObject that is used for the displayed in velocity. Each
* CourseObject will contains a list of CourseOfferingObject(again used for
* vm display). Usually, a CourseObject would only contain one
* CourseOfferingObject. A CourseObject containing multiple
* CourseOfferingObject implies that this is a cross-listing situation.
*
* @param userId
* @param academicSessionEid
* @return
*/
private List prepareCourseAndSectionListing(String userId,
String academicSessionEid, SessionState state) {
// courseOfferingHash = (courseOfferingEid, vourseOffering)
// sectionHash = (courseOfferingEid, list of sections)
HashMap courseOfferingHash = new HashMap();
HashMap sectionHash = new HashMap();
prepareCourseAndSectionMap(userId, academicSessionEid,
courseOfferingHash, sectionHash);
// courseOfferingHash & sectionHash should now be filled with stuffs
// put section list in state for later use
state.setAttribute(STATE_PROVIDER_SECTION_LIST,
getSectionList(sectionHash));
ArrayList offeringList = new ArrayList();
Set keys = courseOfferingHash.keySet();
for (Iterator i = keys.iterator(); i.hasNext();) {
CourseOffering o = (CourseOffering) courseOfferingHash
.get((String) i.next());
offeringList.add(o);
}
Collection offeringListSorted = sortOffering(offeringList);
ArrayList resultedList = new ArrayList();
// use this to keep track of courseOffering that we have dealt with
// already
// this is important 'cos cross-listed offering is dealt with together
// with its
// equivalents
ArrayList dealtWith = new ArrayList();
for (Iterator j = offeringListSorted.iterator(); j.hasNext();) {
CourseOffering o = (CourseOffering) j.next();
if (!dealtWith.contains(o.getEid())) {
// 1. construct list of CourseOfferingObject for CourseObject
ArrayList l = new ArrayList();
CourseOfferingObject coo = new CourseOfferingObject(o,
(ArrayList) sectionHash.get(o.getEid()));
l.add(coo);
// 2. check if course offering is cross-listed
Set set = cms.getEquivalentCourseOfferings(o.getEid());
if (set != null)
{
for (Iterator k = set.iterator(); k.hasNext();) {
CourseOffering eo = (CourseOffering) k.next();
if (courseOfferingHash.containsKey(eo.getEid())) {
// => cross-listed, then list them together
CourseOfferingObject coo_equivalent = new CourseOfferingObject(
eo, (ArrayList) sectionHash.get(eo.getEid()));
l.add(coo_equivalent);
dealtWith.add(eo.getEid());
}
}
}
CourseObject co = new CourseObject(o, l);
dealtWith.add(o.getEid());
resultedList.add(co);
}
}
return resultedList;
} // prepareCourseAndSectionListing
/**
* Sort CourseOffering by order of eid, title uisng velocity SortTool
*
* @param offeringList
* @return
*/
private Collection sortOffering(ArrayList offeringList) {
return sortCmObject(offeringList);
/*
* List propsList = new ArrayList(); propsList.add("eid");
* propsList.add("title"); SortTool sort = new SortTool(); return
* sort.sort(offeringList, propsList);
*/
} // sortOffering
/**
* sort any Cm object such as CourseOffering, CourseOfferingObject,
* SectionObject provided object has getter & setter for eid & title
*
* @param list
* @return
*/
private Collection sortCmObject(List list) {
if (list != null) {
List propsList = new ArrayList();
propsList.add("eid");
propsList.add("title");
SortTool sort = new SortTool();
return sort.sort(list, propsList);
} else {
return list;
}
} // sortCmObject
/**
* this object is used for displaying purposes in chef_site-newSiteCourse.vm
*/
public class SectionObject {
public Section section;
public String eid;
public String title;
public String category;
public String categoryDescription;
public boolean isLecture;
public boolean attached;
public String authorizer;
public SectionObject(Section section) {
this.section = section;
this.eid = section.getEid();
this.title = section.getTitle();
this.category = section.getCategory();
this.categoryDescription = cms
.getSectionCategoryDescription(section.getCategory());
if ("01.lct".equals(section.getCategory())) {
this.isLecture = true;
} else {
this.isLecture = false;
}
Set set = authzGroupService.getAuthzGroupIds(section.getEid());
if (set != null && !set.isEmpty()) {
this.attached = true;
} else {
this.attached = false;
}
}
public Section getSection() {
return section;
}
public String getEid() {
return eid;
}
public String getTitle() {
return title;
}
public String getCategory() {
return category;
}
public String getCategoryDescription() {
return categoryDescription;
}
public boolean getIsLecture() {
return isLecture;
}
public boolean getAttached() {
return attached;
}
public String getAuthorizer() {
return authorizer;
}
public void setAuthorizer(String authorizer) {
this.authorizer = authorizer;
}
} // SectionObject constructor
/**
* this object is used for displaying purposes in chef_site-newSiteCourse.vm
*/
public class CourseObject {
public String eid;
public String title;
public List courseOfferingObjects;
public CourseObject(CourseOffering offering, List courseOfferingObjects) {
this.eid = offering.getEid();
this.title = offering.getTitle();
this.courseOfferingObjects = courseOfferingObjects;
}
public String getEid() {
return eid;
}
public String getTitle() {
return title;
}
public List getCourseOfferingObjects() {
return courseOfferingObjects;
}
} // CourseObject constructor
/**
* this object is used for displaying purposes in chef_site-newSiteCourse.vm
*/
public class CourseOfferingObject {
public String eid;
public String title;
public List sections;
public CourseOfferingObject(CourseOffering offering,
List unsortedSections) {
List propsList = new ArrayList();
propsList.add("category");
propsList.add("eid");
SortTool sort = new SortTool();
this.sections = new ArrayList();
if (unsortedSections != null) {
this.sections = (List) sort.sort(unsortedSections, propsList);
}
this.eid = offering.getEid();
this.title = offering.getTitle();
}
public String getEid() {
return eid;
}
public String getTitle() {
return title;
}
public List getSections() {
return sections;
}
} // CourseOfferingObject constructor
/**
* get campus user directory for dispaly in chef_newSiteCourse.vm
*
* @return
*/
private String getCampusDirectory() {
return ServerConfigurationService.getString(
"site-manage.campusUserDirectory", null);
} // getCampusDirectory
private void removeAnyFlagedSection(SessionState state,
ParameterParser params) {
List all = new ArrayList();
List providerCourseList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (providerCourseList != null && providerCourseList.size() > 0) {
all.addAll(providerCourseList);
}
List manualCourseList = (List) state
.getAttribute(SITE_MANUAL_COURSE_LIST);
if (manualCourseList != null && manualCourseList.size() > 0) {
all.addAll(manualCourseList);
}
for (int i = 0; i < all.size(); i++) {
String eid = (String) all.get(i);
String field = "removeSection" + eid;
String toRemove = params.getString(field);
if ("true".equals(toRemove)) {
// eid is in either providerCourseList or manualCourseList
// either way, just remove it
if (providerCourseList != null)
providerCourseList.remove(eid);
if (manualCourseList != null)
manualCourseList.remove(eid);
}
}
List<SectionObject> requestedCMSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (requestedCMSections != null) {
for (int i = 0; i < requestedCMSections.size(); i++) {
SectionObject so = (SectionObject) requestedCMSections.get(i);
String field = "removeSection" + so.getEid();
String toRemove = params.getString(field);
if ("true".equals(toRemove)) {
requestedCMSections.remove(so);
}
}
if (requestedCMSections.size() == 0)
state.removeAttribute(STATE_CM_REQUESTED_SECTIONS);
}
List<SectionObject> authorizerSections = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (authorizerSections != null) {
for (int i = 0; i < authorizerSections.size(); i++) {
SectionObject so = (SectionObject) authorizerSections.get(i);
String field = "removeSection" + so.getEid();
String toRemove = params.getString(field);
if ("true".equals(toRemove)) {
authorizerSections.remove(so);
}
}
if (authorizerSections.size() == 0)
state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS);
}
// if list is empty, set to null. This is important 'cos null is
// the indication that the list is empty in the code. See case 2 on line
// 1081
if (manualCourseList != null && manualCourseList.size() == 0)
manualCourseList = null;
if (providerCourseList != null && providerCourseList.size() == 0)
providerCourseList = null;
}
private void collectNewSiteInfo(SiteInfo siteInfo, SessionState state,
ParameterParser params, List providerChosenList) {
if (state.getAttribute(STATE_MESSAGE) == null) {
siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
// site title is the title of the 1st section selected -
// daisyf's note
if (providerChosenList != null && providerChosenList.size() >= 1) {
String title = prepareTitle((List) state
.getAttribute(STATE_PROVIDER_SECTION_LIST),
providerChosenList);
siteInfo.title = title;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (params.getString("manualAdds") != null
&& ("true").equals(params.getString("manualAdds"))) {
// if creating a new site
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(
1));
} else if (params.getString("findCourse") != null
&& ("true").equals(params.getString("findCourse"))) {
state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN,
providerChosenList);
prepFindPage(state);
} else {
// no manual add
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
if (getStateSite(state) != null) {
// if revising a site, go to the confirmation
// page of adding classes
//state.setAttribute(STATE_TEMPLATE_INDEX, "37");
} else {
// if creating a site, go the the site
// information entry page
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
}
}
}
}
/**
* By default, courseManagement is implemented
*
* @return
*/
private boolean courseManagementIsImplemented() {
boolean returnValue = true;
String isImplemented = ServerConfigurationService.getString(
"site-manage.courseManagementSystemImplemented", "true");
if (("false").equals(isImplemented))
returnValue = false;
return returnValue;
}
private List getCMSections(String offeringEid) {
if (offeringEid == null || offeringEid.trim().length() == 0)
return null;
if (cms != null) {
Set sections = cms.getSections(offeringEid);
Collection c = sortCmObject(new ArrayList(sections));
return (List) c;
}
return new ArrayList(0);
}
private List getCMCourseOfferings(String subjectEid, String termID) {
if (subjectEid == null || subjectEid.trim().length() == 0
|| termID == null || termID.trim().length() == 0)
return null;
if (cms != null) {
Set offerings = cms.getCourseOfferingsInCourseSet(subjectEid);// ,
// termID);
ArrayList returnList = new ArrayList();
Iterator coIt = offerings.iterator();
while (coIt.hasNext()) {
CourseOffering co = (CourseOffering) coIt.next();
AcademicSession as = co.getAcademicSession();
if (as != null && as.getEid().equals(termID))
returnList.add(co);
}
Collection c = sortCmObject(returnList);
return (List) c;
}
return new ArrayList(0);
}
private List<String> getCMLevelLabels() {
List<String> rv = new Vector<String>();
Set courseSets = cms.getCourseSets();
String currentLevel = "";
rv = addCategories(rv, courseSets);
// course and section exist in the CourseManagementService
rv.add(rb.getString("cm.level.course"));
rv.add(rb.getString("cm.level.section"));
return rv;
}
/**
* a recursive function to add courseset categories
* @param rv
* @param courseSets
*/
private List<String> addCategories(List<String> rv, Set courseSets) {
if (courseSets != null)
{
for (Iterator i = courseSets.iterator(); i.hasNext();)
{
// get the CourseSet object level
CourseSet cs = (CourseSet) i.next();
String level = cs.getCategory();
if (!rv.contains(level))
{
rv.add(level);
}
try
{
// recursively add child categories
rv = addCategories(rv, cms.getChildCourseSets(cs.getEid()));
}
catch (IdNotFoundException e)
{
// current CourseSet not found
}
}
}
return rv;
}
private void prepFindPage(SessionState state) {
final List cmLevels = getCMLevelLabels(), selections = (List) state
.getAttribute(STATE_CM_LEVEL_SELECTIONS);
int lvlSz = 0;
if (cmLevels == null || (lvlSz = cmLevels.size()) < 1) {
// TODO: no cm levels configured, redirect to manual add
return;
}
if (selections != null && selections.size() == lvlSz) {
Section sect = cms.getSection((String) selections.get(selections
.size() - 1));
SectionObject so = new SectionObject(sect);
state.setAttribute(STATE_CM_SELECTED_SECTION, so);
} else
state.removeAttribute(STATE_CM_SELECTED_SECTION);
state.setAttribute(STATE_CM_LEVELS, cmLevels);
state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections);
// check the configuration setting for choosing next screen
Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean("wsetup.skipCourseSectionSelection", Boolean.FALSE);
if (!skipCourseSectionSelection.booleanValue())
{
// go to the course/section selection page
state.setAttribute(STATE_TEMPLATE_INDEX, "53");
}
else
{
// skip the course/section selection page, go directly into the manually create course page
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
}
}
private void addRequestedSection(SessionState state) {
SectionObject so = (SectionObject) state
.getAttribute(STATE_CM_SELECTED_SECTION);
String uniqueName = (String) state
.getAttribute(STATE_SITE_QUEST_UNIQNAME);
if (so == null)
return;
so.setAuthorizer(uniqueName);
if (getStateSite(state) == null)
{
// creating new site
List<SectionObject> requestedSections = (List<SectionObject>) state.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (requestedSections == null) {
requestedSections = new ArrayList<SectionObject>();
}
// don't add duplicates
if (!requestedSections.contains(so))
requestedSections.add(so);
// if the title has not yet been set and there is just
// one section, set the title to that section's EID
if (requestedSections.size() == 1) {
SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteInfo == null) {
siteInfo = new SiteInfo();
}
if (siteInfo.title == null || siteInfo.title.trim().length() == 0) {
siteInfo.title = so.getEid();
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
state.setAttribute(STATE_CM_REQUESTED_SECTIONS, requestedSections);
state.removeAttribute(STATE_CM_SELECTED_SECTION);
}
else
{
// editing site
state.setAttribute(STATE_CM_SELECTED_SECTION, so);
List<SectionObject> cmSelectedSections = (List<SectionObject>) state.getAttribute(STATE_CM_SELECTED_SECTIONS);
if (cmSelectedSections == null) {
cmSelectedSections = new ArrayList<SectionObject>();
}
// don't add duplicates
if (!cmSelectedSections.contains(so))
cmSelectedSections.add(so);
state.setAttribute(STATE_CM_SELECTED_SECTIONS, cmSelectedSections);
state.removeAttribute(STATE_CM_SELECTED_SECTION);
}
state.removeAttribute(STATE_CM_LEVEL_SELECTIONS);
}
public void doFind_course(RunData data) {
final SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
final ParameterParser params = data.getParameters();
final String option = params.get("option");
if (option != null)
{
if ("continue".equals(option))
{
String uniqname = StringUtil.trimToNull(params
.getString("uniqname"));
state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname);
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& !((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue())
{
// if a future term is selected, do not check authorization
// uniqname
if (uniqname == null)
{
addAlert(state, rb.getString("java.author")
+ " "
+ ServerConfigurationService
.getString("officialAccountName")
+ ". ");
}
else
{
try
{
UserDirectoryService.getUserByEid(uniqname);
addRequestedSection(state);
}
catch (UserNotDefinedException e)
{
addAlert(
state,
rb.getString("java.validAuthor1")
+ " "
+ ServerConfigurationService
.getString("officialAccountName")
+ " "
+ rb.getString("java.validAuthor2"));
}
}
}
else
{
addRequestedSection(state);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
if (getStateSite(state) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
}
}
doContinue(data);
return;
} else if ("back".equals(option)) {
doBack(data);
return;
} else if ("cancel".equals(option)) {
if (getStateSite(state) == null)
{
doCancel_create(data);// cancel from new site creation
}
else
{
doCancel(data);// cancel from site info editing
}
return;
} else if (option.equals("add")) {
addRequestedSection(state);
return;
} else if (option.equals("manual")) {
// TODO: send to case 37
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(
1));
return;
} else if (option.equals("remove"))
removeAnyFlagedSection(state, params);
}
final List selections = new ArrayList(3);
int cmLevel = getCMLevelLabels().size();
String deptChanged = params.get("deptChanged");
if ("true".equals(deptChanged)) {
// when dept changes, remove selection on courseOffering and
// courseSection
cmLevel = 1;
}
for (int i = 0; i < cmLevel; i++) {
String val = params.get("idField_" + i);
if (val == null || val.trim().length() < 1) {
break;
}
selections.add(val);
}
state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections);
prepFindPage(state);
}
/**
* return the title of the 1st section in the chosen list that has an
* enrollment set. No discrimination on section category
*
* @param sectionList
* @param chosenList
* @return
*/
private String prepareTitle(List sectionList, List chosenList) {
String title = null;
HashMap map = new HashMap();
for (Iterator i = sectionList.iterator(); i.hasNext();) {
SectionObject o = (SectionObject) i.next();
map.put(o.getEid(), o.getSection());
}
for (int j = 0; j < chosenList.size(); j++) {
String eid = (String) chosenList.get(j);
Section s = (Section) map.get(eid);
// we will always has a title regardless but we prefer it to be the
// 1st section on the chosen list that has an enrollment set
if (j == 0) {
title = s.getTitle();
}
if (s.getEnrollmentSet() != null) {
title = s.getTitle();
break;
}
}
return title;
} // prepareTitle
/**
* return an ArrayList of SectionObject
*
* @param sectionHash
* contains an ArrayList collection of SectionObject
* @return
*/
private ArrayList getSectionList(HashMap sectionHash) {
ArrayList list = new ArrayList();
// values is an ArrayList of section
Collection c = sectionHash.values();
for (Iterator i = c.iterator(); i.hasNext();) {
ArrayList l = (ArrayList) i.next();
list.addAll(l);
}
return list;
}
private String getAuthorizers(SessionState state) {
String authorizers = "";
ArrayList list = (ArrayList) state
.getAttribute(STATE_CM_AUTHORIZER_LIST);
if (list != null) {
for (int i = 0; i < list.size(); i++) {
if (i == 0) {
authorizers = (String) list.get(i);
} else {
authorizers = authorizers + ", " + list.get(i);
}
}
}
return authorizers;
}
private List prepareSectionObject(List sectionList, String userId) {
ArrayList list = new ArrayList();
if (sectionList != null) {
for (int i = 0; i < sectionList.size(); i++) {
String sectionEid = (String) sectionList.get(i);
Section s = cms.getSection(sectionEid);
SectionObject so = new SectionObject(s);
so.setAuthorizer(userId);
list.add(so);
}
}
return list;
}
/**
* change collection object to list object
* @param c
* @return
*/
private List collectionToList(Collection c)
{
List rv = new Vector();
if (c!=null)
{
for (Iterator i = c.iterator(); i.hasNext();)
{
rv.add(i.next());
}
}
return rv;
}
}
| site-manage/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.sakaiproject.site.tool;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Random;
import java.util.Set;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.tools.generic.SortTool;
import org.sakaiproject.alias.api.Alias;
import org.sakaiproject.alias.cover.AliasService;
import org.sakaiproject.archive.api.ImportMetadata;
import org.sakaiproject.archive.cover.ArchiveService;
import org.sakaiproject.authz.api.AuthzGroup;
import org.sakaiproject.authz.api.AuthzPermissionException;
import org.sakaiproject.authz.api.GroupNotDefinedException;
import org.sakaiproject.authz.api.Member;
import org.sakaiproject.authz.api.PermissionsHelper;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.authz.cover.AuthzGroupService;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceActionII;
import org.sakaiproject.cheftool.PortletConfig;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.api.Menu;
import org.sakaiproject.cheftool.api.MenuItem;
import org.sakaiproject.cheftool.menu.MenuEntry;
import org.sakaiproject.cheftool.menu.MenuImpl;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.cover.ContentHostingService;
import org.sakaiproject.coursemanagement.api.AcademicSession;
import org.sakaiproject.coursemanagement.api.CourseOffering;
import org.sakaiproject.coursemanagement.api.CourseSet;
import org.sakaiproject.coursemanagement.api.Enrollment;
import org.sakaiproject.coursemanagement.api.EnrollmentSet;
import org.sakaiproject.coursemanagement.api.Membership;
import org.sakaiproject.coursemanagement.api.Section;
import org.sakaiproject.coursemanagement.api.exception.IdNotFoundException;
import org.sakaiproject.email.cover.EmailService;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.EntityProducer;
import org.sakaiproject.entity.api.EntityPropertyNotDefinedException;
import org.sakaiproject.entity.api.EntityPropertyTypeException;
import org.sakaiproject.entity.api.EntityTransferrer;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.ImportException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.id.cover.IdManager;
import org.sakaiproject.importer.api.ImportDataSource;
import org.sakaiproject.importer.api.ImportService;
import org.sakaiproject.importer.api.SakaiArchive;
import org.sakaiproject.javax.PagingPosition;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SitePage;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.site.api.SiteService.SortType;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.sitemanage.api.SectionField;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserAlreadyDefinedException;
import org.sakaiproject.user.api.UserEdit;
import org.sakaiproject.user.api.UserIdInvalidException;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.api.UserPermissionException;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.ArrayUtil;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.SortedIterator;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
/**
* <p>
* SiteAction controls the interface for worksite setup.
* </p>
*/
public class SiteAction extends PagedResourceActionII {
/** Our logger. */
private static Log M_log = LogFactory.getLog(SiteAction.class);
private ImportService importService = org.sakaiproject.importer.cover.ImportService
.getInstance();
/** portlet configuration parameter values* */
/** Resource bundle using current language locale */
private static ResourceLoader rb = new ResourceLoader("sitesetupgeneric");
private org.sakaiproject.coursemanagement.api.CourseManagementService cms = (org.sakaiproject.coursemanagement.api.CourseManagementService) ComponentManager
.get(org.sakaiproject.coursemanagement.api.CourseManagementService.class);
private org.sakaiproject.authz.api.GroupProvider groupProvider = (org.sakaiproject.authz.api.GroupProvider) ComponentManager
.get(org.sakaiproject.authz.api.GroupProvider.class);
private org.sakaiproject.authz.api.AuthzGroupService authzGroupService = (org.sakaiproject.authz.api.AuthzGroupService) ComponentManager
.get(org.sakaiproject.authz.api.AuthzGroupService.class);
private org.sakaiproject.sitemanage.api.SectionFieldProvider sectionFieldProvider = (org.sakaiproject.sitemanage.api.SectionFieldProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.SectionFieldProvider.class);
private org.sakaiproject.sitemanage.api.AffiliatedSectionProvider affiliatedSectionProvider = (org.sakaiproject.sitemanage.api.AffiliatedSectionProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.AffiliatedSectionProvider.class);
private org.sakaiproject.sitemanage.api.UserNotificationProvider userNotificationProvider = (org.sakaiproject.sitemanage.api.UserNotificationProvider) ComponentManager
.get(org.sakaiproject.sitemanage.api.UserNotificationProvider.class);
private static final String SITE_MODE_SITESETUP = "sitesetup";
private static final String SITE_MODE_SITEINFO = "siteinfo";
private static final String STATE_SITE_MODE = "site_mode";
protected final static String[] TEMPLATE = {
"-list",// 0
"-type",
"-newSiteInformation",
"-newSiteFeatures",
"-addRemoveFeature",
"-addParticipant",
"",
"",
"-siteDeleteConfirm",
"",
"-newSiteConfirm",// 10
"",
"-siteInfo-list",// 12
"-siteInfo-editInfo",
"-siteInfo-editInfoConfirm",
"-addRemoveFeatureConfirm",// 15
"",
"",
"-siteInfo-editAccess",
"-addParticipant-sameRole",
"-addParticipant-differentRole",// 20
"-addParticipant-notification",
"-addParticipant-confirm",
"",
"",
"",// 25
"-modifyENW",
"-importSites",
"-siteInfo-import",
"-siteInfo-duplicate",
"",// 30
"",// 31
"",// 32
"",// 33
"",// 34
"",// 35
"-newSiteCourse",// 36
"-newSiteCourseManual",// 37
"",// 38
"",// 39
"",// 40
"",// 41
"-gradtoolsConfirm",// 42
"-siteInfo-editClass",// 43
"-siteInfo-addCourseConfirm",// 44
"-siteInfo-importMtrlMaster", // 45 -- htripath for import
// material from a file
"-siteInfo-importMtrlCopy", // 46
"-siteInfo-importMtrlCopyConfirm",
"-siteInfo-importMtrlCopyConfirmMsg", // 48
"-siteInfo-group", // 49
"-siteInfo-groupedit", // 50
"-siteInfo-groupDeleteConfirm", // 51,
"",
"-findCourse" // 53
};
/** Name of state attribute for Site instance id */
private static final String STATE_SITE_INSTANCE_ID = "site.instance.id";
/** Name of state attribute for Site Information */
private static final String STATE_SITE_INFO = "site.info";
/** Name of state attribute for CHEF site type */
private static final String STATE_SITE_TYPE = "site-type";
/** Name of state attribute for poissible site types */
private static final String STATE_SITE_TYPES = "site_types";
private static final String STATE_DEFAULT_SITE_TYPE = "default_site_type";
private static final String STATE_PUBLIC_CHANGEABLE_SITE_TYPES = "changeable_site_types";
private static final String STATE_PUBLIC_SITE_TYPES = "public_site_types";
private static final String STATE_PRIVATE_SITE_TYPES = "private_site_types";
private static final String STATE_DISABLE_JOINABLE_SITE_TYPE = "disable_joinable_site_types";
// Names of state attributes corresponding to properties of a site
private final static String PROP_SITE_CONTACT_EMAIL = "contact-email";
private final static String PROP_SITE_CONTACT_NAME = "contact-name";
private final static String PROP_SITE_TERM = "term";
private final static String PROP_SITE_TERM_EID = "term_eid";
/**
* Name of the state attribute holding the site list column list is sorted
* by
*/
private static final String SORTED_BY = "site.sorted.by";
/** the list of criteria for sorting */
private static final String SORTED_BY_TITLE = "title";
private static final String SORTED_BY_DESCRIPTION = "description";
private static final String SORTED_BY_TYPE = "type";
private static final String SORTED_BY_STATUS = "status";
private static final String SORTED_BY_CREATION_DATE = "creationdate";
private static final String SORTED_BY_JOINABLE = "joinable";
private static final String SORTED_BY_PARTICIPANT_NAME = "participant_name";
private static final String SORTED_BY_PARTICIPANT_UNIQNAME = "participant_uniqname";
private static final String SORTED_BY_PARTICIPANT_ROLE = "participant_role";
private static final String SORTED_BY_PARTICIPANT_ID = "participant_id";
private static final String SORTED_BY_PARTICIPANT_COURSE = "participant_course";
private static final String SORTED_BY_PARTICIPANT_CREDITS = "participant_credits";
private static final String SORTED_BY_PARTICIPANT_STATUS = "participant_status";
private static final String SORTED_BY_MEMBER_NAME = "member_name";
/** Name of the state attribute holding the site list column to sort by */
private static final String SORTED_ASC = "site.sort.asc";
/** State attribute for list of sites to be deleted. */
private static final String STATE_SITE_REMOVALS = "site.removals";
/** Name of the state attribute holding the site list View selected */
private static final String STATE_VIEW_SELECTED = "site.view.selected";
/** Names of lists related to tools */
private static final String STATE_TOOL_REGISTRATION_LIST = "toolRegistrationList";
private static final String STATE_TOOL_REGISTRATION_SELECTED_LIST = "toolRegistrationSelectedList";
private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST = "toolRegistrationOldSelectedList";
private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME = "toolRegistrationOldSelectedHome";
private static final String STATE_TOOL_EMAIL_ADDRESS = "toolEmailAddress";
private static final String STATE_TOOL_HOME_SELECTED = "toolHomeSelected";
private static final String STATE_PROJECT_TOOL_LIST = "projectToolList";
private final static String STATE_MULTIPLE_TOOL_ID_SET = "multipleToolIdSet";
private final static String STATE_MULTIPLE_TOOL_ID_TITLE_MAP = "multipleToolIdTitleMap";
private final static String SITE_DEFAULT_LIST = ServerConfigurationService
.getString("site.types");
private final static String STATE_SITE_QUEST_UNIQNAME = "site_quest_uniqname";
private static final String STATE_SITE_ADD_COURSE = "canAddCourse";
// %%% get rid of the IdAndText tool lists and just use ToolConfiguration or
// ToolRegistration lists
// %%% same for CourseItems
// Names for other state attributes that are lists
private final static String STATE_WORKSITE_SETUP_PAGE_LIST = "wSetupPageList"; // the
// list
// of
// site
// pages
// consistent
// with
// Worksite
// Setup
// page
// patterns
/**
* The name of the state form field containing additional information for a
* course request
*/
private static final String FORM_ADDITIONAL = "form.additional";
/** %%% in transition from putting all form variables in state */
private final static String FORM_TITLE = "form_title";
private final static String FORM_DESCRIPTION = "form_description";
private final static String FORM_HONORIFIC = "form_honorific";
private final static String FORM_INSTITUTION = "form_institution";
private final static String FORM_SUBJECT = "form_subject";
private final static String FORM_PHONE = "form_phone";
private final static String FORM_EMAIL = "form_email";
private final static String FORM_REUSE = "form_reuse";
private final static String FORM_RELATED_CLASS = "form_related_class";
private final static String FORM_RELATED_PROJECT = "form_related_project";
private final static String FORM_NAME = "form_name";
private final static String FORM_SHORT_DESCRIPTION = "form_short_description";
private final static String FORM_ICON_URL = "iconUrl";
/** site info edit form variables */
private final static String FORM_SITEINFO_TITLE = "siteinfo_title";
private final static String FORM_SITEINFO_TERM = "siteinfo_term";
private final static String FORM_SITEINFO_DESCRIPTION = "siteinfo_description";
private final static String FORM_SITEINFO_SHORT_DESCRIPTION = "siteinfo_short_description";
private final static String FORM_SITEINFO_SKIN = "siteinfo_skin";
private final static String FORM_SITEINFO_INCLUDE = "siteinfo_include";
private final static String FORM_SITEINFO_ICON_URL = "siteinfo_icon_url";
private final static String FORM_SITEINFO_CONTACT_NAME = "siteinfo_contact_name";
private final static String FORM_SITEINFO_CONTACT_EMAIL = "siteinfo_contact_email";
private final static String FORM_WILL_NOTIFY = "form_will_notify";
/** Context action */
private static final String CONTEXT_ACTION = "SiteAction";
/** The name of the Attribute for display template index */
private static final String STATE_TEMPLATE_INDEX = "site.templateIndex";
/** State attribute for state initialization. */
private static final String STATE_INITIALIZED = "site.initialized";
/** The action for menu */
private static final String STATE_ACTION = "site.action";
/** The user copyright string */
private static final String STATE_MY_COPYRIGHT = "resources.mycopyright";
/** The copyright character */
private static final String COPYRIGHT_SYMBOL = "copyright (c)";
/** The null/empty string */
private static final String NULL_STRING = "";
/** The state attribute alerting user of a sent course request */
private static final String REQUEST_SENT = "site.request.sent";
/** The state attributes in the make public vm */
private static final String STATE_JOINABLE = "state_joinable";
private static final String STATE_JOINERROLE = "state_joinerRole";
/** the list of selected user */
private static final String STATE_SELECTED_USER_LIST = "state_selected_user_list";
private static final String STATE_SELECTED_PARTICIPANT_ROLES = "state_selected_participant_roles";
private static final String STATE_SELECTED_PARTICIPANTS = "state_selected_participants";
private static final String STATE_PARTICIPANT_LIST = "state_participant_list";
private static final String STATE_ADD_PARTICIPANTS = "state_add_participants";
/** for changing participant roles */
private static final String STATE_CHANGEROLE_SAMEROLE = "state_changerole_samerole";
private static final String STATE_CHANGEROLE_SAMEROLE_ROLE = "state_changerole_samerole_role";
/** for remove user */
private static final String STATE_REMOVEABLE_USER_LIST = "state_removeable_user_list";
private static final String STATE_IMPORT = "state_import";
private static final String STATE_IMPORT_SITES = "state_import_sites";
private static final String STATE_IMPORT_SITE_TOOL = "state_import_site_tool";
/** for navigating between sites in site list */
private static final String STATE_SITES = "state_sites";
private static final String STATE_PREV_SITE = "state_prev_site";
private static final String STATE_NEXT_SITE = "state_next_site";
/** for course information */
private final static String STATE_TERM_COURSE_LIST = "state_term_course_list";
private final static String STATE_TERM_COURSE_HASH = "state_term_course_hash";
private final static String STATE_TERM_SELECTED = "state_term_selected";
private final static String STATE_INSTRUCTOR_SELECTED = "state_instructor_selected";
private final static String STATE_FUTURE_TERM_SELECTED = "state_future_term_selected";
private final static String STATE_ADD_CLASS_PROVIDER = "state_add_class_provider";
private final static String STATE_ADD_CLASS_PROVIDER_CHOSEN = "state_add_class_provider_chosen";
private final static String STATE_ADD_CLASS_MANUAL = "state_add_class_manual";
private final static String STATE_AUTO_ADD = "state_auto_add";
private final static String STATE_MANUAL_ADD_COURSE_NUMBER = "state_manual_add_course_number";
private final static String STATE_MANUAL_ADD_COURSE_FIELDS = "state_manual_add_course_fields";
public final static String PROP_SITE_REQUEST_COURSE = "site-request-course-sections";
public final static String SITE_PROVIDER_COURSE_LIST = "site_provider_course_list";
public final static String SITE_MANUAL_COURSE_LIST = "site_manual_course_list";
private final static String STATE_SUBJECT_AFFILIATES = "site.subject.affiliates";
private final static String STATE_ICONS = "icons";
// site template used to create a UM Grad Tools student site
public static final String SITE_GTS_TEMPLATE = "!gtstudent";
// the type used to identify a UM Grad Tools student site
public static final String SITE_TYPE_GRADTOOLS_STUDENT = "GradToolsStudent";
// list of UM Grad Tools site types for editing
public static final String GRADTOOLS_SITE_TYPES = "gradtools_site_types";
public static final String SITE_DUPLICATED = "site_duplicated";
public static final String SITE_DUPLICATED_NAME = "site_duplicated_named";
// used for site creation wizard title
public static final String SITE_CREATE_TOTAL_STEPS = "site_create_total_steps";
public static final String SITE_CREATE_CURRENT_STEP = "site_create_current_step";
// types of site whose title can be editable
public static final String TITLE_EDITABLE_SITE_TYPE = "title_editable_site_type";
// types of site where site view roster permission is editable
public static final String EDIT_VIEW_ROSTER_SITE_TYPE = "edit_view_roster_site_type";
// htripath : for import material from file - classic import
private static final String ALL_ZIP_IMPORT_SITES = "allzipImports";
private static final String FINAL_ZIP_IMPORT_SITES = "finalzipImports";
private static final String DIRECT_ZIP_IMPORT_SITES = "directzipImports";
private static final String CLASSIC_ZIP_FILE_NAME = "classicZipFileName";
private static final String SESSION_CONTEXT_ID = "sessionContextId";
// page size for worksite setup tool
private static final String STATE_PAGESIZE_SITESETUP = "state_pagesize_sitesetup";
// page size for site info tool
private static final String STATE_PAGESIZE_SITEINFO = "state_pagesize_siteinfo";
// group info
private static final String STATE_GROUP_INSTANCE_ID = "state_group_instance_id";
private static final String STATE_GROUP_TITLE = "state_group_title";
private static final String STATE_GROUP_DESCRIPTION = "state_group_description";
private static final String STATE_GROUP_MEMBERS = "state_group_members";
private static final String STATE_GROUP_REMOVE = "state_group_remove";
private static final String GROUP_PROP_WSETUP_CREATED = "group_prop_wsetup_created";
private static final String IMPORT_DATA_SOURCE = "import_data_source";
private static final String EMAIL_CHAR = "@";
// Special tool id for Home page
private static final String HOME_TOOL_ID = "home";
private static final String STATE_CM_LEVELS = "site.cm.levels";
private static final String STATE_CM_LEVEL_OPTS = "site.cm.level_opts";
private static final String STATE_CM_LEVEL_SELECTIONS = "site.cm.level.selections";
private static final String STATE_CM_SELECTED_SECTION = "site.cm.selectedSection";
private static final String STATE_CM_REQUESTED_SECTIONS = "site.cm.requested";
private static final String STATE_CM_SELECTED_SECTIONS = "site.cm.selectedSections";
private static final String STATE_PROVIDER_SECTION_LIST = "site_provider_section_list";
private static final String STATE_CM_CURRENT_USERID = "site_cm_current_userId";
private static final String STATE_CM_AUTHORIZER_LIST = "site_cm_authorizer_list";
private static final String STATE_CM_AUTHORIZER_SECTIONS = "site_cm_authorizer_sections";
private String cmSubjectCategory;
private boolean warnedNoSubjectCategory = false;
// the string marks the protocol part in url
private static final String PROTOCOL_STRING = "://";
private static final String TOOL_ID_SUMMARY_CALENDAR = "sakai.summary.calendar";
// the string for course site type
private static final String STATE_COURSE_SITE_TYPE = "state_course_site_type";
/**
* Populate the state object, if needed.
*/
protected void initState(SessionState state, VelocityPortlet portlet,
JetspeedRunData rundata) {
super.initState(state, portlet, rundata);
// store current userId in state
User user = UserDirectoryService.getCurrentUser();
String userId = user.getEid();
state.setAttribute(STATE_CM_CURRENT_USERID, userId);
PortletConfig config = portlet.getPortletConfig();
// types of sites that can either be public or private
String changeableTypes = StringUtil.trimToNull(config
.getInitParameter("publicChangeableSiteTypes"));
if (state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES) == null) {
if (changeableTypes != null) {
state
.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES,
new ArrayList(Arrays.asList(changeableTypes
.split(","))));
} else {
state.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES,
new Vector());
}
}
// type of sites that are always public
String publicTypes = StringUtil.trimToNull(config
.getInitParameter("publicSiteTypes"));
if (state.getAttribute(STATE_PUBLIC_SITE_TYPES) == null) {
if (publicTypes != null) {
state.setAttribute(STATE_PUBLIC_SITE_TYPES, new ArrayList(
Arrays.asList(publicTypes.split(","))));
} else {
state.setAttribute(STATE_PUBLIC_SITE_TYPES, new Vector());
}
}
// types of sites that are always private
String privateTypes = StringUtil.trimToNull(config
.getInitParameter("privateSiteTypes"));
if (state.getAttribute(STATE_PRIVATE_SITE_TYPES) == null) {
if (privateTypes != null) {
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new ArrayList(
Arrays.asList(privateTypes.split(","))));
} else {
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector());
}
}
// default site type
String defaultType = StringUtil.trimToNull(config
.getInitParameter("defaultSiteType"));
if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) == null) {
if (defaultType != null) {
state.setAttribute(STATE_DEFAULT_SITE_TYPE, defaultType);
} else {
state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector());
}
}
// certain type(s) of site cannot get its "joinable" option set
if (state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE) == null) {
if (ServerConfigurationService
.getStrings("wsetup.disable.joinable") != null) {
state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE,
new ArrayList(Arrays.asList(ServerConfigurationService
.getStrings("wsetup.disable.joinable"))));
} else {
state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE,
new Vector());
}
}
// course site type
if (state.getAttribute(STATE_COURSE_SITE_TYPE) == null)
{
state.setAttribute(STATE_COURSE_SITE_TYPE, ServerConfigurationService.getString("courseSiteType", "course"));
}
if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) {
state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0));
}
// skins if any
if (state.getAttribute(STATE_ICONS) == null) {
setupIcons(state);
}
if (state.getAttribute(GRADTOOLS_SITE_TYPES) == null) {
List gradToolsSiteTypes = new Vector();
if (ServerConfigurationService.getStrings("gradToolsSiteType") != null) {
gradToolsSiteTypes = new ArrayList(Arrays
.asList(ServerConfigurationService
.getStrings("gradToolsSiteType")));
}
state.setAttribute(GRADTOOLS_SITE_TYPES, gradToolsSiteTypes);
}
if (ServerConfigurationService.getStrings("titleEditableSiteType") != null) {
state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new ArrayList(Arrays
.asList(ServerConfigurationService
.getStrings("titleEditableSiteType"))));
} else {
state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new Vector());
}
if (state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE) == null) {
List siteTypes = new Vector();
if (ServerConfigurationService.getStrings("editViewRosterSiteType") != null) {
siteTypes = new ArrayList(Arrays
.asList(ServerConfigurationService
.getStrings("editViewRosterSiteType")));
}
state.setAttribute(EDIT_VIEW_ROSTER_SITE_TYPE, siteTypes);
}
// get site tool mode from tool registry
String site_mode = portlet.getPortletConfig().getInitParameter(
STATE_SITE_MODE);
state.setAttribute(STATE_SITE_MODE, site_mode);
} // initState
/**
* cleanState removes the current site instance and it's properties from
* state
*/
private void cleanState(SessionState state) {
state.removeAttribute(STATE_SITE_INSTANCE_ID);
state.removeAttribute(STATE_SITE_INFO);
state.removeAttribute(STATE_SITE_TYPE);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
state.removeAttribute(STATE_TOOL_HOME_SELECTED);
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_JOINABLE);
state.removeAttribute(STATE_JOINERROLE);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
state.removeAttribute(STATE_IMPORT);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
// remove those state attributes related to course site creation
state.removeAttribute(STATE_TERM_COURSE_LIST);
state.removeAttribute(STATE_TERM_COURSE_HASH);
state.removeAttribute(STATE_TERM_SELECTED);
state.removeAttribute(STATE_INSTRUCTOR_SELECTED);
state.removeAttribute(STATE_FUTURE_TERM_SELECTED);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_ADD_CLASS_MANUAL);
state.removeAttribute(STATE_AUTO_ADD);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(SITE_CREATE_TOTAL_STEPS);
state.removeAttribute(SITE_CREATE_CURRENT_STEP);
state.removeAttribute(STATE_PROVIDER_SECTION_LIST);
state.removeAttribute(STATE_CM_LEVELS);
state.removeAttribute(STATE_CM_LEVEL_SELECTIONS);
state.removeAttribute(STATE_CM_SELECTED_SECTION);
state.removeAttribute(STATE_CM_REQUESTED_SECTIONS);
state.removeAttribute(STATE_CM_CURRENT_USERID);
state.removeAttribute(STATE_CM_AUTHORIZER_LIST);
state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS);
state.removeAttribute(FORM_ADDITIONAL); // don't we need to clena this
// too? -daisyf
} // cleanState
/**
* Fire up the permissions editor
*/
public void doPermissions(RunData data, Context context) {
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String contextString = ToolManager.getCurrentPlacement().getContext();
String siteRef = SiteService.siteReference(contextString);
// if it is in Worksite setup tool, pass the selected site's reference
if (state.getAttribute(STATE_SITE_MODE) != null
&& ((String) state.getAttribute(STATE_SITE_MODE))
.equals(SITE_MODE_SITESETUP)) {
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) {
Site s = getStateSite(state);
if (s != null) {
siteRef = s.getReference();
}
}
}
// setup for editing the permissions of the site for this tool, using
// the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb
.getString("setperfor")
+ " " + SiteService.getSiteDisplay(contextString));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "site.");
} // doPermissions
/**
* Build the context for normal display
*/
public String buildMainPanelContext(VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
context.put("tlang", rb);
// TODO: what is all this doing? if we are in helper mode, we are
// already setup and don't get called here now -ggolden
/*
* String helperMode = (String)
* state.getAttribute(PermissionsAction.STATE_MODE); if (helperMode !=
* null) { Site site = getStateSite(state); if (site != null) { if
* (site.getType() != null && ((List)
* state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE)).contains(site.getType())) {
* context.put("editViewRoster", Boolean.TRUE); } else {
* context.put("editViewRoster", Boolean.FALSE); } } else {
* context.put("editViewRoster", Boolean.FALSE); } // for new, don't
* show site.del in Permission page context.put("hiddenLock",
* "site.del");
*
* String template = PermissionsAction.buildHelperContext(portlet,
* context, data, state); if (template == null) { addAlert(state,
* rb.getString("theisa")); } else { return template; } }
*/
String template = null;
context.put("action", CONTEXT_ACTION);
// updatePortlet(state, portlet, data);
if (state.getAttribute(STATE_INITIALIZED) == null) {
init(portlet, data, state);
}
int index = Integer.valueOf(
(String) state.getAttribute(STATE_TEMPLATE_INDEX)).intValue();
template = buildContextForTemplate(index, portlet, context, data, state);
return template;
} // buildMainPanelContext
/**
* Build the context for each template using template_index parameter passed
* in a form hidden field. Each case is associated with a template. (Not all
* templates implemented). See String[] TEMPLATES.
*
* @param index
* is the number contained in the template's template_index
*/
private String buildContextForTemplate(int index, VelocityPortlet portlet,
Context context, RunData data, SessionState state) {
String realmId = "";
String site_type = "";
String sortedBy = "";
String sortedAsc = "";
ParameterParser params = data.getParameters();
context.put("tlang", rb);
context.put("alertMessage", state.getAttribute(STATE_MESSAGE));
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
} else {
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
// Lists used in more than one template
// Access
List roles = new Vector();
// the hashtables for News and Web Content tools
Hashtable newsTitles = new Hashtable();
Hashtable newsUrls = new Hashtable();
Hashtable wcTitles = new Hashtable();
Hashtable wcUrls = new Hashtable();
List toolRegistrationList = new Vector();
List toolRegistrationSelectedList = new Vector();
ResourceProperties siteProperties = null;
// for showing site creation steps
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null) {
context.put("totalSteps", state
.getAttribute(SITE_CREATE_TOTAL_STEPS));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) {
context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP));
}
String hasGradSites = ServerConfigurationService.getString(
"withDissertation", Boolean.FALSE.toString());
context.put("cms", cms);
// course site type
context.put("courseSiteType", state.getAttribute(STATE_COURSE_SITE_TYPE));
//can the user create course sites?
context.put(STATE_SITE_ADD_COURSE, SiteService.allowAddCourseSite());
Site site = getStateSite(state);
switch (index) {
case 0:
/*
* buildContextForTemplate chef_site-list.vm
*
*/
// site types
List sTypes = (List) state.getAttribute(STATE_SITE_TYPES);
// make sure auto-updates are enabled
Hashtable views = new Hashtable();
if (SecurityService.isSuperUser()) {
views.put(rb.getString("java.allmy"), rb
.getString("java.allmy"));
views.put(rb.getString("java.my") + " "
+ rb.getString("java.sites"), rb.getString("java.my"));
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
views.put(type + " " + rb.getString("java.sites"), type);
}
if (hasGradSites.equalsIgnoreCase("true")) {
views.put(rb.getString("java.gradtools") + " "
+ rb.getString("java.sites"), rb
.getString("java.gradtools"));
}
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, rb
.getString("java.allmy"));
}
context.put("superUser", Boolean.TRUE);
} else {
context.put("superUser", Boolean.FALSE);
views.put(rb.getString("java.allmy"), rb
.getString("java.allmy"));
// if there is a GradToolsStudent choice inside
boolean remove = false;
if (hasGradSites.equalsIgnoreCase("true")) {
try {
// the Grad Tools site option is only presented to
// GradTools Candidates
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
// am I a grad student?
if (!isGradToolsCandidate(userId)) {
// not a gradstudent
remove = true;
}
} catch (Exception e) {
remove = true;
}
} else {
// not support for dissertation sites
remove = true;
}
// do not show this site type in views
// sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT));
for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) {
String type = (String) sTypes.get(sTypeIndex);
if (!type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) {
views
.put(type + " " + rb.getString("java.sites"),
type);
}
}
if (!remove) {
views.put(rb.getString("java.gradtools") + " "
+ rb.getString("java.sites"), rb
.getString("java.gradtools"));
}
// default view
if (state.getAttribute(STATE_VIEW_SELECTED) == null) {
state.setAttribute(STATE_VIEW_SELECTED, rb
.getString("java.allmy"));
}
}
context.put("views", views);
if (state.getAttribute(STATE_VIEW_SELECTED) != null) {
context.put("viewSelected", (String) state
.getAttribute(STATE_VIEW_SELECTED));
}
String search = (String) state.getAttribute(STATE_SEARCH);
context.put("search_term", search);
sortedBy = (String) state.getAttribute(SORTED_BY);
if (sortedBy == null) {
state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString());
sortedBy = SortType.TITLE_ASC.toString();
}
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
String portalUrl = ServerConfigurationService.getPortalUrl();
context.put("portalUrl", portalUrl);
List sites = prepPage(state);
state.setAttribute(STATE_SITES, sites);
context.put("sites", sites);
context.put("totalPageNumber", new Integer(totalPageNumber(state)));
context.put("searchString", state.getAttribute(STATE_SEARCH));
context.put("form_search", FORM_SEARCH);
context.put("formPageNumber", FORM_PAGE_NUMBER);
context.put("prev_page_exists", state
.getAttribute(STATE_PREV_PAGE_EXISTS));
context.put("next_page_exists", state
.getAttribute(STATE_NEXT_PAGE_EXISTS));
context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE));
// put the service in the context (used for allow update calls on
// each site)
context.put("service", SiteService.getInstance());
context.put("sortby_title", SortType.TITLE_ASC.toString());
context.put("sortby_type", SortType.TYPE_ASC.toString());
context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString());
context.put("sortby_publish", SortType.PUBLISHED_ASC.toString());
context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString());
// top menu bar
Menu bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site"));
}
bar.add(new MenuEntry(rb.getString("java.revise"), null, true,
MenuItem.CHECKED_NA, "doGet_site", "sitesForm"));
bar.add(new MenuEntry(rb.getString("java.delete"), null, true,
MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm"));
context.put("menu", bar);
// default to be no pageing
context.put("paged", Boolean.FALSE);
Menu bar2 = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
// add the search commands
addSearchMenus(bar2, state);
context.put("menu2", bar2);
pagingInfoToContext(state, context);
return (String) getContext(data).get("template") + TEMPLATE[0];
case 1:
/*
* buildContextForTemplate chef_site-type.vm
*
*/
if (hasGradSites.equalsIgnoreCase("true")) {
context.put("withDissertation", Boolean.TRUE);
try {
// the Grad Tools site option is only presented to UM grad
// students
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
// am I a UM grad student?
Boolean isGradStudent = new Boolean(
isGradToolsCandidate(userId));
context.put("isGradStudent", isGradStudent);
// if I am a UM grad student, do I already have a Grad Tools
// site?
boolean noGradToolsSite = true;
if (hasGradToolsStudentSite(userId))
noGradToolsSite = false;
context
.put("noGradToolsSite",
new Boolean(noGradToolsSite));
} catch (Exception e) {
if (Log.isWarnEnabled()) {
M_log.warn("buildContextForTemplate chef_site-type.vm "
+ e);
}
}
} else {
context.put("withDissertation", Boolean.FALSE);
}
List types = (List) state.getAttribute(STATE_SITE_TYPES);
context.put("siteTypes", types);
// put selected/default site type into context
if (siteInfo.site_type != null && siteInfo.site_type.length() > 0) {
context.put("typeSelected", siteInfo.site_type);
} else if (types.size() > 0) {
context.put("typeSelected", types.get(0));
}
setTermListForContext(context, state, true); // true => only
// upcoming terms
setSelectedTermForContext(context, state, STATE_TERM_SELECTED);
return (String) getContext(data).get("template") + TEMPLATE[1];
case 2:
/*
* buildContextForTemplate chef_site-newSiteInformation.vm
*
*/
context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES));
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("type", siteType);
if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
List<SectionObject> cmRequestedList = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (cmRequestedList != null) {
context.put("cmRequestedSections", cmRequestedList);
context.put("back", "53");
}
List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (cmAuthorizerSectionList != null) {
context
.put("cmAuthorizerSections",
cmAuthorizerSectionList);
context.put("back", "36");
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("back", "37");
} else {
if (courseManagementIsImplemented()) {
context.put("back", "36");
} else {
context.put("back", "0");
context.put("template-index", "37");
}
}
context.put("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) {
context.put("selectedIcon", siteInfo.getIconUrl());
}
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null) {
context.put(FORM_ICON_URL, siteInfo.iconUrl);
}
context.put("back", "1");
}
context.put(FORM_TITLE, siteInfo.title);
context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description);
context.put(FORM_DESCRIPTION, siteInfo.description);
// defalt the site contact person to the site creator
if (siteInfo.site_contact_name.equals(NULL_STRING)
&& siteInfo.site_contact_email.equals(NULL_STRING)) {
User user = UserDirectoryService.getCurrentUser();
siteInfo.site_contact_name = user.getDisplayName();
siteInfo.site_contact_email = user.getEmail();
}
context.put("form_site_contact_name", siteInfo.site_contact_name);
context.put("form_site_contact_email", siteInfo.site_contact_email);
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[2];
case 3:
/*
* buildContextForTemplate chef_site-newSiteFeatures.vm
*
*/
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
}
context.put("defaultTools", ServerConfigurationService
.getToolsRequired(siteType));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// If this is the first time through, check for tools
// which should be selected by default.
List defaultSelectedTools = ServerConfigurationService
.getDefaultTools(siteType);
if (toolRegistrationSelectedList == null) {
toolRegistrationSelectedList = new Vector(defaultSelectedTools);
}
// String toolId's
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList);
// use ToolRegistrations for template list titles for multiple tool instances
context.put(STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
// The "Home" tool checkbox needs special treatment to be selected
// by
// default.
Boolean checkHome = (Boolean) state
.getAttribute(STATE_TOOL_HOME_SELECTED);
if (checkHome == null) {
if ((defaultSelectedTools != null)
&& defaultSelectedTools.contains(HOME_TOOL_ID)) {
checkHome = Boolean.TRUE;
}
}
context.put("check_home", checkHome);
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
context.put("import", state.getAttribute(STATE_IMPORT));
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[3];
case 4:
/*
* buildContextForTemplate chef_site-addRemoveFeatures.vm
*
*/
context.put("SiteTitle", site.getTitle());
String type = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("defaultTools", ServerConfigurationService
.getToolsRequired(type));
boolean myworkspace_site = false;
// Put up tool lists filtered by category
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes.contains(type)) {
myworkspace_site = false;
}
if (SiteService.isUserSite(site.getId())
|| (type != null && type.equalsIgnoreCase("myworkspace"))) {
myworkspace_site = true;
type = "myworkspace";
}
context.put("myworkspace_site", new Boolean(myworkspace_site));
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST));
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
// titles for multiple tool instances
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
// get the email alias when an Email Archive tool has been selected
String channelReference = mailArchiveChannelReference(site.getId());
List aliases = AliasService.getAliases(channelReference, 1, 1);
if (aliases.size() > 0) {
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases
.get(0)).getId());
} else {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[4];
case 5:
/*
* buildContextForTemplate chef_site-addParticipant.vm
*
*/
context.put("title", site.getTitle());
roles = getRoles(state);
context.put("roles", roles);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
context.put("isCourseSite", siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))?Boolean.TRUE:Boolean.FALSE);
// Note that (for now) these strings are in both sakai.properties
// and sitesetupgeneric.properties
context.put("officialAccountSectionTitle", ServerConfigurationService
.getString("officialAccountSectionTitle"));
context.put("officialAccountName", ServerConfigurationService
.getString("officialAccountName"));
context.put("officialAccountLabel", ServerConfigurationService
.getString("officialAccountLabel"));
context.put("nonOfficialAccountSectionTitle", ServerConfigurationService
.getString("nonOfficialAccountSectionTitle"));
context.put("nonOfficialAccountName", ServerConfigurationService
.getString("nonOfficialAccountName"));
context.put("nonOfficialAccountLabel", ServerConfigurationService
.getString("nonOfficialAccountLabel"));
if (state.getAttribute("officialAccountValue") != null) {
context.put("officialAccountValue", (String) state
.getAttribute("officialAccountValue"));
}
if (state.getAttribute("nonOfficialAccountValue") != null) {
context.put("nonOfficialAccountValue", (String) state
.getAttribute("nonOfficialAccountValue"));
}
if (state.getAttribute("form_same_role") != null) {
context.put("form_same_role", ((Boolean) state
.getAttribute("form_same_role")).toString());
} else {
context.put("form_same_role", Boolean.TRUE.toString());
}
context.put("backIndex", "12");
return (String) getContext(data).get("template") + TEMPLATE[5];
case 8:
/*
* buildContextForTemplate chef_site-siteDeleteConfirm.vm
*
*/
String site_title = NULL_STRING;
String[] removals = (String[]) state
.getAttribute(STATE_SITE_REMOVALS);
List remove = new Vector();
String user = SessionManager.getCurrentSessionUserId();
String workspace = SiteService.getUserSiteId(user);
if (removals != null && removals.length != 0) {
for (int i = 0; i < removals.length; i++) {
String id = (String) removals[i];
if (!(id.equals(workspace))) {
try {
site_title = SiteService.getSite(id).getTitle();
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.doSite_delete_confirmed - IdUnusedException "
+ id);
addAlert(state, rb.getString("java.sitewith") + " "
+ id + " " + rb.getString("java.couldnt")
+ " ");
}
if (SiteService.allowRemoveSite(id)) {
try {
Site removeSite = SiteService.getSite(id);
remove.add(removeSite);
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException");
}
} else {
addAlert(state, site_title + " "
+ rb.getString("java.couldntdel") + " ");
}
} else {
addAlert(state, rb.getString("java.yourwork"));
}
}
if (remove.size() == 0) {
addAlert(state, rb.getString("java.click"));
}
}
context.put("removals", remove);
return (String) getContext(data).get("template") + TEMPLATE[8];
case 10:
/*
* buildContextForTemplate chef_site-newSiteConfirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
context.put("selectedAuthorizerCourse", state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
context.put("selectedRequestedCourse", state
.getAttribute(STATE_CM_REQUESTED_SECTIONS));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(number - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put("skins", state.getAttribute(STATE_ICONS));
if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) {
context.put("selectedIcon", siteInfo.getIconUrl());
}
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType != null && siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
if (StringUtil.trimToNull(siteInfo.iconUrl) != null) {
context.put("iconUrl", siteInfo.iconUrl);
}
}
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
context.put("siteContactName", siteInfo.site_contact_name);
context.put("siteContactEmail", siteInfo.site_contact_email);
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use Tool
// titles for multiple tool instances
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", new Boolean(siteInfo.include));
context.put("published", new Boolean(siteInfo.published));
context.put("joinable", new Boolean(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
// back to edit access page
context.put("back", "18");
context.put("importSiteTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("siteService", SiteService.getInstance());
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[10];
case 12:
/*
* buildContextForTemplate chef_site-siteInfo-list.vm
*
*/
context.put("userDirectoryService", UserDirectoryService
.getInstance());
try {
siteProperties = site.getProperties();
siteType = site.getType();
if (siteType != null) {
state.setAttribute(STATE_SITE_TYPE, siteType);
}
boolean isMyWorkspace = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
isMyWorkspace = true;
context.put("siteUserId", SiteService
.getSiteUserId(site.getId()));
}
}
context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace));
String siteId = site.getId();
if (state.getAttribute(STATE_ICONS) != null) {
List skins = (List) state.getAttribute(STATE_ICONS);
for (int i = 0; i < skins.size(); i++) {
MyIcon s = (MyIcon) skins.get(i);
if (!StringUtil
.different(s.getUrl(), site.getIconUrl())) {
context.put("siteUnit", s.getName());
break;
}
}
}
context.put("siteIcon", site.getIconUrl());
context.put("siteTitle", site.getTitle());
context.put("siteDescription", site.getDescription());
context.put("siteJoinable", new Boolean(site.isJoinable()));
if (site.isPublished()) {
context.put("published", Boolean.TRUE);
} else {
context.put("published", Boolean.FALSE);
context.put("owner", site.getCreatedBy().getSortName());
}
Time creationTime = site.getCreatedTime();
if (creationTime != null) {
context.put("siteCreationDate", creationTime
.toStringLocalFull());
}
boolean allowUpdateSite = SiteService.allowUpdateSite(siteId);
context.put("allowUpdate", Boolean.valueOf(allowUpdateSite));
boolean allowUpdateGroupMembership = SiteService
.allowUpdateGroupMembership(siteId);
context.put("allowUpdateGroupMembership", Boolean
.valueOf(allowUpdateGroupMembership));
boolean allowUpdateSiteMembership = SiteService
.allowUpdateSiteMembership(siteId);
context.put("allowUpdateSiteMembership", Boolean
.valueOf(allowUpdateSiteMembership));
Menu b = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (allowUpdateSite)
{
// top menu bar
if (!isMyWorkspace) {
b.add(new MenuEntry(rb.getString("java.editsite"),
"doMenu_edit_site_info"));
}
b.add(new MenuEntry(rb.getString("java.edittools"),
"doMenu_edit_site_tools"));
// if the page order helper is available, not
// stealthed and not hidden, show the link
if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) {
b.add(new MenuEntry(rb.getString("java.orderpages"),
"doPageOrderHelper"));
}
}
if (allowUpdateSiteMembership)
{
// show add participant menu
if (!isMyWorkspace) {
// show the Add Participant menu
b.add(new MenuEntry(rb.getString("java.addp"),
"doMenu_siteInfo_addParticipant"));
// show the Edit Class Roster menu
if (siteType != null && siteType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
b.add(new MenuEntry(rb.getString("java.editc"),
"doMenu_siteInfo_editClass"));
}
}
}
if (allowUpdateGroupMembership) {
// show Manage Groups menu
if (!isMyWorkspace
&& (ServerConfigurationService
.getString("wsetup.group.support") == "" || ServerConfigurationService
.getString("wsetup.group.support")
.equalsIgnoreCase(Boolean.TRUE.toString()))) {
// show the group toolbar unless configured
// to not support group
b.add(new MenuEntry(rb.getString("java.group"),
"doMenu_group"));
}
}
if (allowUpdateSite)
{
if (!isMyWorkspace) {
List gradToolsSiteTypes = (List) state
.getAttribute(GRADTOOLS_SITE_TYPES);
boolean isGradToolSite = false;
if (siteType != null
&& gradToolsSiteTypes.contains(siteType)) {
isGradToolSite = true;
}
if (siteType == null || siteType != null
&& !isGradToolSite) {
// hide site access for GRADTOOLS
// type of sites
b.add(new MenuEntry(
rb.getString("java.siteaccess"),
"doMenu_edit_site_access"));
}
if (siteType == null || siteType != null
&& !isGradToolSite) {
// hide site duplicate and import
// for GRADTOOLS type of sites
if (SiteService.allowAddSite(null))
{
b.add(new MenuEntry(rb.getString("java.duplicate"),
"doMenu_siteInfo_duplicate"));
}
List updatableSites = SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null,
SortType.TITLE_ASC, null);
// import link should be visible even if only one
// site
if (updatableSites.size() > 0) {
b.add(new MenuEntry(
rb.getString("java.import"),
"doMenu_siteInfo_import"));
// a configuration param for
// showing/hiding import
// from file choice
String importFromFile = ServerConfigurationService
.getString("site.setup.import.file",
Boolean.TRUE.toString());
if (importFromFile.equalsIgnoreCase("true")) {
// htripath: June
// 4th added as per
// Kris and changed
// desc of above
b.add(new MenuEntry(rb
.getString("java.importFile"),
"doAttachmentsMtrlFrmFile"));
}
}
}
}
}
if (b.size() > 0)
{
// add the menus to vm
context.put("menu", b);
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
// editing from worksite setup tool
context.put("fromWSetup", Boolean.TRUE);
if (state.getAttribute(STATE_PREV_SITE) != null) {
context.put("prevSite", state
.getAttribute(STATE_PREV_SITE));
}
if (state.getAttribute(STATE_NEXT_SITE) != null) {
context.put("nextSite", state
.getAttribute(STATE_NEXT_SITE));
}
} else {
context.put("fromWSetup", Boolean.FALSE);
}
// allow view roster?
boolean allowViewRoster = SiteService.allowViewRoster(siteId);
if (allowViewRoster) {
context.put("viewRoster", Boolean.TRUE);
} else {
context.put("viewRoster", Boolean.FALSE);
}
// set participant list
if (allowUpdateSite || allowViewRoster
|| allowUpdateSiteMembership) {
Collection participantsCollection = getParticipantList(state);
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy == null) {
state.setAttribute(SORTED_BY,
SORTED_BY_PARTICIPANT_NAME);
sortedBy = SORTED_BY_PARTICIPANT_NAME;
}
if (sortedAsc == null) {
sortedAsc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, sortedAsc);
}
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
context.put("participantListSize", new Integer(participantsCollection.size()));
context.put("participantList", prepPage(state));
pagingInfoToContext(state, context);
}
context.put("include", Boolean.valueOf(site.isPubView()));
// site contact information
String contactName = siteProperties
.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null) {
User u = site.getCreatedBy();
String email = u.getEmail();
if (email != null) {
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
}
if (contactName != null) {
context.put("contactName", contactName);
}
if (contactEmail != null) {
context.put("contactEmail", contactEmail);
}
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
coursesIntoContext(state, context, site);
context.put("term", siteProperties
.getProperty(PROP_SITE_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
} catch (Exception e) {
M_log.warn(this + " site info list: " + e.toString());
}
roles = getRoles(state);
context.put("roles", roles);
// will have the choice to active/inactive user or not
String activeInactiveUser = ServerConfigurationService.getString(
"activeInactiveUser", Boolean.FALSE.toString());
if (activeInactiveUser.equalsIgnoreCase("true")) {
context.put("activeInactiveUser", Boolean.TRUE);
} else {
context.put("activeInactiveUser", Boolean.FALSE);
}
context.put("groupsWithMember", site
.getGroupsWithMember(UserDirectoryService.getCurrentUser()
.getId()));
return (String) getContext(data).get("template") + TEMPLATE[12];
case 13:
/*
* buildContextForTemplate chef_site-siteInfo-editInfo.vm
*
*/
siteProperties = site.getProperties();
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, site.getType())));
context.put("type", site.getType());
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("skins", state.getAttribute(STATE_ICONS));
if (state.getAttribute(FORM_SITEINFO_SKIN) != null) {
context.put("selectedIcon", state
.getAttribute(FORM_SITEINFO_SKIN));
} else if (site.getIconUrl() != null) {
context.put("selectedIcon", site.getIconUrl());
}
setTermListForContext(context, state, true); // true->only future terms
if (state.getAttribute(FORM_SITEINFO_TERM) == null) {
String currentTerm = site.getProperties().getProperty(
PROP_SITE_TERM);
if (currentTerm != null) {
state.setAttribute(FORM_SITEINFO_TERM, currentTerm);
}
}
setSelectedTermForContext(context, state, FORM_SITEINFO_TERM);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null
&& StringUtil.trimToNull(site.getIconUrl()) != null) {
state.setAttribute(FORM_SITEINFO_ICON_URL, site
.getIconUrl());
}
if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null) {
context.put("iconUrl", state
.getAttribute(FORM_SITEINFO_ICON_URL));
}
}
context.put("description", state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("short_description", state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("form_site_contact_name", state
.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("form_site_contact_email", state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
// Display of appearance icon/url list with course site based on
// "disable.course.site.skin.selection" value set with
// sakai.properties file.
if ((ServerConfigurationService
.getString("disable.course.site.skin.selection"))
.equals("true")) {
context.put("disableCourseSelection", Boolean.TRUE);
}
return (String) getContext(data).get("template") + TEMPLATE[13];
case 14:
/*
* buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm
*
*/
siteProperties = site.getProperties();
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM));
} else {
context.put("isCourseSite", Boolean.FALSE);
}
context.put("oTitle", site.getTitle());
context.put("title", state.getAttribute(FORM_SITEINFO_TITLE));
context.put("description", state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
context.put("oDescription", site.getDescription());
context.put("short_description", state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
context.put("oShort_description", site.getShortDescription());
context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN));
context.put("oSkin", site.getIconUrl());
context.put("skins", state.getAttribute(STATE_ICONS));
context.put("oIcon", site.getIconUrl());
context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL));
context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE));
context.put("oInclude", Boolean.valueOf(site.isPubView()));
context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME));
context.put("oName", siteProperties
.getProperty(PROP_SITE_CONTACT_NAME));
context.put("email", state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL));
context.put("oEmail", siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL));
return (String) getContext(data).get("template") + TEMPLATE[14];
case 15:
/*
* buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm
*
*/
context.put("title", site.getTitle());
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
myworkspace_site = false;
if (SiteService.isUserSite(site.getId())) {
if (SiteService.getSiteUserId(site.getId()).equals(
SessionManager.getCurrentSessionUserId())) {
myworkspace_site = true;
site_type = "myworkspace";
}
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("selectedTools", orderToolIds(state, (String) state
.getAttribute(STATE_SITE_TYPE), (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST)));
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
context.put("oldSelectedHome", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME));
context.put("continueIndex", "12");
if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) {
context.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
}
context.put("serverName", ServerConfigurationService
.getServerName());
// titles for multiple tool instances
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP ));
if (fromENWModifyView(state)) {
context.put("back", "26");
} else {
context.put("back", "4");
}
return (String) getContext(data).get("template") + TEMPLATE[15];
case 18:
/*
* buildContextForTemplate chef_siteInfo-editAccess.vm
*
*/
List publicChangeableSiteTypes = (List) state
.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES);
List unJoinableSiteTypes = (List) state
.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE);
if (site != null) {
// editing existing site
context.put("site", site);
siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state
.getAttribute(STATE_SITE_TYPE)
: null;
if (siteType != null
&& publicChangeableSiteTypes.contains(siteType)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(site.isPubView()));
if (siteType != null && !unJoinableSiteTypes.contains(siteType)) {
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
if (state.getAttribute(STATE_JOINABLE) == null) {
state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site
.isJoinable()));
}
if (state.getAttribute(STATE_JOINERROLE) == null
|| state.getAttribute(STATE_JOINABLE) != null
&& ((Boolean) state.getAttribute(STATE_JOINABLE))
.booleanValue()) {
state.setAttribute(STATE_JOINERROLE, site
.getJoinerRole());
}
if (state.getAttribute(STATE_JOINABLE) != null) {
context.put("joinable", state
.getAttribute(STATE_JOINABLE));
}
if (state.getAttribute(STATE_JOINERROLE) != null) {
context.put("joinerRole", state
.getAttribute(STATE_JOINERROLE));
}
} else {
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
context.put("roles", getRoles(state));
context.put("back", "12");
} else {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteInfo.site_type != null
&& publicChangeableSiteTypes
.contains(siteInfo.site_type)) {
context.put("publicChangeable", Boolean.TRUE);
} else {
context.put("publicChangeable", Boolean.FALSE);
}
context.put("include", Boolean.valueOf(siteInfo.getInclude()));
context.put("published", Boolean.valueOf(siteInfo
.getPublished()));
if (siteInfo.site_type != null
&& !unJoinableSiteTypes.contains(siteInfo.site_type)) {
// site can be set as joinable
context.put("disableJoinable", Boolean.FALSE);
context.put("joinable", Boolean.valueOf(siteInfo.joinable));
context.put("joinerRole", siteInfo.joinerRole);
} else {
// site cannot be set as joinable
context.put("disableJoinable", Boolean.TRUE);
}
// use the type's template, if defined
String realmTemplate = "!site.template";
if (siteInfo.site_type != null) {
realmTemplate = realmTemplate + "." + siteInfo.site_type;
}
try {
AuthzGroup r = AuthzGroupService
.getAuthzGroup(realmTemplate);
context.put("roles", r.getRoles());
} catch (GroupNotDefinedException e) {
try {
AuthzGroup rr = AuthzGroupService
.getAuthzGroup("!site.template");
context.put("roles", rr.getRoles());
} catch (GroupNotDefinedException ee) {
}
}
// new site, go to confirmation page
context.put("continue", "10");
if (fromENWModifyView(state)) {
context.put("back", "26");
} else if (state.getAttribute(STATE_IMPORT) != null) {
context.put("back", "27");
} else {
context.put("back", "3");
}
siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("isProjectSite", Boolean.FALSE);
} else {
context.put("isCourseSite", Boolean.FALSE);
if (siteType.equalsIgnoreCase("project")) {
context.put("isProjectSite", Boolean.TRUE);
}
}
}
return (String) getContext(data).get("template") + TEMPLATE[18];
case 19:
/*
* buildContextForTemplate chef_site-addParticipant-sameRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("participantList", state
.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("form_selectedRole", state
.getAttribute("form_selectedRole"));
return (String) getContext(data).get("template") + TEMPLATE[19];
case 20:
/*
* buildContextForTemplate chef_site-addParticipant-differentRole.vm
*
*/
context.put("title", site.getTitle());
context.put("roles", getRoles(state));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context.put("participantList", state
.getAttribute(STATE_ADD_PARTICIPANTS));
return (String) getContext(data).get("template") + TEMPLATE[20];
case 21:
/*
* buildContextForTemplate chef_site-addParticipant-notification.vm
*
*/
context.put("title", site.getTitle());
context.put("sitePublished", Boolean.valueOf(site.isPublished()));
if (state.getAttribute("form_selectedNotify") == null) {
state.setAttribute("form_selectedNotify", Boolean.FALSE);
}
context.put("notify", state.getAttribute("form_selectedNotify"));
boolean same_role = state.getAttribute("form_same_role") == null ? true
: ((Boolean) state.getAttribute("form_same_role"))
.booleanValue();
if (same_role) {
context.put("backIndex", "19");
} else {
context.put("backIndex", "20");
}
return (String) getContext(data).get("template") + TEMPLATE[21];
case 22:
/*
* buildContextForTemplate chef_site-addParticipant-confirm.vm
*
*/
context.put("title", site.getTitle());
context.put("participants", state
.getAttribute(STATE_ADD_PARTICIPANTS));
context.put("notify", state.getAttribute("form_selectedNotify"));
context.put("roles", getRoles(state));
context.put("same_role", state.getAttribute("form_same_role"));
context.put("selectedRoles", state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES));
context
.put("selectedRole", state
.getAttribute("form_selectedRole"));
return (String) getContext(data).get("template") + TEMPLATE[22];
case 26:
/*
* buildContextForTemplate chef_site-modifyENW.vm
*
*/
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
boolean existingSite = site != null ? true : false;
if (existingSite) {
// revising a existing site's tool
context.put("existingSite", Boolean.TRUE);
context.put("back", "4");
context.put("continue", "15");
context.put("function", "eventSubmit_doAdd_remove_features");
} else {
// new site
context.put("existingSite", Boolean.FALSE);
context.put("function", "eventSubmit_doAdd_features");
if (state.getAttribute(STATE_IMPORT) != null) {
context.put("back", "27");
} else {
// new site, go to edit access page
context.put("back", "3");
}
context.put("continue", "18");
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_MULTIPLE_TOOL_ID_SET, state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET));
context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP));
context.put("toolManager", ToolManager.getInstance());
String emailId = (String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS);
if (emailId != null) {
context.put("emailId", emailId);
}
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("oldSelectedTools", state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST));
return (String) getContext(data).get("template") + TEMPLATE[26];
case 27:
/*
* buildContextForTemplate chef_site-importSites.vm
*
*/
existingSite = site != null ? true : false;
site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (existingSite) {
// revising a existing site's tool
context.put("continue", "12");
context.put("back", "28");
context.put("totalSteps", "2");
context.put("step", "2");
context.put("currentSite", site);
} else {
// new site, go to edit access page
context.put("back", "3");
if (fromENWModifyView(state)) {
context.put("continue", "26");
} else {
context.put("continue", "18");
}
}
context.put(STATE_TOOL_REGISTRATION_LIST, state
.getAttribute(STATE_TOOL_REGISTRATION_LIST));
context.put("selectedTools", orderToolIds(state, site_type,
(List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); // String toolId's
context.put("importSites", state.getAttribute(STATE_IMPORT_SITES));
context.put("importSitesTools", state
.getAttribute(STATE_IMPORT_SITE_TOOL));
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context.put("importSupportedTools", importTools());
return (String) getContext(data).get("template") + TEMPLATE[27];
case 28:
/*
* buildContextForTemplate chef_siteinfo-import.vm
*
*/
context.put("currentSite", site);
context.put("importSiteList", state
.getAttribute(STATE_IMPORT_SITES));
context.put("sites", SiteService.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
null, null, null, SortType.TITLE_ASC, null));
return (String) getContext(data).get("template") + TEMPLATE[28];
case 29:
/*
* buildContextForTemplate chef_siteinfo-duplicate.vm
*
*/
context.put("siteTitle", site.getTitle());
String sType = site.getType();
if (sType != null && sType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
context.put("isCourseSite", Boolean.TRUE);
context.put("currentTermId", site.getProperties().getProperty(
PROP_SITE_TERM));
setTermListForContext(context, state, true); // true upcoming only
} else {
context.put("isCourseSite", Boolean.FALSE);
}
if (state.getAttribute(SITE_DUPLICATED) == null) {
context.put("siteDuplicated", Boolean.FALSE);
} else {
context.put("siteDuplicated", Boolean.TRUE);
context.put("duplicatedName", state
.getAttribute(SITE_DUPLICATED_NAME));
}
return (String) getContext(data).get("template") + TEMPLATE[29];
case 36:
/*
* buildContextForTemplate chef_site-newSiteCourse.vm
*/
// SAK-9824
Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE);
context.put("enableCourseCreationForUser", enableCourseCreationForUser);
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
setTermListForContext(context, state, true); // true -> upcoming only
List providerCourseList = (List) state
.getAttribute(SITE_PROVIDER_COURSE_LIST);
coursesIntoContext(state, context, site);
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
context.put("term", t);
if (t != null) {
String userId = UserDirectoryService.getCurrentUser().getEid();
List courses = prepareCourseAndSectionListing(userId, t
.getEid(), state);
if (courses != null && courses.size() > 0) {
Vector notIncludedCourse = new Vector();
// remove included sites
for (Iterator i = courses.iterator(); i.hasNext();) {
CourseObject c = (CourseObject) i.next();
if (providerCourseList == null || providerCourseList != null && !providerCourseList.contains(c.getEid())) {
notIncludedCourse.add(c);
}
}
state.setAttribute(STATE_TERM_COURSE_LIST,
notIncludedCourse);
} else {
state.removeAttribute(STATE_TERM_COURSE_LIST);
}
}
// step number used in UI
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1"));
} else {
// need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS
// contains sections that doens't belongs to current user and
// STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does -
// v2.4 daisyf
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null
|| state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) {
List<String> providerSectionList = (List<String>) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (providerSectionList != null) {
/*
List list1 = prepareSectionObject(providerSectionList,
(String) state
.getAttribute(STATE_CM_CURRENT_USERID));
*/
context.put("selectedProviderCourse", providerSectionList);
}
List<SectionObject> authorizerSectionList = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (authorizerSectionList != null) {
List authorizerList = (List) state
.getAttribute(STATE_CM_AUTHORIZER_LIST);
//authorizerList is a list of SectionObject
/*
String userId = null;
if (authorizerList != null) {
userId = (String) authorizerList.get(0);
}
List list2 = prepareSectionObject(
authorizerSectionList, userId);
*/
ArrayList list2 = new ArrayList();
for (int i=0; i<authorizerSectionList.size();i++){
SectionObject so = (SectionObject)authorizerSectionList.get(i);
list2.add(so.getEid());
}
context.put("selectedAuthorizerCourse", list2);
}
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
context.put("selectedManualCourse", Boolean.TRUE);
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("currentUserId", (String) state
.getAttribute(STATE_CM_CURRENT_USERID));
context.put("form_additional", (String) state
.getAttribute(FORM_ADDITIONAL));
context.put("authorizers", getAuthorizers(state));
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
context.put("backIndex", "1");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
context.put("backIndex", "");
}
List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST);
context.put("termCourseList", state
.getAttribute(STATE_TERM_COURSE_LIST));
// added for 2.4 -daisyf
context.put("campusDirectory", getCampusDirectory());
context.put("userId", (String) state
.getAttribute(STATE_INSTRUCTOR_SELECTED));
/*
* for measuring how long it takes to load sections java.util.Date
* date = new java.util.Date(); M_log.debug("***2. finish at:
* "+date); M_log.debug("***3. userId:"+(String) state
* .getAttribute(STATE_INSTRUCTOR_SELECTED));
*/
return (String) getContext(data).get("template") + TEMPLATE[36];
case 37:
/*
* buildContextForTemplate chef_site-newSiteCourseManual.vm
*/
if (site != null) {
context.put("site", site);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
}
buildInstructorSectionsList(state, params, context);
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("form_additional", siteInfo.additional);
context.put("form_title", siteInfo.title);
context.put("form_description", siteInfo.description);
context.put("officialAccountName", ServerConfigurationService
.getString("officialAccountName", ""));
context.put("value_uniqname", state
.getAttribute(STATE_SITE_QUEST_UNIQNAME));
int number = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
number = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("currentNumber", new Integer(number));
}
context.put("currentNumber", new Integer(number));
context.put("listSize", number>0?new Integer(number - 1):0);
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null && ((List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)).size() > 0)
{
context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
List l = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
context.put("selectedProviderCourse", l);
context.put("size", new Integer(l.size() - 1));
}
if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) {
List l = (List) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
context.put("cmRequestedSections", l);
}
if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO))
{
context.put("editSite", Boolean.TRUE);
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (site == null) {
// v2.4 - added & modified by daisyf
if (courseManagementIsImplemented() && state.getAttribute(STATE_TERM_COURSE_LIST) != null)
{
// back to the list view of sections
context.put("back", "36");
} else {
context.put("back", "1");
}
if (state.getAttribute(STATE_AUTO_ADD) != null) {
context.put("autoAdd", Boolean.TRUE);
// context.put("back", "36");
}
}
else
{
// editing site
context.put("back", "36");
}
isFutureTermSelected(state);
context.put("isFutureTerm", state
.getAttribute(STATE_FUTURE_TERM_SELECTED));
context.put("weeksAhead", ServerConfigurationService.getString(
"roster.available.weeks.before.term.start", "0"));
return (String) getContext(data).get("template") + TEMPLATE[37];
case 42:
/*
* buildContextForTemplate chef_site-gradtoolsConfirm.vm
*
*/
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
context.put("title", siteInfo.title);
context.put("description", siteInfo.description);
context.put("short_description", siteInfo.short_description);
toolRegistrationList = (Vector) state
.getAttribute(STATE_PROJECT_TOOL_LIST);
toolRegistrationSelectedList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST,
toolRegistrationSelectedList); // String toolId's
context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%%
// use
// Tool
context.put("check_home", state
.getAttribute(STATE_TOOL_HOME_SELECTED));
context
.put("emailId", state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
context.put("serverName", ServerConfigurationService
.getServerName());
context.put("include", new Boolean(siteInfo.include));
return (String) getContext(data).get("template") + TEMPLATE[42];
case 43:
/*
* buildContextForTemplate chef_siteInfo-editClass.vm
*
*/
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowAddSite(null)) {
bar.add(new MenuEntry(rb.getString("java.addclasses"),
"doMenu_siteInfo_addClass"));
}
context.put("menu", bar);
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
return (String) getContext(data).get("template") + TEMPLATE[43];
case 44:
/*
* buildContextForTemplate chef_siteInfo-addCourseConfirm.vm
*
*/
context.put("siteTitle", site.getTitle());
coursesIntoContext(state, context, site);
context.put("providerAddCourses", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null)
{
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int addNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue() - 1;
context.put("manualAddNumber", new Integer(addNumber));
context.put("requestFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
context.put("backIndex", "37");
} else {
context.put("backIndex", "36");
}
// those manual inputs
context.put("form_requiredFields", sectionFieldProvider
.getRequiredFields());
context.put("fieldValues", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
return (String) getContext(data).get("template") + TEMPLATE[44];
// htripath - import materials from classic
case 45:
/*
* buildContextForTemplate chef_siteInfo-importMtrlMaster.vm
*
*/
return (String) getContext(data).get("template") + TEMPLATE[45];
case 46:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopy.vm
*
*/
// this is for list display in listbox
context
.put("allZipSites", state
.getAttribute(ALL_ZIP_IMPORT_SITES));
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
// zip file
// context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME));
return (String) getContext(data).get("template") + TEMPLATE[46];
case 47:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[47];
case 48:
/*
* buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm
*
*/
context.put("finalZipSites", state
.getAttribute(FINAL_ZIP_IMPORT_SITES));
return (String) getContext(data).get("template") + TEMPLATE[48];
case 49:
/*
* buildContextForTemplate chef_siteInfo-group.vm
*
*/
context.put("site", site);
bar = new MenuImpl(portlet, data, (String) state
.getAttribute(STATE_ACTION));
if (SiteService.allowUpdateSite(site.getId())
|| SiteService.allowUpdateGroupMembership(site.getId())) {
bar.add(new MenuEntry(rb.getString("java.newgroup"), "doGroup_new"));
}
context.put("menu", bar);
// the group list
sortedBy = (String) state.getAttribute(SORTED_BY);
sortedAsc = (String) state.getAttribute(SORTED_ASC);
if (sortedBy != null)
context.put("currentSortedBy", sortedBy);
if (sortedAsc != null)
context.put("currentSortAsc", sortedAsc);
// only show groups created by WSetup tool itself
Collection groups = (Collection) site.getGroups();
List groupsByWSetup = new Vector();
for (Iterator gIterator = groups.iterator(); gIterator.hasNext();) {
Group gNext = (Group) gIterator.next();
String gProp = gNext.getProperties().getProperty(
GROUP_PROP_WSETUP_CREATED);
if (gProp != null && gProp.equals(Boolean.TRUE.toString())) {
groupsByWSetup.add(gNext);
}
}
if (sortedBy != null && sortedAsc != null) {
context.put("groups", new SortedIterator(groupsByWSetup
.iterator(), new SiteComparator(sortedBy, sortedAsc)));
}
return (String) getContext(data).get("template") + TEMPLATE[49];
case 50:
/*
* buildContextForTemplate chef_siteInfo-groupedit.vm
*
*/
Group g = getStateGroup(state);
if (g != null) {
context.put("group", g);
context.put("newgroup", Boolean.FALSE);
} else {
context.put("newgroup", Boolean.TRUE);
}
if (state.getAttribute(STATE_GROUP_TITLE) != null) {
context.put("title", state.getAttribute(STATE_GROUP_TITLE));
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) != null) {
context.put("description", state
.getAttribute(STATE_GROUP_DESCRIPTION));
}
Iterator siteMembers = new SortedIterator(getParticipantList(state)
.iterator(), new SiteComparator(SORTED_BY_PARTICIPANT_NAME,
Boolean.TRUE.toString()));
if (siteMembers != null && siteMembers.hasNext()) {
context.put("generalMembers", siteMembers);
}
Set groupMembersSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
if (state.getAttribute(STATE_GROUP_MEMBERS) != null) {
context.put("groupMembers", new SortedIterator(groupMembersSet
.iterator(), new SiteComparator(SORTED_BY_MEMBER_NAME,
Boolean.TRUE.toString())));
}
context.put("groupMembersClone", groupMembersSet);
context.put("userDirectoryService", UserDirectoryService
.getInstance());
return (String) getContext(data).get("template") + TEMPLATE[50];
case 51:
/*
* buildContextForTemplate chef_siteInfo-groupDeleteConfirm.vm
*
*/
context.put("site", site);
context
.put("removeGroupIds", new ArrayList(Arrays
.asList((String[]) state
.getAttribute(STATE_GROUP_REMOVE))));
return (String) getContext(data).get("template") + TEMPLATE[51];
case 53: {
/*
* build context for chef_site-findCourse.vm
*/
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state
.getAttribute(STATE_CM_LEVEL_SELECTIONS);
if (cmLevels == null)
{
cmLevels = getCMLevelLabels();
}
SectionObject selectedSect = (SectionObject) state
.getAttribute(STATE_CM_SELECTED_SECTION);
List<SectionObject> requestedSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (courseManagementIsImplemented() && cms != null) {
context.put("cmsAvailable", new Boolean(true));
}
int cmLevelSize = 0;
if (cms == null || !courseManagementIsImplemented()
|| cmLevels == null || cmLevels.size() < 1) {
// TODO: redirect to manual entry: case #37
} else {
cmLevelSize = cmLevels.size();
Object levelOpts[] = state.getAttribute(STATE_CM_LEVEL_OPTS) == null?new Object[cmLevelSize]:(Object[])state.getAttribute(STATE_CM_LEVEL_OPTS);
int numSelections = 0;
if (selections != null)
numSelections = selections.size();
// execution will fall through these statements based on number of selections already made
if (numSelections == cmLevelSize - 1)
{
levelOpts[numSelections] = getCMSections((String) selections.get(numSelections-1));
}
else if (numSelections == cmLevelSize - 2)
{
levelOpts[numSelections] = getCMCourseOfferings((String) selections.get(numSelections-1), t.getEid());
}
else if (numSelections < cmLevelSize)
{
levelOpts[numSelections] = sortCmObject(cms.findCourseSets((String) cmLevels.get(numSelections==0?0:numSelections-1)));
}
// always set the top level
levelOpts[0] = sortCmObject(cms.findCourseSets((String) cmLevels.get(0)));
// clean further element inside the array
for (int i = numSelections + 1; i<cmLevelSize; i++)
{
levelOpts[i] = null;
}
context.put("cmLevelOptions", Arrays.asList(levelOpts));
state.setAttribute(STATE_CM_LEVEL_OPTS, levelOpts);
}
if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) {
context.put("selectedProviderCourse", state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN));
}
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
int courseInd = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
context.put("manualAddNumber", new Integer(courseInd - 1));
context.put("manualAddFields", state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS));
}
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
context.put("cmLevels", cmLevels);
context.put("cmLevelSelections", selections);
context.put("selectedCourse", selectedSect);
context.put("cmRequestedSections", requestedSections);
if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO))
{
context.put("editSite", Boolean.TRUE);
context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS));
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
if (state.getAttribute(STATE_TERM_COURSE_LIST) != null)
{
context.put("backIndex", "36");
}
else
{
context.put("backIndex", "1");
}
}
else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO))
{
context.put("backIndex", "36");
}
context.put("authzGroupService", AuthzGroupService.getInstance());
return (String) getContext(data).get("template") + TEMPLATE[53];
}
}
// should never be reached
return (String) getContext(data).get("template") + TEMPLATE[0];
} // buildContextForTemplate
/**
* Launch the Page Order Helper Tool -- for ordering, adding and customizing
* pages
*
* @see case 12
*
*/
public void doPageOrderHelper(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// pass in the siteId of the site to be ordered (so it can configure
// sites other then the current site)
SessionManager.getCurrentToolSession().setAttribute(
HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId());
// launch the helper
startHelper(data.getRequest(), "sakai-site-pageorder-helper");
}
// htripath: import materials from classic
/**
* Master import -- for import materials from a file
*
* @see case 45
*
*/
public void doAttachmentsMtrlFrmFile(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// state.setAttribute(FILE_UPLOAD_MAX_SIZE,
// ServerConfigurationService.getString("content.upload.max", "1"));
state.setAttribute(STATE_TEMPLATE_INDEX, "45");
} // doImportMtrlFrmFile
/**
* Handle File Upload request
*
* @see case 46
* @throws Exception
*/
public void doUpload_Mtrl_Frm_File(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
List allzipList = new Vector();
List finalzipList = new Vector();
List directcopyList = new Vector();
// see if the user uploaded a file
FileItem fileFromUpload = null;
String fileName = null;
fileFromUpload = data.getParameters().getFileItem("file");
String max_file_size_mb = ServerConfigurationService.getString(
"content.upload.max", "1");
int max_bytes = 1024 * 1024;
try {
max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024;
} catch (Exception e) {
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1024 * 1024;
}
if (fileFromUpload == null) {
// "The user submitted a file to upload but it was too big!"
addAlert(state, rb.getString("importFile.size") + " "
+ max_file_size_mb + "MB "
+ rb.getString("importFile.exceeded"));
} else if (fileFromUpload.getFileName() == null
|| fileFromUpload.getFileName().length() == 0) {
addAlert(state, rb.getString("importFile.choosefile"));
} else {
byte[] fileData = fileFromUpload.get();
if (fileData.length >= max_bytes) {
addAlert(state, rb.getString("size") + " " + max_file_size_mb
+ "MB " + rb.getString("importFile.exceeded"));
} else if (fileData.length > 0) {
if (importService.isValidArchive(fileData)) {
ImportDataSource importDataSource = importService
.parseFromFile(fileData);
Log.info("chef", "Getting import items from manifest.");
List lst = importDataSource.getItemCategories();
if (lst != null && lst.size() > 0) {
Iterator iter = lst.iterator();
while (iter.hasNext()) {
ImportMetadata importdata = (ImportMetadata) iter
.next();
// Log.info("chef","Preparing import
// item '" + importdata.getId() + "'");
if ((!importdata.isMandatory())
&& (importdata.getFileName()
.endsWith(".xml"))) {
allzipList.add(importdata);
} else {
directcopyList.add(importdata);
}
}
}
// set Attributes
state.setAttribute(ALL_ZIP_IMPORT_SITES, allzipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, finalzipList);
state.setAttribute(DIRECT_ZIP_IMPORT_SITES, directcopyList);
state.setAttribute(CLASSIC_ZIP_FILE_NAME, fileName);
state.setAttribute(IMPORT_DATA_SOURCE, importDataSource);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} else { // uploaded file is not a valid archive
}
}
}
} // doImportMtrlFrmFile
/**
* Handle addition to list request
*
* @param data
*/
public void doAdd_MtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List importSites = new ArrayList(Arrays.asList(params
.getStrings("addImportSelected")));
for (int i = 0; i < importSites.size(); i++) {
String value = (String) importSites.get(i);
fnlList.add(removeItems(value, zipList));
}
state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} // doAdd_MtrlSite
/**
* Helper class for Add and remove
*
* @param value
* @param items
* @return
*/
public ImportMetadata removeItems(String value, List items) {
ImportMetadata result = null;
for (int i = 0; i < items.size(); i++) {
ImportMetadata item = (ImportMetadata) items.get(i);
if (value.equals(item.getId())) {
result = (ImportMetadata) items.remove(i);
break;
}
}
return result;
}
/**
* Handle the request for remove
*
* @param data
*/
public void doRemove_MtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List importSites = new ArrayList(Arrays.asList(params
.getStrings("removeImportSelected")));
for (int i = 0; i < importSites.size(); i++) {
String value = (String) importSites.get(i);
zipList.add(removeItems(value, fnlList));
}
state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "46");
} // doAdd_MtrlSite
/**
* Handle the request for copy
*
* @param data
*/
public void doCopyMtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList);
state.setAttribute(STATE_TEMPLATE_INDEX, "47");
} // doCopy_MtrlSite
/**
* Handle the request for Save
*
* @param data
* @throws ImportException
*/
public void doSaveMtrlSite(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES);
List directList = (List) state.getAttribute(DIRECT_ZIP_IMPORT_SITES);
ImportDataSource importDataSource = (ImportDataSource) state
.getAttribute(IMPORT_DATA_SOURCE);
// combine the selected import items with the mandatory import items
fnlList.addAll(directList);
Log.info("chef", "doSaveMtrlSite() about to import " + fnlList.size()
+ " top level items");
Log.info("chef", "doSaveMtrlSite() the importDataSource is "
+ importDataSource.getClass().getName());
if (importDataSource instanceof SakaiArchive) {
Log.info("chef",
"doSaveMtrlSite() our data source is a Sakai format");
((SakaiArchive) importDataSource).buildSourceFolder(fnlList);
Log.info("chef", "doSaveMtrlSite() source folder is "
+ ((SakaiArchive) importDataSource).getSourceFolder());
ArchiveService.merge(((SakaiArchive) importDataSource)
.getSourceFolder(), siteId, null);
} else {
importService.doImportItems(importDataSource
.getItemsForCategories(fnlList), siteId);
}
// remove attributes
state.removeAttribute(ALL_ZIP_IMPORT_SITES);
state.removeAttribute(FINAL_ZIP_IMPORT_SITES);
state.removeAttribute(DIRECT_ZIP_IMPORT_SITES);
state.removeAttribute(CLASSIC_ZIP_FILE_NAME);
state.removeAttribute(SESSION_CONTEXT_ID);
state.removeAttribute(IMPORT_DATA_SOURCE);
state.setAttribute(STATE_TEMPLATE_INDEX, "48");
// state.setAttribute(STATE_TEMPLATE_INDEX, "28");
} // doSave_MtrlSite
public void doSaveMtrlSiteMsg(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// remove attributes
state.removeAttribute(ALL_ZIP_IMPORT_SITES);
state.removeAttribute(FINAL_ZIP_IMPORT_SITES);
state.removeAttribute(DIRECT_ZIP_IMPORT_SITES);
state.removeAttribute(CLASSIC_ZIP_FILE_NAME);
state.removeAttribute(SESSION_CONTEXT_ID);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
// htripath-end
/**
* Handle the site search request.
*/
public void doSite_search(RunData data, Context context) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// read the search form field into the state object
String search = StringUtil.trimToNull(data.getParameters().getString(
FORM_SEARCH));
// set the flag to go to the prev page on the next list
if (search == null) {
state.removeAttribute(STATE_SEARCH);
} else {
state.setAttribute(STATE_SEARCH, search);
}
} // doSite_search
/**
* Handle a Search Clear request.
*/
public void doSite_search_clear(RunData data, Context context) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// clear the search
state.removeAttribute(STATE_SEARCH);
} // doSite_search_clear
private void coursesIntoContext(SessionState state, Context context,
Site site) {
List providerCourseList = getProviderCourseList(StringUtil
.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null && providerCourseList.size() > 0) {
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
String sectionTitleString = "";
for(int i = 0; i < providerCourseList.size(); i++)
{
String sectionId = (String) providerCourseList.get(i);
try
{
Section s = cms.getSection(sectionId);
sectionTitleString = (i>0)?sectionTitleString + "<br />" + s.getTitle():s.getTitle();
}
catch (Exception e)
{
M_log.warn("coursesIntoContext " + e.getMessage() + " sectionId=" + sectionId);
}
}
context.put("providedSectionTitle", sectionTitleString);
context.put("providerCourseList", providerCourseList);
}
// put manual requested courses into context
courseListFromStringIntoContext(state, context, site, STATE_CM_REQUESTED_SECTIONS, STATE_CM_REQUESTED_SECTIONS, "cmRequestedCourseList");
// put manual requested courses into context
courseListFromStringIntoContext(state, context, site, PROP_SITE_REQUEST_COURSE, SITE_MANUAL_COURSE_LIST, "manualCourseList");
}
private void courseListFromStringIntoContext(SessionState state, Context context, Site site, String site_prop_name, String state_attribute_string, String context_string) {
String courseListString = StringUtil.trimToNull(site.getProperties().getProperty(site_prop_name));
if (courseListString != null) {
List courseList = new Vector();
if (courseListString.indexOf("+") != -1) {
courseList = new ArrayList(Arrays.asList(courseListString.split("\\+")));
} else {
courseList.add(courseListString);
}
if (state_attribute_string.equals(STATE_CM_REQUESTED_SECTIONS))
{
// need to construct the list of SectionObjects
List<SectionObject> soList = new Vector();
for (int i=0; i<courseList.size();i++)
{
String courseEid = (String) courseList.get(i);
try
{
Section s = cms.getSection(courseEid);
if (s!=null)
soList.add(new SectionObject(s));
}
catch (Exception e)
{
M_log.warn(e.getMessage() + courseEid);
}
}
if (soList.size() > 0)
state.setAttribute(STATE_CM_REQUESTED_SECTIONS, soList);
}
else
{
// the list is of String objects
state.setAttribute(state_attribute_string, courseList);
}
}
context.put(context_string, state.getAttribute(state_attribute_string));
}
/**
* buildInstructorSectionsList Build the CourseListItem list for this
* Instructor for the requested Term
*
*/
private void buildInstructorSectionsList(SessionState state,
ParameterParser params, Context context) {
// Site information
// The sections of the specified term having this person as Instructor
context.put("providerCourseSectionList", state
.getAttribute("providerCourseSectionList"));
context.put("manualCourseSectionList", state
.getAttribute("manualCourseSectionList"));
context.put("term", (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED));
setTermListForContext(context, state, true); //-> future terms only
context.put(STATE_TERM_COURSE_LIST, state
.getAttribute(STATE_TERM_COURSE_LIST));
context.put("tlang", rb);
} // buildInstructorSectionsList
/**
* getProviderCourseList a course site/realm id in one of three formats, for
* a single section, for multiple sections of the same course, or for a
* cross-listing having multiple courses. getProviderCourseList parses a
* realm id into year, term, campus_code, catalog_nbr, section components.
*
* @param id
* is a String representation of the course realm id (external
* id).
*/
private List getProviderCourseList(String id) {
Vector rv = new Vector();
if (id == null || id == NULL_STRING) {
return rv;
}
// Break Provider Id into course id parts
String[] courseIds = groupProvider.unpackId(id);
// Iterate through course ids
for (int i=0; i<courseIds.length; i++) {
String courseId = (String) courseIds[i];
rv.add(courseId);
}
return rv;
} // getProviderCourseList
/**
* {@inheritDoc}
*/
protected int sizeResources(SessionState state) {
int size = 0;
String search = "";
String userId = SessionManager.getCurrentSessionUserId();
// if called from the site list page
if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) {
search = StringUtil.trimToNull((String) state
.getAttribute(STATE_SEARCH));
if (SecurityService.isSuperUser()) {
// admin-type of user
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(rb.getString("java.allmy"))) {
// search for non-user sites, using
// the criteria
size = SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
null, search, null);
} else if (view.equals(rb.getString("java.my"))) {
// search for a specific user site
// for the particular user id in the
// criteria - exact match only
try {
SiteService.getSite(SiteService
.getUserSiteId(search));
size++;
} catch (IdUnusedException e) {
}
} else if (view.equalsIgnoreCase(rb
.getString("java.gradtools"))) {
// search for gradtools sites
size = SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
state
.getAttribute(GRADTOOLS_SITE_TYPES),
search, null);
} else {
// search for specific type of sites
size = SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
view, search, null);
}
}
} else {
Site userWorkspaceSite = null;
try {
userWorkspaceSite = SiteService.getSite(SiteService
.getUserSiteId(userId));
} catch (IdUnusedException e) {
M_log.warn("Cannot find user "
+ SessionManager.getCurrentSessionUserId()
+ "'s My Workspace site.");
}
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(rb.getString("java.allmy"))) {
view = null;
// add my workspace if any
if (userWorkspaceSite != null) {
if (search != null) {
if (userId.indexOf(search) != -1) {
size++;
}
} else {
size++;
}
}
size += SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
null, search, null);
} else if (view.equalsIgnoreCase(rb
.getString("java.gradtools"))) {
// search for gradtools sites
size += SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
state
.getAttribute(GRADTOOLS_SITE_TYPES),
search, null);
} else {
// search for specific type of sites
size += SiteService
.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
view, search, null);
}
}
}
}
// for SiteInfo list page
else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals(
"12")) {
Collection l = (Collection) state.getAttribute(STATE_PARTICIPANT_LIST);
size = (l != null) ? l.size() : 0;
}
return size;
} // sizeResources
/**
* {@inheritDoc}
*/
protected List readResourcesPage(SessionState state, int first, int last) {
String search = StringUtil.trimToNull((String) state
.getAttribute(STATE_SEARCH));
// if called from the site list page
if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) {
// get sort type
SortType sortType = null;
String sortBy = (String) state.getAttribute(SORTED_BY);
boolean sortAsc = (new Boolean((String) state
.getAttribute(SORTED_ASC))).booleanValue();
if (sortBy.equals(SortType.TITLE_ASC.toString())) {
sortType = sortAsc ? SortType.TITLE_ASC : SortType.TITLE_DESC;
} else if (sortBy.equals(SortType.TYPE_ASC.toString())) {
sortType = sortAsc ? SortType.TYPE_ASC : SortType.TYPE_DESC;
} else if (sortBy.equals(SortType.CREATED_BY_ASC.toString())) {
sortType = sortAsc ? SortType.CREATED_BY_ASC
: SortType.CREATED_BY_DESC;
} else if (sortBy.equals(SortType.CREATED_ON_ASC.toString())) {
sortType = sortAsc ? SortType.CREATED_ON_ASC
: SortType.CREATED_ON_DESC;
} else if (sortBy.equals(SortType.PUBLISHED_ASC.toString())) {
sortType = sortAsc ? SortType.PUBLISHED_ASC
: SortType.PUBLISHED_DESC;
}
if (SecurityService.isSuperUser()) {
// admin-type of user
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(rb.getString("java.allmy"))) {
// search for non-user sites, using the
// criteria
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
null, search, null, sortType,
new PagingPosition(first, last));
} else if (view.equalsIgnoreCase(rb.getString("java.my"))) {
// search for a specific user site for
// the particular user id in the
// criteria - exact match only
List rv = new Vector();
try {
Site userSite = SiteService.getSite(SiteService
.getUserSiteId(search));
rv.add(userSite);
} catch (IdUnusedException e) {
}
return rv;
} else if (view.equalsIgnoreCase(rb
.getString("java.gradtools"))) {
// search for gradtools sites
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.NON_USER,
state
.getAttribute(GRADTOOLS_SITE_TYPES),
search, null, sortType,
new PagingPosition(first, last));
} else {
// search for a specific site
return SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ANY,
view, search, null, sortType,
new PagingPosition(first, last));
}
}
} else {
List rv = new Vector();
Site userWorkspaceSite = null;
String userId = SessionManager.getCurrentSessionUserId();
try {
userWorkspaceSite = SiteService.getSite(SiteService
.getUserSiteId(userId));
} catch (IdUnusedException e) {
M_log.warn("Cannot find user "
+ SessionManager.getCurrentSessionUserId()
+ "'s My Workspace site.");
}
String view = (String) state.getAttribute(STATE_VIEW_SELECTED);
if (view != null) {
if (view.equals(rb.getString("java.allmy"))) {
view = null;
// add my workspace if any
if (userWorkspaceSite != null) {
if (search != null) {
if (userId.indexOf(search) != -1) {
rv.add(userWorkspaceSite);
}
} else {
rv.add(userWorkspaceSite);
}
}
rv
.addAll(SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
null, search, null, sortType,
new PagingPosition(first, last)));
} else if (view.equalsIgnoreCase(rb
.getString("java.gradtools"))) {
// search for a specific user site for
// the particular user id in the
// criteria - exact match only
rv
.addAll(SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
state
.getAttribute(GRADTOOLS_SITE_TYPES),
search, null, sortType,
new PagingPosition(first, last)));
} else {
rv
.addAll(SiteService
.getSites(
org.sakaiproject.site.api.SiteService.SelectionType.ACCESS,
view, search, null, sortType,
new PagingPosition(first, last)));
}
}
return rv;
}
}
// if in Site Info list view
else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals(
"12")) {
List participants = (state.getAttribute(STATE_PARTICIPANT_LIST) != null) ? collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)): new Vector();
String sortedBy = (String) state.getAttribute(SORTED_BY);
String sortedAsc = (String) state.getAttribute(SORTED_ASC);
Iterator sortedParticipants = null;
if (sortedBy != null) {
sortedParticipants = new SortedIterator(participants
.iterator(), new SiteComparator(sortedBy,
sortedAsc));
participants.clear();
while (sortedParticipants.hasNext()) {
participants.add(sortedParticipants.next());
}
}
PagingPosition page = new PagingPosition(first, last);
page.validate(participants.size());
participants = participants.subList(page.getFirst() - 1, page.getLast());
return participants;
}
return null;
} // readResourcesPage
/**
* get the selected tool ids from import sites
*/
private boolean select_import_tools(ParameterParser params,
SessionState state) {
// has the user selected any tool for importing?
boolean anyToolSelected = false;
Hashtable importTools = new Hashtable();
// the tools for current site
List selectedTools = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // String
// toolId's
for (int i = 0; i < selectedTools.size(); i++) {
// any tools chosen from import sites?
String toolId = (String) selectedTools.get(i);
if (params.getStrings(toolId) != null) {
importTools.put(toolId, new ArrayList(Arrays.asList(params
.getStrings(toolId))));
if (!anyToolSelected) {
anyToolSelected = true;
}
}
}
state.setAttribute(STATE_IMPORT_SITE_TOOL, importTools);
return anyToolSelected;
} // select_import_tools
/**
* Is it from the ENW edit page?
*
* @return ture if the process went through the ENW page; false, otherwise
*/
private boolean fromENWModifyView(SessionState state) {
boolean fromENW = false;
List oTools = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
List toolList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
for (int i = 0; i < toolList.size() && !fromENW; i++) {
String toolId = (String) toolList.get(i);
if (toolId.equals("sakai.mailbox")
|| isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) {
if (oTools == null) {
// if during site creation proces
fromENW = true;
} else if (!oTools.contains(toolId)) {
// if user is adding either EmailArchive tool, News tool or
// Web Content tool, go to the Customize page for the tool
fromENW = true;
}
}
}
return fromENW;
}
/**
* doNew_site is called when the Site list tool bar New... button is clicked
*
*/
public void doNew_site(RunData data) throws Exception {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// start clean
cleanState(state);
List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES);
if (siteTypes != null) {
if (siteTypes.size() == 1) {
String siteType = (String) siteTypes.get(0);
if (!siteType.equals(ServerConfigurationService.getString(
"courseSiteType", (String) state.getAttribute(STATE_COURSE_SITE_TYPE)))) {
// if only one site type is allowed and the type isn't
// course type
// skip the select site type step
setNewSiteType(state, siteType);
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
}
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
}
}
} // doNew_site
/**
* doMenu_site_delete is called when the Site list tool bar Delete button is
* clicked
*
*/
public void doMenu_site_delete(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (params.getStrings("selectedMembers") == null) {
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
String[] removals = (String[]) params.getStrings("selectedMembers");
state.setAttribute(STATE_SITE_REMOVALS, removals);
// present confirm delete template
state.setAttribute(STATE_TEMPLATE_INDEX, "8");
} // doMenu_site_delete
public void doSite_delete_confirmed(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (params.getStrings("selectedMembers") == null) {
M_log
.warn("SiteAction.doSite_delete_confirmed selectedMembers null");
state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the
// site list
return;
}
List chosenList = new ArrayList(Arrays.asList(params
.getStrings("selectedMembers"))); // Site id's of checked
// sites
if (!chosenList.isEmpty()) {
for (ListIterator i = chosenList.listIterator(); i.hasNext();) {
String id = (String) i.next();
String site_title = NULL_STRING;
try {
site_title = SiteService.getSite(id).getTitle();
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.doSite_delete_confirmed - IdUnusedException "
+ id);
addAlert(state, rb.getString("java.sitewith") + " " + id
+ " " + rb.getString("java.couldnt") + " ");
}
if (SiteService.allowRemoveSite(id)) {
try {
Site site = SiteService.getSite(id);
site_title = site.getTitle();
SiteService.removeSite(site);
} catch (IdUnusedException e) {
M_log
.warn("SiteAction.doSite_delete_confirmed - IdUnusedException "
+ id);
addAlert(state, rb.getString("java.sitewith") + " "
+ site_title + "(" + id + ") "
+ rb.getString("java.couldnt") + " ");
} catch (PermissionException e) {
M_log
.warn("SiteAction.doSite_delete_confirmed - PermissionException, site "
+ site_title + "(" + id + ").");
addAlert(state, site_title + " "
+ rb.getString("java.dontperm") + " ");
}
} else {
M_log
.warn("SiteAction.doSite_delete_confirmed - allowRemoveSite failed for site "
+ id);
addAlert(state, site_title + " "
+ rb.getString("java.dontperm") + " ");
}
}
}
state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the site
// list
// TODO: hard coding this frame id is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
} // doSite_delete_confirmed
/**
* get the Site object based on SessionState attribute values
*
* @return Site object related to current state; null if no such Site object
* could be found
*/
protected Site getStateSite(SessionState state) {
Site site = null;
if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) {
try {
site = SiteService.getSite((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
} catch (Exception ignore) {
}
}
return site;
} // getStateSite
/**
* get the Group object based on SessionState attribute values
*
* @return Group object related to current state; null if no such Group
* object could be found
*/
protected Group getStateGroup(SessionState state) {
Group group = null;
Site site = getStateSite(state);
if (site != null && state.getAttribute(STATE_GROUP_INSTANCE_ID) != null) {
try {
group = site.getGroup((String) state
.getAttribute(STATE_GROUP_INSTANCE_ID));
} catch (Exception ignore) {
}
}
return group;
} // getStateGroup
/**
* do called when "eventSubmit_do" is in the request parameters to c is
* called from site list menu entry Revise... to get a locked site as
* editable and to go to the correct template to begin DB version of writes
* changes to disk at site commit whereas XML version writes at server
* shutdown
*/
public void doGet_site(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// check form filled out correctly
if (params.getStrings("selectedMembers") == null) {
addAlert(state, rb.getString("java.nosites"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
List chosenList = new ArrayList(Arrays.asList(params
.getStrings("selectedMembers"))); // Site id's of checked
// sites
String siteId = "";
if (!chosenList.isEmpty()) {
if (chosenList.size() != 1) {
addAlert(state, rb.getString("java.please"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
return;
}
siteId = (String) chosenList.get(0);
getReviseSite(state, siteId);
state.setAttribute(SORTED_BY, SORTED_BY_PARTICIPANT_NAME);
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
}
// reset the paging info
resetPaging(state);
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
state.setAttribute(STATE_PAGESIZE_SITESETUP, state
.getAttribute(STATE_PAGESIZE));
}
Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO);
if (!h.containsKey(siteId)) {
// when first entered Site Info, set the participant list size to
// 200 as default
state.setAttribute(STATE_PAGESIZE, new Integer(200));
// update
h.put(siteId, new Integer(200));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
} else {
// restore the page size in site info tool
state.setAttribute(STATE_PAGESIZE, h.get(siteId));
}
} // doGet_site
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doMenu_site_reuse(RunData data) throws Exception {
// called from chef_site-list.vm after a site has been selected from
// list
// create a new Site object based on selected Site object and put in
// state
//
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} // doMenu_site_reuse
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doMenu_site_revise(RunData data) throws Exception {
// called from chef_site-list.vm after a site has been selected from
// list
// get site as Site object, check SiteCreationStatus and SiteType of
// site, put in state, and set STATE_TEMPLATE_INDEX correctly
// set mode to state_mode_site_type
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} // doMenu_site_revise
/**
* doView_sites is called when "eventSubmit_doView_sites" is in the request
* parameters
*/
public void doView_sites(RunData data) throws Exception {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.setAttribute(STATE_VIEW_SELECTED, params.getString("view"));
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
resetPaging(state);
} // doView_sites
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doView(RunData data) throws Exception {
// called from chef_site-list.vm with a select option to build query of
// sites
//
//
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "1");
} // doView
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doSite_type(RunData data) {
/*
* for measuring how long it takes to load sections java.util.Date date =
* new java.util.Date(); M_log.debug("***1. start preparing
* section:"+date);
*/
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
int index = Integer.valueOf(params.getString("template-index"))
.intValue();
actionForTemplate("continue", index, params, state);
String type = StringUtil.trimToNull(params.getString("itemType"));
int totalSteps = 0;
if (type == null) {
addAlert(state, rb.getString("java.select") + " ");
} else {
setNewSiteType(state, type);
if (type.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
User user = UserDirectoryService.getCurrentUser();
String currentUserId = user.getEid();
String userId = params.getString("userId");
if (userId == null || "".equals(userId)) {
userId = currentUserId;
} else {
// implies we are trying to pick sections owned by other
// users. Currently "select section by user" page only
// take one user per sitte request - daisy's note 1
ArrayList<String> list = new ArrayList();
list.add(userId);
state.setAttribute(STATE_CM_AUTHORIZER_LIST, list);
}
state.setAttribute(STATE_INSTRUCTOR_SELECTED, userId);
String academicSessionEid = params.getString("selectTerm");
AcademicSession t = cms.getAcademicSession(academicSessionEid);
state.setAttribute(STATE_TERM_SELECTED, t);
if (t != null) {
List sections = prepareCourseAndSectionListing(userId, t
.getEid(), state);
isFutureTermSelected(state);
if (sections != null && sections.size() > 0) {
state.setAttribute(STATE_TERM_COURSE_LIST, sections);
state.setAttribute(STATE_TEMPLATE_INDEX, "36");
state.setAttribute(STATE_AUTO_ADD, Boolean.TRUE);
} else {
state.removeAttribute(STATE_TERM_COURSE_LIST);
Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean("wsetup.skipCourseSectionSelection", Boolean.FALSE);
if (!skipCourseSectionSelection.booleanValue() && courseManagementIsImplemented())
{
state.setAttribute(STATE_TEMPLATE_INDEX, "53");
}
else
{
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
}
}
} else { // not course type
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
totalSteps = 5;
}
} else if (type.equals("project")) {
totalSteps = 4;
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
} else if (type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) {
// if a GradTools site use pre-defined site info and exclude
// from public listing
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
User currentUser = UserDirectoryService.getCurrentUser();
siteInfo.title = rb.getString("java.grad") + " - "
+ currentUser.getId();
siteInfo.description = rb.getString("java.gradsite") + " "
+ currentUser.getDisplayName();
siteInfo.short_description = rb.getString("java.grad") + " - "
+ currentUser.getId();
siteInfo.include = false;
state.setAttribute(STATE_SITE_INFO, siteInfo);
// skip directly to confirm creation of site
state.setAttribute(STATE_TEMPLATE_INDEX, "42");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
}
}
if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) == null) {
state
.setAttribute(SITE_CREATE_TOTAL_STEPS, new Integer(
totalSteps));
}
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) == null) {
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(1));
}
} // doSite_type
/**
* Determine whether the selected term is considered of "future term"
* @param state
* @param t
*/
private void isFutureTermSelected(SessionState state) {
AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
int weeks = 0;
Calendar c = (Calendar) Calendar.getInstance().clone();
try {
weeks = Integer
.parseInt(ServerConfigurationService
.getString(
"roster.available.weeks.before.term.start",
"0"));
c.add(Calendar.DATE, weeks * 7);
} catch (Exception ignore) {
}
if (t.getStartDate() != null && c.getTimeInMillis() < t.getStartDate().getTime()) {
// if a future term is selected
state.setAttribute(STATE_FUTURE_TERM_SELECTED,
Boolean.TRUE);
} else {
state.setAttribute(STATE_FUTURE_TERM_SELECTED,
Boolean.FALSE);
}
}
public void doChange_user(RunData data) {
doSite_type(data);
} // doChange_user
/**
* cleanEditGroupParams clean the state parameters used by editing group
* process
*
*/
public void cleanEditGroupParams(SessionState state) {
state.removeAttribute(STATE_GROUP_INSTANCE_ID);
state.removeAttribute(STATE_GROUP_TITLE);
state.removeAttribute(STATE_GROUP_DESCRIPTION);
state.removeAttribute(STATE_GROUP_MEMBERS);
state.removeAttribute(STATE_GROUP_REMOVE);
} // cleanEditGroupParams
/**
* doGroup_edit
*
*/
public void doGroup_update(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
Set gMemberSet = (Set) state.getAttribute(STATE_GROUP_MEMBERS);
Site site = getStateSite(state);
String title = StringUtil.trimToNull(params.getString(rb
.getString("group.title")));
state.setAttribute(STATE_GROUP_TITLE, title);
String description = StringUtil.trimToZero(params.getString(rb
.getString("group.description")));
state.setAttribute(STATE_GROUP_DESCRIPTION, description);
boolean found = false;
String option = params.getString("option");
if (option.equals("add")) {
// add selected members into it
if (params.getStrings("generallist") != null) {
List addMemberIds = new ArrayList(Arrays.asList(params
.getStrings("generallist")));
for (int i = 0; i < addMemberIds.size(); i++) {
String aId = (String) addMemberIds.get(i);
found = false;
for (Iterator iSet = gMemberSet.iterator(); !found
&& iSet.hasNext();) {
if (((Member) iSet.next()).getUserEid().equals(aId)) {
found = true;
}
}
if (!found) {
try {
User u = UserDirectoryService.getUser(aId);
gMemberSet.add(site.getMember(u.getId()));
} catch (UserNotDefinedException e) {
try {
User u2 = UserDirectoryService
.getUserByEid(aId);
gMemberSet.add(site.getMember(u2.getId()));
} catch (UserNotDefinedException ee) {
M_log.warn(this + ee.getMessage() + aId);
}
}
}
}
}
state.setAttribute(STATE_GROUP_MEMBERS, gMemberSet);
} else if (option.equals("remove")) {
// update the group member list by remove selected members from it
if (params.getStrings("grouplist") != null) {
List removeMemberIds = new ArrayList(Arrays.asList(params
.getStrings("grouplist")));
for (int i = 0; i < removeMemberIds.size(); i++) {
found = false;
for (Iterator iSet = gMemberSet.iterator(); !found
&& iSet.hasNext();) {
Member mSet = (Member) iSet.next();
if (mSet.getUserId().equals(
(String) removeMemberIds.get(i))) {
found = true;
gMemberSet.remove(mSet);
}
}
}
}
state.setAttribute(STATE_GROUP_MEMBERS, gMemberSet);
} else if (option.equals("cancel")) {
// cancel from the update the group member process
doCancel(data);
cleanEditGroupParams(state);
} else if (option.equals("save")) {
Group group = null;
if (site != null
&& state.getAttribute(STATE_GROUP_INSTANCE_ID) != null) {
try {
group = site.getGroup((String) state
.getAttribute(STATE_GROUP_INSTANCE_ID));
} catch (Exception ignore) {
}
}
if (title == null) {
addAlert(state, rb.getString("editgroup.titlemissing"));
} else {
if (group == null) {
// when adding a group, check whether the group title has
// been used already
boolean titleExist = false;
for (Iterator iGroups = site.getGroups().iterator(); !titleExist
&& iGroups.hasNext();) {
Group iGroup = (Group) iGroups.next();
if (iGroup.getTitle().equals(title)) {
// found same title
titleExist = true;
}
}
if (titleExist) {
addAlert(state, rb.getString("group.title.same"));
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
if (group == null) {
// adding new group
group = site.addGroup();
group.getProperties().addProperty(
GROUP_PROP_WSETUP_CREATED, Boolean.TRUE.toString());
}
if (group != null) {
group.setTitle(title);
group.setDescription(description);
// save the modification to group members
// remove those no longer included in the group
Set members = group.getMembers();
for (Iterator iMembers = members.iterator(); iMembers
.hasNext();) {
found = false;
String mId = ((Member) iMembers.next()).getUserId();
for (Iterator iMemberSet = gMemberSet.iterator(); !found
&& iMemberSet.hasNext();) {
if (mId.equals(((Member) iMemberSet.next())
.getUserId())) {
found = true;
}
}
if (!found) {
group.removeMember(mId);
}
}
// add those seleted members
for (Iterator iMemberSet = gMemberSet.iterator(); iMemberSet
.hasNext();) {
String memberId = ((Member) iMemberSet.next())
.getUserId();
if (group.getUserRole(memberId) == null) {
Role r = site.getUserRole(memberId);
Member m = site.getMember(memberId);
// for every member added through the "Manage
// Groups" interface, he should be defined as
// non-provided
group.addMember(memberId, r != null ? r.getId()
: "", m != null ? m.isActive() : true,
false);
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
try {
SiteService.save(site);
} catch (IdUnusedException e) {
} catch (PermissionException e) {
}
// return to group list view
state.setAttribute(STATE_TEMPLATE_INDEX, "49");
cleanEditGroupParams(state);
}
}
}
}
} // doGroup_updatemembers
/**
* doGroup_new
*
*/
public void doGroup_new(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (state.getAttribute(STATE_GROUP_TITLE) == null) {
state.setAttribute(STATE_GROUP_TITLE, "");
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) == null) {
state.setAttribute(STATE_GROUP_DESCRIPTION, "");
}
if (state.getAttribute(STATE_GROUP_MEMBERS) == null) {
state.setAttribute(STATE_GROUP_MEMBERS, new HashSet());
}
state.setAttribute(STATE_TEMPLATE_INDEX, "50");
} // doGroup_new
/**
* doGroup_edit
*
*/
public void doGroup_edit(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String groupId = data.getParameters().getString("groupId");
state.setAttribute(STATE_GROUP_INSTANCE_ID, groupId);
Site site = getStateSite(state);
if (site != null) {
Group g = site.getGroup(groupId);
if (g != null) {
if (state.getAttribute(STATE_GROUP_TITLE) == null) {
state.setAttribute(STATE_GROUP_TITLE, g.getTitle());
}
if (state.getAttribute(STATE_GROUP_DESCRIPTION) == null) {
state.setAttribute(STATE_GROUP_DESCRIPTION, g
.getDescription());
}
if (state.getAttribute(STATE_GROUP_MEMBERS) == null) {
// double check the member existance
Set gMemberSet = g.getMembers();
Set rvGMemberSet = new HashSet();
for (Iterator iSet = gMemberSet.iterator(); iSet.hasNext();) {
Member member = (Member) iSet.next();
try {
UserDirectoryService.getUser(member.getUserId());
((Set) rvGMemberSet).add(member);
} catch (UserNotDefinedException e) {
// cannot find user
M_log.warn(this + rb.getString("user.notdefined")
+ member.getUserId());
}
}
state.setAttribute(STATE_GROUP_MEMBERS, rvGMemberSet);
}
}
}
state.setAttribute(STATE_TEMPLATE_INDEX, "50");
} // doGroup_edit
/**
* doGroup_remove_prep Go to confirmation page before deleting group(s)
*
*/
public void doGroup_remove_prep(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String[] removeGroupIds = data.getParameters().getStrings(
"removeGroups");
if (removeGroupIds.length > 0) {
state.setAttribute(STATE_GROUP_REMOVE, removeGroupIds);
state.setAttribute(STATE_TEMPLATE_INDEX, "51");
}
} // doGroup_remove_prep
/**
* doGroup_remove_confirmed Delete selected groups after confirmation
*
*/
public void doGroup_remove_confirmed(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String[] removeGroupIds = (String[]) state
.getAttribute(STATE_GROUP_REMOVE);
Site site = getStateSite(state);
for (int i = 0; i < removeGroupIds.length; i++) {
if (site != null) {
Group g = site.getGroup(removeGroupIds[i]);
if (g != null) {
site.removeGroup(g);
}
}
}
try {
SiteService.save(site);
} catch (IdUnusedException e) {
addAlert(state, rb.getString("editgroup.site.notfound.alert"));
} catch (PermissionException e) {
addAlert(state, rb.getString("editgroup.site.permission.alert"));
}
if (state.getAttribute(STATE_MESSAGE) == null) {
cleanEditGroupParams(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "49");
}
} // doGroup_remove_confirmed
/**
* doMenu_edit_site_info The menu choice to enter group view
*
*/
public void doMenu_group(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// reset sort criteria
state.setAttribute(SORTED_BY, rb.getString("group.title"));
state.setAttribute(SORTED_ASC, Boolean.TRUE.toString());
state.setAttribute(STATE_TEMPLATE_INDEX, "49");
} // doMenu_group
/**
*
*/
private void removeSection(SessionState state, ParameterParser params)
{
// v2.4 - added by daisyf
// RemoveSection - remove any selected course from a list of
// provider courses
// check if any section need to be removed
removeAnyFlagedSection(state, params);
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
List providerChosenList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
collectNewSiteInfo(siteInfo, state, params, providerChosenList);
// next step
//state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2));
}
/**
* dispatch to different functions based on the option value in the
* parameter
*/
public void doManual_add_course(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
if (option.equalsIgnoreCase("change") || option.equalsIgnoreCase("add")) {
readCourseSectionInfo(state, params);
String uniqname = StringUtil.trimToNull(params
.getString("uniqname"));
state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname);
updateSiteInfo(params, state);
if (option.equalsIgnoreCase("add")) {
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& !((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue()) {
// if a future term is selected, do not check authorization
// uniqname
if (uniqname == null) {
addAlert(state, rb.getString("java.author")
+ " "
+ ServerConfigurationService
.getString("officialAccountName")
+ ". ");
} else {
// in case of multiple instructors
List instructors = new ArrayList(Arrays.asList(uniqname.split(",")));
for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();)
{
try {
UserDirectoryService.getUserByEid(StringUtil.trimToZero((String) iInstructors.next()));
} catch (UserNotDefinedException e) {
addAlert(
state,
rb.getString("java.validAuthor1")
+ " "
+ ServerConfigurationService
.getString("officialAccountName")
+ " "
+ rb.getString("java.validAuthor2"));
}
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
if (getStateSite(state) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
}
}
updateCurrentStep(state, true);
}
} else if (option.equalsIgnoreCase("back")) {
doBack(data);
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, false);
}
} else if (option.equalsIgnoreCase("cancel")) {
if (getStateSite(state) == null) {
doCancel_create(data);
} else {
doCancel(data);
}
} else if (option.equalsIgnoreCase("removeSection"))
{
// remove selected section
removeSection(state, params);
}
} // doManual_add_course
/**
* dispatch to different functions based on the option value in the
* parameter
*/
public void doSite_information(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
if (option.equalsIgnoreCase("continue"))
{
doContinue(data);
} else if (option.equalsIgnoreCase("back")) {
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
if (getStateSite(state) == null) {
doCancel_create(data);
} else {
doCancel(data);
}
} else if (option.equalsIgnoreCase("removeSection"))
{
// remove selected section
removeSection(state, params);
}
} // doSite_information
/**
* read the input information of subject, course and section in the manual
* site creation page
*/
private void readCourseSectionInfo(SessionState state,
ParameterParser params) {
String option = params.getString("option");
int oldNumber = 1;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
oldNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue();
}
// read the user input
int validInputSites = 0;
boolean validInput = true;
List multiCourseInputs = new Vector();
for (int i = 0; i < oldNumber; i++) {
List requiredFields = sectionFieldProvider.getRequiredFields();
List aCourseInputs = new Vector();
int emptyInputNum = 0;
// iterate through all required fields
for (int k = 0; k < requiredFields.size(); k++) {
SectionField sectionField = (SectionField) requiredFields
.get(k);
String fieldLabel = sectionField.getLabelKey();
String fieldInput = StringUtil.trimToZero(params
.getString(fieldLabel + i));
sectionField.setValue(fieldInput);
aCourseInputs.add(sectionField);
if (fieldInput.length() == 0) {
// is this an empty String input?
emptyInputNum++;
}
}
// is any input invalid?
if (emptyInputNum == 0) {
// valid if all the inputs are not empty
multiCourseInputs.add(validInputSites++, aCourseInputs);
} else if (emptyInputNum == requiredFields.size()) {
// ignore if all inputs are empty
if (option.equalsIgnoreCase("change"))
{
multiCourseInputs.add(validInputSites++, aCourseInputs);
}
} else {
// input invalid
validInput = false;
}
}
// how many more course/section to include in the site?
if (option.equalsIgnoreCase("change")) {
if (params.getString("number") != null) {
int newNumber = Integer.parseInt(params.getString("number"));
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(oldNumber + newNumber));
List requiredFields = sectionFieldProvider.getRequiredFields();
for (int j = 0; j < newNumber; j++) {
// add a new course input
List aCourseInputs = new Vector();
// iterate through all required fields
for (int m = 0; m < requiredFields.size(); m++) {
aCourseInputs = sectionFieldProvider.getRequiredFields();
}
multiCourseInputs.add(aCourseInputs);
}
}
}
state.setAttribute(STATE_MANUAL_ADD_COURSE_FIELDS, multiCourseInputs);
if (!option.equalsIgnoreCase("change")) {
if (!validInput || validInputSites == 0) {
// not valid input
addAlert(state, rb.getString("java.miss"));
}
// valid input, adjust the add course number
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer( validInputSites));
}
// set state attributes
state.setAttribute(FORM_ADDITIONAL, StringUtil.trimToZero(params
.getString("additional")));
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
List providerCourseList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
// store the manually requested sections in one site property
if ((providerCourseList == null || providerCourseList.size() == 0)
&& multiCourseInputs.size() > 0) {
AcademicSession t = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
String sectionEid = sectionFieldProvider.getSectionEid(t.getEid(),
(List) multiCourseInputs.get(0));
// default title
String title = sectionEid;
try {
title = cms.getSection(sectionEid).getTitle();
} catch (Exception e) {
// ignore
}
siteInfo.title = title;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
} // readCourseSectionInfo
/**
* set the site type for new site
*
* @param type
* The type String
*/
private void setNewSiteType(SessionState state, String type) {
state.setAttribute(STATE_SITE_TYPE, type);
// start out with fresh site information
SiteInfo siteInfo = new SiteInfo();
siteInfo.site_type = type;
siteInfo.published = true;
state.setAttribute(STATE_SITE_INFO, siteInfo);
// set tool registration list
setToolRegistrationList(state, type);
}
/**
* Set the state variables for tool registration list basd on site type
* @param state
* @param type
*/
private void setToolRegistrationList(SessionState state, String type) {
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET);
// get the tool id set which allows for multiple instances
Set multipleToolIdSet = new HashSet();
// get registered tools list
Set categories = new HashSet();
categories.add(type);
Set toolRegistrations = ToolManager.findTools(categories, null);
if ((toolRegistrations == null || toolRegistrations.size() == 0)
&& state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null)
{
// use default site type and try getting tools again
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
categories.clear();
categories.add(type);
toolRegistrations = ToolManager.findTools(categories, null);
}
List tools = new Vector();
SortedIterator i = new SortedIterator(toolRegistrations.iterator(),
new ToolComparator());
for (; i.hasNext();) {
// form a new Tool
Tool tr = (Tool) i.next();
MyTool newTool = new MyTool();
newTool.title = tr.getTitle();
newTool.id = tr.getId();
newTool.description = tr.getDescription();
tools.add(newTool);
if (isMultipleInstancesAllowed(findOriginalToolId(state, tr.getId())))
{
// of a tool which allows multiple instances
multipleToolIdSet.add(tr.getId());
}
}
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, tools);
state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet);
}
/**
* Set the field on which to sort the list of students
*
*/
public void doSort_roster(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the field on which to sort the student list
ParameterParser params = data.getParameters();
String criterion = params.getString("criterion");
// current sorting sequence
String asc = "";
if (!criterion.equals(state.getAttribute(SORTED_BY))) {
state.setAttribute(SORTED_BY, criterion);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, asc);
} else {
// current sorting sequence
asc = (String) state.getAttribute(SORTED_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString())) {
asc = Boolean.FALSE.toString();
} else {
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_ASC, asc);
}
} // doSort_roster
/**
* Set the field on which to sort the list of sites
*
*/
public void doSort_sites(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// call this method at the start of a sort for proper paging
resetPaging(state);
// get the field on which to sort the site list
ParameterParser params = data.getParameters();
String criterion = params.getString("criterion");
// current sorting sequence
String asc = "";
if (!criterion.equals(state.getAttribute(SORTED_BY))) {
state.setAttribute(SORTED_BY, criterion);
asc = Boolean.TRUE.toString();
state.setAttribute(SORTED_ASC, asc);
} else {
// current sorting sequence
asc = (String) state.getAttribute(SORTED_ASC);
// toggle between the ascending and descending sequence
if (asc.equals(Boolean.TRUE.toString())) {
asc = Boolean.FALSE.toString();
} else {
asc = Boolean.TRUE.toString();
}
state.setAttribute(SORTED_ASC, asc);
}
state.setAttribute(SORTED_BY, criterion);
} // doSort_sites
/**
* doContinue is called when "eventSubmit_doContinue" is in the request
* parameters
*/
public void doContinue(RunData data) {
// Put current form data in state and continue to the next template,
// make any permanent changes
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
int index = Integer.valueOf(params.getString("template-index"))
.intValue();
// Let actionForTemplate know to make any permanent changes before
// continuing to the next template
String direction = "continue";
String option = params.getString("option");
actionForTemplate(direction, index, params, state);
if (state.getAttribute(STATE_MESSAGE) == null) {
if (index == 36 && ("add").equals(option)) {
// this is the Add extra Roster(s) case after a site is created
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
} else if (params.getString("continue") != null) {
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("continue"));
}
}
}// doContinue
/**
* handle with continue add new course site options
*
*/
public void doContinue_new_course(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = data.getParameters().getString("option");
if (option.equals("continue")) {
doContinue(data);
} else if (option.equals("cancel")) {
doCancel_create(data);
} else if (option.equals("back")) {
doBack(data);
} else if (option.equals("cancel")) {
doCancel_create(data);
}
else if (option.equalsIgnoreCase("change")) {
// change term
String termId = params.getString("selectTerm");
AcademicSession t = cms.getAcademicSession(termId);
state.setAttribute(STATE_TERM_SELECTED, t);
isFutureTermSelected(state);
} else if (option.equalsIgnoreCase("cancel_edit")) {
// cancel
doCancel(data);
} else if (option.equalsIgnoreCase("add")) {
isFutureTermSelected(state);
// continue
doContinue(data);
}
} // doContinue_new_course
/**
* doBack is called when "eventSubmit_doBack" is in the request parameters
* Pass parameter to actionForTemplate to request action for backward
* direction
*/
public void doBack(RunData data) {
// Put current form data in state and return to the previous template
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
int currentIndex = Integer.parseInt((String) state
.getAttribute(STATE_TEMPLATE_INDEX));
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("back"));
// Let actionForTemplate know not to make any permanent changes before
// continuing to the next template
String direction = "back";
actionForTemplate(direction, currentIndex, params, state);
}// doBack
/**
* doFinish is called when a site has enough information to be saved as an
* unpublished site
*/
public void doFinish(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("continue"));
int index = Integer.valueOf(params.getString("template-index"))
.intValue();
actionForTemplate("continue", index, params, state);
addNewSite(params, state);
addFeatures(state);
Site site = getStateSite(state);
// for course sites
String siteType = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
String siteId = site.getId();
ResourcePropertiesEdit rp = site.getPropertiesEdit();
AcademicSession term = null;
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
term = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
rp.addProperty(PROP_SITE_TERM, term.getTitle());
rp.addProperty(PROP_SITE_TERM_EID, term.getEid());
}
// update the site and related realm based on the rosters chosen or requested
updateCourseSiteSections(state, siteId, rp, term);
}
// commit site
commitSite(site);
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
// now that the site exists, we can set the email alias when an
// Email Archive tool has been selected
String alias = StringUtil.trimToNull((String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
if (alias != null) {
String channelReference = mailArchiveChannelReference(siteId);
try {
AliasService.setAlias(alias, channelReference);
} catch (IdUsedException ee) {
addAlert(state, rb.getString("java.alias") + " " + alias
+ " " + rb.getString("java.exists"));
} catch (IdInvalidException ee) {
addAlert(state, rb.getString("java.alias") + " " + alias
+ " " + rb.getString("java.isinval"));
} catch (PermissionException ee) {
addAlert(state, rb.getString("java.addalias") + " ");
}
}
// TODO: hard coding this frame id is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
resetPaging(state);
// clean state variables
cleanState(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
}
}// doFinish
/**
* Update course site and related realm based on the roster chosen or requested
* @param state
* @param siteId
* @param rp
* @param term
*/
private void updateCourseSiteSections(SessionState state, String siteId, ResourcePropertiesEdit rp, AcademicSession term) {
// whether this is in the process of editing a site?
boolean editingSite = ((String)state.getAttribute(STATE_SITE_MODE)).equals(SITE_MODE_SITEINFO)?true:false;
List providerCourseList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
int manualAddNumber = 0;
if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
manualAddNumber = ((Integer) state
.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER))
.intValue();
}
List<SectionObject> cmRequestedSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
List<SectionObject> cmAuthorizerSections = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
String realm = SiteService.siteReference(siteId);
if ((providerCourseList != null)
&& (providerCourseList.size() != 0)) {
try {
AuthzGroup realmEdit = AuthzGroupService
.getAuthzGroup(realm);
String providerRealm = buildExternalRealm(siteId, state,
providerCourseList, StringUtil.trimToNull(realmEdit.getProviderGroupId()));
realmEdit.setProviderGroupId(providerRealm);
AuthzGroupService.save(realmEdit);
} catch (GroupNotDefinedException e) {
M_log.warn(this + " IdUnusedException, not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.realm"));
}
// catch (AuthzPermissionException e)
// {
// M_log.warn(this + " PermissionException, user does not
// have permission to edit AuthzGroup object.");
// addAlert(state, rb.getString("java.notaccess"));
// return;
// }
catch (Exception e) {
addAlert(state, this + rb.getString("java.problem"));
}
sendSiteNotification(state, providerCourseList);
}
if (manualAddNumber != 0) {
// set the manual sections to the site property
String manualSections = rp.getProperty(PROP_SITE_REQUEST_COURSE) != null?rp.getProperty(PROP_SITE_REQUEST_COURSE)+"+":"";
// manualCourseInputs is a list of a list of SectionField
List manualCourseInputs = (List) state
.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
// but we want to feed a list of a list of String (input of
// the required fields)
for (int j = 0; j < manualAddNumber; j++) {
manualSections = manualSections.concat(
sectionFieldProvider.getSectionEid(
term.getEid(),
(List) manualCourseInputs.get(j)))
.concat("+");
}
// trim the trailing plus sign
manualSections = trimTrailingString(manualSections, "+");
rp.addProperty(PROP_SITE_REQUEST_COURSE, manualSections);
// send request
sendSiteRequest(state, "new", manualAddNumber, manualCourseInputs, "manual");
}
if (cmRequestedSections != null
&& cmRequestedSections.size() > 0 || state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) {
// set the cmRequest sections to the site property
String cmRequestedSectionString = "";
if (!editingSite)
{
// but we want to feed a list of a list of String (input of
// the required fields)
for (int j = 0; j < cmRequestedSections.size(); j++) {
cmRequestedSectionString = cmRequestedSectionString.concat(( cmRequestedSections.get(j)).eid).concat("+");
}
// trim the trailing plus sign
cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+");
sendSiteRequest(state, "new", cmRequestedSections.size(), cmRequestedSections, "cmRequest");
}
else
{
cmRequestedSectionString = rp.getProperty(STATE_CM_REQUESTED_SECTIONS) != null ? (String) rp.getProperty(STATE_CM_REQUESTED_SECTIONS):"";
// get the selected cm section
if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null )
{
List<SectionObject> cmSelectedSections = (List) state.getAttribute(STATE_CM_SELECTED_SECTIONS);
if (cmRequestedSectionString.length() != 0)
{
cmRequestedSectionString = cmRequestedSectionString.concat("+");
}
for (int j = 0; j < cmSelectedSections.size(); j++) {
cmRequestedSectionString = cmRequestedSectionString.concat(( cmSelectedSections.get(j)).eid).concat("+");
}
// trim the trailing plus sign
cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+");
sendSiteRequest(state, "new", cmSelectedSections.size(), cmSelectedSections, "cmRequest");
}
}
// update site property
if (cmRequestedSectionString.length() > 0)
{
rp.addProperty(STATE_CM_REQUESTED_SECTIONS, cmRequestedSectionString);
}
else
{
rp.removeProperty(STATE_CM_REQUESTED_SECTIONS);
}
}
}
/**
* Trim the trailing occurance of specified string
* @param cmRequestedSectionString
* @param trailingString
* @return
*/
private String trimTrailingString(String cmRequestedSectionString, String trailingString) {
if (cmRequestedSectionString.endsWith(trailingString)) {
cmRequestedSectionString = cmRequestedSectionString.substring(0, cmRequestedSectionString.lastIndexOf(trailingString));
}
return cmRequestedSectionString;
}
/**
* buildExternalRealm creates a site/realm id in one of three formats, for a
* single section, for multiple sections of the same course, or for a
* cross-listing having multiple courses
*
* @param sectionList
* is a Vector of CourseListItem
* @param id
* The site id
*/
private String buildExternalRealm(String id, SessionState state,
List<String> providerIdList, String existingProviderIdString) {
String realm = SiteService.siteReference(id);
if (!AuthzGroupService.allowUpdate(realm)) {
addAlert(state, rb.getString("java.rosters"));
return null;
}
List<String> allProviderIdList = new Vector<String>();
// see if we need to keep existing provider settings
if (existingProviderIdString != null)
{
allProviderIdList.addAll(Arrays.asList(groupProvider.unpackId(existingProviderIdString)));
}
// update the list with newly added providers
allProviderIdList.addAll(providerIdList);
if (allProviderIdList == null || allProviderIdList.size() == 0)
return null;
String[] providers = new String[allProviderIdList.size()];
providers = (String[]) allProviderIdList.toArray(providers);
String providerId = groupProvider.packId(providers);
return providerId;
} // buildExternalRealm
/**
* Notification sent when a course site needs to be set up by Support
*
*/
private void sendSiteRequest(SessionState state, String request,
int requestListSize, List requestFields, String fromContext) {
User cUser = UserDirectoryService.getCurrentUser();
String sendEmailToRequestee = null;
StringBuilder buf = new StringBuilder();
// get the request email from configuration
String requestEmail = getSetupRequestEmailAddress();
if (requestEmail != null) {
String officialAccountName = ServerConfigurationService
.getString("officialAccountName", "");
SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
Site site = getStateSite(state);
String id = site.getId();
String title = site.getTitle();
Time time = TimeService.newTime();
String local_time = time.toStringLocalTime();
String local_date = time.toStringLocalDate();
AcademicSession term = null;
boolean termExist = false;
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
termExist = true;
term = (AcademicSession) state
.getAttribute(STATE_TERM_SELECTED);
}
String productionSiteName = ServerConfigurationService
.getServerName();
String from = NULL_STRING;
String to = NULL_STRING;
String headerTo = NULL_STRING;
String replyTo = NULL_STRING;
String message_subject = NULL_STRING;
String content = NULL_STRING;
String sessionUserName = cUser.getDisplayName();
String additional = NULL_STRING;
if (request.equals("new")) {
additional = siteInfo.getAdditional();
} else {
additional = (String) state.getAttribute(FORM_ADDITIONAL);
}
boolean isFutureTerm = false;
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& ((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue()) {
isFutureTerm = true;
}
// message subject
if (termExist) {
message_subject = rb.getString("java.sitereqfrom") + " "
+ sessionUserName + " " + rb.getString("java.for")
+ " " + term.getEid();
} else {
message_subject = rb.getString("java.official") + " "
+ sessionUserName;
}
// there is no offical instructor for future term sites
String requestId = (String) state
.getAttribute(STATE_SITE_QUEST_UNIQNAME);
if (!isFutureTerm) {
// To site quest account - the instructor of record's
if (requestId != null) {
// in case of multiple instructors
List instructors = new ArrayList(Arrays.asList(requestId.split(",")));
for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();)
{
String instructorId = (String) iInstructors.next();
try {
User instructor = UserDirectoryService.getUserByEid(instructorId);
// reset
buf.setLength(0);
to = instructor.getEmail();
from = requestEmail;
headerTo = to;
replyTo = requestEmail;
buf.append(rb.getString("java.hello") + " \n\n");
buf.append(rb.getString("java.receiv") + " "
+ sessionUserName + ", ");
buf.append(rb.getString("java.who") + "\n");
if (termExist) {
buf.append(term.getTitle());
}
// requested sections
if (fromContext.equals("manual"))
{
addRequestedSectionIntoNotification(state, requestFields, buf);
}
else if (fromContext.equals("cmRequest"))
{
addRequestedCMSectionIntoNotification(state, requestFields, buf);
}
buf.append("\n" + rb.getString("java.sitetitle") + "\t"
+ title + "\n");
buf.append(rb.getString("java.siteid") + "\t" + id);
buf.append("\n\n" + rb.getString("java.according")
+ " " + sessionUserName + " "
+ rb.getString("java.record"));
buf.append(" " + rb.getString("java.canyou") + " "
+ sessionUserName + " "
+ rb.getString("java.assoc") + "\n\n");
buf.append(rb.getString("java.respond") + " "
+ sessionUserName
+ rb.getString("java.appoint") + "\n\n");
buf.append(rb.getString("java.thanks") + "\n");
buf.append(productionSiteName + " "
+ rb.getString("java.support"));
content = buf.toString();
// send the email
EmailService.send(from, to, message_subject, content,
headerTo, replyTo, null);
}
catch (Exception e)
{
sendEmailToRequestee = sendEmailToRequestee == null?instructorId:sendEmailToRequestee.concat(", ").concat(instructorId);
}
}
}
}
// To Support
from = cUser.getEmail();
to = requestEmail;
headerTo = requestEmail;
replyTo = cUser.getEmail();
buf.setLength(0);
buf.append(rb.getString("java.to") + "\t\t" + productionSiteName
+ " " + rb.getString("java.supp") + "\n");
buf.append("\n" + rb.getString("java.from") + "\t"
+ sessionUserName + "\n");
if (request.equals("new")) {
buf.append(rb.getString("java.subj") + "\t"
+ rb.getString("java.sitereq") + "\n");
} else {
buf.append(rb.getString("java.subj") + "\t"
+ rb.getString("java.sitechreq") + "\n");
}
buf.append(rb.getString("java.date") + "\t" + local_date + " "
+ local_time + "\n\n");
if (request.equals("new")) {
buf.append(rb.getString("java.approval") + " "
+ productionSiteName + " "
+ rb.getString("java.coursesite") + " ");
} else {
buf.append(rb.getString("java.approval2") + " "
+ productionSiteName + " "
+ rb.getString("java.coursesite") + " ");
}
if (termExist) {
buf.append(term.getTitle());
}
if (requestListSize > 1) {
buf.append(" " + rb.getString("java.forthese") + " "
+ requestListSize + " " + rb.getString("java.sections")
+ "\n\n");
} else {
buf.append(" " + rb.getString("java.forthis") + "\n\n");
}
// requested sections
if (fromContext.equals("manual"))
{
addRequestedSectionIntoNotification(state, requestFields, buf);
}
else if (fromContext.equals("cmRequest"))
{
addRequestedCMSectionIntoNotification(state, requestFields, buf);
}
buf.append(rb.getString("java.name") + "\t" + sessionUserName
+ " (" + officialAccountName + " " + cUser.getEid()
+ ")\n");
buf.append(rb.getString("java.email") + "\t" + replyTo + "\n\n");
buf.append(rb.getString("java.sitetitle") + "\t" + title + "\n");
buf.append(rb.getString("java.siteid") + "\t" + id + "\n");
buf.append(rb.getString("java.siteinstr") + "\n" + additional
+ "\n\n");
if (!isFutureTerm) {
if (sendEmailToRequestee == null) {
buf.append(rb.getString("java.authoriz") + " " + requestId
+ " " + rb.getString("java.asreq"));
} else {
buf.append(rb.getString("java.thesiteemail") + " "
+ sendEmailToRequestee + " " + rb.getString("java.asreq"));
}
}
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo,
replyTo, null);
// To the Instructor
from = requestEmail;
to = cUser.getEmail();
headerTo = to;
replyTo = to;
buf.setLength(0);
buf.append(rb.getString("java.isbeing") + " ");
buf.append(rb.getString("java.meantime") + "\n\n");
buf.append(rb.getString("java.copy") + "\n\n");
buf.append(content);
buf.append("\n" + rb.getString("java.wish") + " " + requestEmail);
content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo,
replyTo, null);
state.setAttribute(REQUEST_SENT, new Boolean(true));
} // if
} // sendSiteRequest
private void addRequestedSectionIntoNotification(SessionState state, List requestFields, StringBuilder buf) {
// what are the required fields shown in the UI
List requiredFields = state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null ?(List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS):new Vector();
for (int i = 0; i < requiredFields.size(); i++) {
List requiredFieldList = (List) requestFields
.get(i);
for (int j = 0; j < requiredFieldList.size(); j++) {
SectionField requiredField = (SectionField) requiredFieldList
.get(j);
buf.append(requiredField.getLabelKey() + "\t"
+ requiredField.getValue() + "\n");
}
}
}
private void addRequestedCMSectionIntoNotification(SessionState state, List cmRequestedSections, StringBuilder buf) {
// what are the required fields shown in the UI
for (int i = 0; i < cmRequestedSections.size(); i++) {
SectionObject so = (SectionObject) cmRequestedSections.get(i);
buf.append(so.getTitle() + "(" + so.getEid()
+ ")" + so.getCategory() + "\n");
}
}
/**
* Notification sent when a course site is set up automatcally
*
*/
private void sendSiteNotification(SessionState state, List notifySites) {
// get the request email from configuration
String requestEmail = getSetupRequestEmailAddress();
if (requestEmail != null) {
// send emails
Site site = getStateSite(state);
String id = site.getId();
String title = site.getTitle();
Time time = TimeService.newTime();
String local_time = time.toStringLocalTime();
String local_date = time.toStringLocalDate();
String term_name = "";
if (state.getAttribute(STATE_TERM_SELECTED) != null) {
term_name = ((AcademicSession) state
.getAttribute(STATE_TERM_SELECTED)).getEid();
}
String message_subject = rb.getString("java.official") + " "
+ UserDirectoryService.getCurrentUser().getDisplayName()
+ " " + rb.getString("java.for") + " " + term_name;
String from = NULL_STRING;
String to = NULL_STRING;
String headerTo = NULL_STRING;
String replyTo = NULL_STRING;
String sender = UserDirectoryService.getCurrentUser()
.getDisplayName();
String userId = StringUtil.trimToZero(SessionManager
.getCurrentSessionUserId());
try {
userId = UserDirectoryService.getUserEid(userId);
} catch (UserNotDefinedException e) {
M_log.warn(this + rb.getString("user.notdefined") + " "
+ userId);
}
// To Support
from = UserDirectoryService.getCurrentUser().getEmail();
to = requestEmail;
headerTo = requestEmail;
replyTo = UserDirectoryService.getCurrentUser().getEmail();
StringBuilder buf = new StringBuilder();
buf.append("\n" + rb.getString("java.fromwork") + " "
+ ServerConfigurationService.getServerName() + " "
+ rb.getString("java.supp") + ":\n\n");
buf.append(rb.getString("java.off") + " '" + title + "' (id " + id
+ "), " + rb.getString("java.wasset") + " ");
buf.append(sender + " (" + userId + ", "
+ rb.getString("java.email2") + " " + replyTo + ") ");
buf.append(rb.getString("java.on") + " " + local_date + " "
+ rb.getString("java.at") + " " + local_time + " ");
buf.append(rb.getString("java.for") + " " + term_name + ", ");
int nbr_sections = notifySites.size();
if (nbr_sections > 1) {
buf.append(rb.getString("java.withrost") + " "
+ Integer.toString(nbr_sections) + " "
+ rb.getString("java.sections") + "\n\n");
} else {
buf.append(" " + rb.getString("java.withrost2") + "\n\n");
}
for (int i = 0; i < nbr_sections; i++) {
String course = (String) notifySites.get(i);
buf.append(rb.getString("java.course2") + " " + course + "\n");
}
String content = buf.toString();
EmailService.send(from, to, message_subject, content, headerTo,
replyTo, null);
} // if
} // sendSiteNotification
/**
* doCancel called when "eventSubmit_doCancel_create" is in the request
* parameters to c
*/
public void doCancel_create(RunData data) {
// Don't put current form data in state, just return to the previous
// template
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
removeAddClassContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} // doCancel_create
/**
* doCancel called when "eventSubmit_doCancel" is in the request parameters
* to c int index = Integer.valueOf(params.getString
* ("template-index")).intValue();
*/
public void doCancel(RunData data) {
// Don't put current form data in state, just return to the previous
// template
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
state.removeAttribute(STATE_MESSAGE);
String currentIndex = (String) state.getAttribute(STATE_TEMPLATE_INDEX);
String backIndex = params.getString("back");
state.setAttribute(STATE_TEMPLATE_INDEX, backIndex);
if (currentIndex.equals("4")) {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
state.removeAttribute(STATE_MESSAGE);
removeEditToolState(state);
} else if (currentIndex.equals("5")) {
// remove related state variables
removeAddParticipantContext(state);
params = data.getParameters();
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("back"));
} else if (currentIndex.equals("13") || currentIndex.equals("14")) {
// clean state attributes
state.removeAttribute(FORM_SITEINFO_TITLE);
state.removeAttribute(FORM_SITEINFO_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SKIN);
state.removeAttribute(FORM_SITEINFO_INCLUDE);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} else if (currentIndex.equals("15")) {
params = data.getParameters();
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("cancelIndex"));
removeEditToolState(state);
}
// htripath: added 'currentIndex.equals("45")' for import from file
// cancel
else if (currentIndex.equals("19") || currentIndex.equals("20")
|| currentIndex.equals("21") || currentIndex.equals("22")
|| currentIndex.equals("45")) {
// from adding participant pages
// remove related state variables
removeAddParticipantContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} else if (currentIndex.equals("3")) {
// from adding class
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} else if (currentIndex.equals("27") || currentIndex.equals("28")) {
// from import
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
// worksite setup
if (getStateSite(state) == null) {
// in creating new site process
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else {
// in editing site process
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
// site info
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
} else if (currentIndex.equals("26")) {
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)
&& getStateSite(state) == null) {
// from creating site
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else {
// from revising site
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
removeEditToolState(state);
} else if (currentIndex.equals("37") || currentIndex.equals("44") || currentIndex.equals("53") || currentIndex.equals("36")) {
// cancel back to edit class view
state.removeAttribute(STATE_TERM_SELECTED);
removeAddClassContext(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "43");
}
} // doCancel
/**
* doMenu_customize is called when "eventSubmit_doBack" is in the request
* parameters Pass parameter to actionForTemplate to request action for
* backward direction
*/
public void doMenu_customize(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "15");
}// doMenu_customize
/**
* doBack_to_list cancels an outstanding site edit, cleans state and returns
* to the site list
*
*/
public void doBack_to_list(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site site = getStateSite(state);
if (site != null) {
Hashtable h = (Hashtable) state
.getAttribute(STATE_PAGESIZE_SITEINFO);
h.put(site.getId(), state.getAttribute(STATE_PAGESIZE));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
}
// restore the page size for Worksite setup tool
if (state.getAttribute(STATE_PAGESIZE_SITESETUP) != null) {
state.setAttribute(STATE_PAGESIZE, state
.getAttribute(STATE_PAGESIZE_SITESETUP));
state.removeAttribute(STATE_PAGESIZE_SITESETUP);
}
cleanState(state);
setupFormNamesAndConstants(state);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} // doBack_to_list
/**
* do called when "eventSubmit_do" is in the request parameters to c
*/
public void doAdd_custom_link(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
if ((params.getString("name")) == null
|| (params.getString("url") == null)) {
Tool tr = ToolManager.getTool("sakai.iframe");
Site site = getStateSite(state);
SitePage page = site.addPage();
page.setTitle(params.getString("name")); // the visible label on
// the tool menu
ToolConfiguration tool = page.addTool();
tool.setTool("sakai.iframe", tr);
tool.setTitle(params.getString("name"));
commitSite(site);
} else {
addAlert(state, rb.getString("java.reqmiss"));
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("template-index"));
}
} // doAdd_custom_link
/**
* doAdd_remove_features is called when Make These Changes is clicked in
* chef_site-addRemoveFeatures
*/
public void doAdd_remove_features(RunData data) {
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
// dispatch
if (option.startsWith("add_")) {
// this could be format of originalToolId plus number of multiplication
String addToolId = option.substring("add_".length(), option.length());
// find the original tool id
String originToolId = findOriginalToolId(state, addToolId);
if (originToolId != null)
{
Tool tool = ToolManager.getTool(originToolId);
if (tool != null)
{
updateSelectedToolList(state, params, false);
insertTool(state, originToolId, tool.getTitle(), tool.getDescription(), Integer.parseInt(params.getString("num_"+ addToolId)));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
}
} else if (option.equalsIgnoreCase("save")) {
getFeatures(params, state, "15");
} else if (option.equalsIgnoreCase("continue")) {
updateSelectedToolList(state, params, false);
// continue
doContinue(data);
} else if (option.equalsIgnoreCase("Back")) {
// back
doBack(data);
} else if (option.equalsIgnoreCase("Cancel")) {
// cancel
doCancel(data);
}
} // doAdd_remove_features
/**
* toolId might be of form original tool id concatenated with number
* find whether there is an counterpart in the the multipleToolIdSet
* @param state
* @param toolId
* @return
*/
private String findOriginalToolId(SessionState state, String toolId) {
// treat home tool differently
if (toolId.equals(HOME_TOOL_ID))
{
return toolId;
}
else
{
Set categories = new HashSet();
categories.add((String) state.getAttribute(STATE_SITE_TYPE));
Set toolRegistrationList = ToolManager.findTools(categories, null);
String originToolId = null;
if (toolRegistrationList != null)
{
for (Iterator i=toolRegistrationList.iterator(); originToolId == null && i.hasNext();)
{
Tool tool = (Tool) i.next();
if (toolId.indexOf(tool.getId()) != -1)
{
originToolId = tool.getId();
}
}
}
return originToolId;
}
}
/**
* Read from tool registration whether multiple registration is allowed for this tool
* @param toolId
* @return
*/
private boolean isMultipleInstancesAllowed(String toolId)
{
Tool tool = ToolManager.getTool(toolId);
if (tool != null)
{
Properties tProperties = tool.getRegisteredConfig();
return (tProperties.containsKey("allowMultipleInstances")
&& tProperties.getProperty("allowMultipleInstances").equalsIgnoreCase(Boolean.TRUE.toString()))?true:false;
}
return false;
}
/**
* doSave_revised_features
*/
public void doSave_revised_features(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
getRevisedFeatures(params, state);
Site site = getStateSite(state);
String id = site.getId();
// now that the site exists, we can set the email alias when an Email
// Archive tool has been selected
String alias = StringUtil.trimToNull((String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
if (alias != null) {
String channelReference = mailArchiveChannelReference(id);
try {
AliasService.setAlias(alias, channelReference);
} catch (IdUsedException ee) {
} catch (IdInvalidException ee) {
addAlert(state, rb.getString("java.alias") + " " + alias + " "
+ rb.getString("java.isinval"));
} catch (PermissionException ee) {
addAlert(state, rb.getString("java.addalias") + " ");
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// clean state variables
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP);
state.setAttribute(STATE_SITE_INSTANCE_ID, id);
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("continue"));
}
// refresh the whole page
scheduleTopRefresh();
} // doSave_revised_features
/**
* doMenu_add_participant
*/
public void doMenu_add_participant(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
} // doMenu_add_participant
/**
* doMenu_siteInfo_addParticipant
*/
public void doMenu_siteInfo_addParticipant(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
}
} // doMenu_siteInfo_addParticipant
/**
* doMenu_siteInfo_cancel_access
*/
public void doMenu_siteInfo_cancel_access(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} // doMenu_siteInfo_cancel_access
/**
* doMenu_siteInfo_import
*/
public void doMenu_siteInfo_import(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "28");
}
} // doMenu_siteInfo_import
/**
* doMenu_siteInfo_editClass
*/
public void doMenu_siteInfo_editClass(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(STATE_TEMPLATE_INDEX, "43");
} // doMenu_siteInfo_editClass
/**
* doMenu_siteInfo_addClass
*/
public void doMenu_siteInfo_addClass(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site site = getStateSite(state);
String termEid = site.getProperties().getProperty(PROP_SITE_TERM_EID);
if (termEid == null)
{
// no term eid stored, need to get term eid from the term title
String termTitle = site.getProperties().getProperty(PROP_SITE_TERM);
List asList = cms.getAcademicSessions();
if (termTitle != null && asList != null)
{
boolean found = false;
for (int i = 0; i<asList.size() && !found; i++)
{
AcademicSession as = (AcademicSession) asList.get(i);
if (as.getTitle().equals(termTitle))
{
termEid = as.getEid();
site.getPropertiesEdit().addProperty(PROP_SITE_TERM_EID, termEid);
try
{
SiteService.save(site);
}
catch (Exception e)
{
M_log.warn(this + e.getMessage() + site.getId());
}
found=true;
}
}
}
}
state.setAttribute(STATE_TERM_SELECTED, cms.getAcademicSession(termEid));
try
{
List sections = prepareCourseAndSectionListing(UserDirectoryService.getCurrentUser().getEid(), cms.getAcademicSession(termEid).getEid(), state);
isFutureTermSelected(state);
if (sections != null && sections.size() > 0)
state.setAttribute(STATE_TERM_COURSE_LIST, sections);
}
catch (Exception e)
{
M_log.warn(e.getMessage() + termEid);
}
state.setAttribute(STATE_TEMPLATE_INDEX, "36");
} // doMenu_siteInfo_addClass
/**
* doMenu_siteInfo_duplicate
*/
public void doMenu_siteInfo_duplicate(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "29");
}
} // doMenu_siteInfo_import
/**
* doMenu_edit_site_info
*
*/
public void doMenu_edit_site_info(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site Site = getStateSite(state);
ResourceProperties siteProperties = Site.getProperties();
state.setAttribute(FORM_SITEINFO_TITLE, Site.getTitle());
String site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (site_type != null && !site_type.equalsIgnoreCase("myworkspace")) {
state.setAttribute(FORM_SITEINFO_INCLUDE, Boolean.valueOf(
Site.isPubView()).toString());
}
state.setAttribute(FORM_SITEINFO_DESCRIPTION, Site.getDescription());
state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION, Site
.getShortDescription());
state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl());
if (Site.getIconUrl() != null) {
state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl());
}
// site contact information
String contactName = siteProperties.getProperty(PROP_SITE_CONTACT_NAME);
String contactEmail = siteProperties
.getProperty(PROP_SITE_CONTACT_EMAIL);
if (contactName == null && contactEmail == null) {
String creatorId = siteProperties
.getProperty(ResourceProperties.PROP_CREATOR);
try {
User u = UserDirectoryService.getUser(creatorId);
String email = u.getEmail();
if (email != null) {
contactEmail = u.getEmail();
}
contactName = u.getDisplayName();
} catch (UserNotDefinedException e) {
}
}
if (contactName != null) {
state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName);
}
if (contactEmail != null) {
state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, contactEmail);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "13");
}
} // doMenu_edit_site_info
/**
* doMenu_edit_site_tools
*
*/
public void doMenu_edit_site_tools(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
// get the tools
siteToolsIntoState(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "4");
}
} // doMenu_edit_site_tools
/**
* doMenu_edit_site_access
*
*/
public void doMenu_edit_site_access(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} // doMenu_edit_site_access
/**
* Back to worksite setup's list view
*
*/
public void doBack_to_site_list(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_SITE_TYPE);
state.removeAttribute(STATE_SITE_INSTANCE_ID);
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} // doBack_to_site_list
/**
* doSave_site_info
*
*/
public void doSave_siteInfo(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site Site = getStateSite(state);
ResourcePropertiesEdit siteProperties = Site.getPropertiesEdit();
String site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (siteTitleEditable(state, site_type))
{
Site.setTitle((String) state.getAttribute(FORM_SITEINFO_TITLE));
}
Site.setDescription((String) state
.getAttribute(FORM_SITEINFO_DESCRIPTION));
Site.setShortDescription((String) state
.getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION));
if (site_type != null) {
if (site_type.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
// set icon url for course
String skin = (String) state.getAttribute(FORM_SITEINFO_SKIN);
setAppearance(state, Site, skin);
} else {
// set icon url for others
String iconUrl = (String) state
.getAttribute(FORM_SITEINFO_ICON_URL);
Site.setIconUrl(iconUrl);
}
}
// site contact information
String contactName = (String) state
.getAttribute(FORM_SITEINFO_CONTACT_NAME);
if (contactName != null) {
siteProperties.addProperty(PROP_SITE_CONTACT_NAME, contactName);
}
String contactEmail = (String) state
.getAttribute(FORM_SITEINFO_CONTACT_EMAIL);
if (contactEmail != null) {
siteProperties.addProperty(PROP_SITE_CONTACT_EMAIL, contactEmail);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
try {
SiteService.save(Site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
// clean state attributes
state.removeAttribute(FORM_SITEINFO_TITLE);
state.removeAttribute(FORM_SITEINFO_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION);
state.removeAttribute(FORM_SITEINFO_SKIN);
state.removeAttribute(FORM_SITEINFO_INCLUDE);
state.removeAttribute(FORM_SITEINFO_CONTACT_NAME);
state.removeAttribute(FORM_SITEINFO_CONTACT_EMAIL);
// back to site info view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
// refresh the whole page
scheduleTopRefresh();
}
} // doSave_siteInfo
/**
* Check to see whether the site's title is editable or not
* @param state
* @param site_type
* @return
*/
private boolean siteTitleEditable(SessionState state, String site_type) {
return site_type != null
&& (!site_type.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))
|| (state.getAttribute(TITLE_EDITABLE_SITE_TYPE) != null
&& ((List) state.getAttribute(TITLE_EDITABLE_SITE_TYPE)).contains(site_type)));
}
/**
* init
*
*/
private void init(VelocityPortlet portlet, RunData data, SessionState state) {
state.setAttribute(STATE_ACTION, "SiteAction");
setupFormNamesAndConstants(state);
if (state.getAttribute(STATE_PAGESIZE_SITEINFO) == null) {
state.setAttribute(STATE_PAGESIZE_SITEINFO, new Hashtable());
}
if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITESETUP)) {
state.setAttribute(STATE_TEMPLATE_INDEX, "0");
} else if (((String) state.getAttribute(STATE_SITE_MODE))
.equalsIgnoreCase(SITE_MODE_SITEINFO)) {
String siteId = ToolManager.getCurrentPlacement().getContext();
getReviseSite(state, siteId);
Hashtable h = (Hashtable) state
.getAttribute(STATE_PAGESIZE_SITEINFO);
if (!h.containsKey(siteId)) {
// update
h.put(siteId, new Integer(200));
state.setAttribute(STATE_PAGESIZE_SITEINFO, h);
state.setAttribute(STATE_PAGESIZE, new Integer(200));
}
}
if (state.getAttribute(STATE_SITE_TYPES) == null) {
PortletConfig config = portlet.getPortletConfig();
// all site types (SITE_DEFAULT_LIST overrides tool config)
String t = StringUtil.trimToNull(SITE_DEFAULT_LIST);
if ( t == null )
t = StringUtil.trimToNull(config.getInitParameter("siteTypes"));
if (t != null) {
List types = new ArrayList(Arrays.asList(t.split(",")));
if (cms == null)
{
// if there is no CourseManagementService, disable the process of creating course site
String courseType = ServerConfigurationService.getString("courseSiteType", (String) state.getAttribute(STATE_COURSE_SITE_TYPE));
types.remove(courseType);
}
state.setAttribute(STATE_SITE_TYPES, types);
} else {
state.setAttribute(STATE_SITE_TYPES, new Vector());
}
}
} // init
public void doNavigate_to_site(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String siteId = StringUtil.trimToNull(data.getParameters().getString(
"option"));
if (siteId != null) {
getReviseSite(state, siteId);
} else {
doBack_to_list(data);
}
} // doNavigate_to_site
/**
* Get site information for revise screen
*/
private void getReviseSite(SessionState state, String siteId) {
if (state.getAttribute(STATE_SELECTED_USER_LIST) == null) {
state.setAttribute(STATE_SELECTED_USER_LIST, new Vector());
}
List sites = (List) state.getAttribute(STATE_SITES);
try {
Site site = SiteService.getSite(siteId);
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
if (sites != null) {
int pos = -1;
for (int index = 0; index < sites.size() && pos == -1; index++) {
if (((Site) sites.get(index)).getId().equals(siteId)) {
pos = index;
}
}
// has any previous site in the list?
if (pos > 0) {
state.setAttribute(STATE_PREV_SITE, sites.get(pos - 1));
} else {
state.removeAttribute(STATE_PREV_SITE);
}
// has any next site in the list?
if (pos < sites.size() - 1) {
state.setAttribute(STATE_NEXT_SITE, sites.get(pos + 1));
} else {
state.removeAttribute(STATE_NEXT_SITE);
}
}
String type = site.getType();
if (type == null) {
if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) {
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
}
state.setAttribute(STATE_SITE_TYPE, type);
} catch (IdUnusedException e) {
M_log.warn(this + e.toString());
}
// one site has been selected
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
} // getReviseSite
/**
* doUpdate_participant
*
*/
public void doUpdate_participant(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
Site s = getStateSite(state);
String realmId = SiteService.siteReference(s.getId());
if (AuthzGroupService.allowUpdate(realmId)
|| SiteService.allowUpdateSiteMembership(s.getId())) {
try {
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId);
// does the site has maintain type user(s) before updating
// participants?
String maintainRoleString = realmEdit.getMaintainRole();
boolean hadMaintainUser = !realmEdit.getUsersHasRole(
maintainRoleString).isEmpty();
// update participant roles
List participants = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST));
// remove all roles and then add back those that were checked
for (int i = 0; i < participants.size(); i++) {
String id = null;
// added participant
Participant participant = (Participant) participants.get(i);
id = participant.getUniqname();
if (id != null) {
// get the newly assigned role
String inputRoleField = "role" + id;
String roleId = params.getString(inputRoleField);
// only change roles when they are different than before
if (roleId != null) {
// get the grant active status
boolean activeGrant = true;
String activeGrantField = "activeGrant" + id;
if (params.getString(activeGrantField) != null) {
activeGrant = params
.getString(activeGrantField)
.equalsIgnoreCase("true") ? true
: false;
}
boolean fromProvider = !participant.isRemoveable();
if (fromProvider && !roleId.equals(participant.getRole())) {
fromProvider = false;
}
realmEdit.addMember(id, roleId, activeGrant,
fromProvider);
}
}
}
// remove selected users
if (params.getStrings("selectedUser") != null) {
List removals = new ArrayList(Arrays.asList(params
.getStrings("selectedUser")));
state.setAttribute(STATE_SELECTED_USER_LIST, removals);
for (int i = 0; i < removals.size(); i++) {
String rId = (String) removals.get(i);
try {
User user = UserDirectoryService.getUser(rId);
realmEdit.removeMember(user.getId());
} catch (UserNotDefinedException e) {
M_log.warn(this + " IdUnusedException " + rId
+ ". ");
}
}
}
if (hadMaintainUser
&& realmEdit.getUsersHasRole(maintainRoleString)
.isEmpty()) {
// if after update, the "had maintain type user" status
// changed, show alert message and don't save the update
addAlert(state, rb
.getString("sitegen.siteinfolist.nomaintainuser")
+ maintainRoleString + ".");
} else {
// post event about the participant update
EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_SITE_MEMBERSHIP, realmEdit.getId(),false));
AuthzGroupService.save(realmEdit);
// then update all related group realms for the role
doUpdate_related_group_participants(s, realmId);
}
} catch (GroupNotDefinedException e) {
addAlert(state, rb.getString("java.problem2"));
M_log.warn(this + " IdUnusedException " + s.getTitle() + "("
+ realmId + "). ");
} catch (AuthzPermissionException e) {
addAlert(state, rb.getString("java.changeroles"));
M_log.warn(this + " PermissionException " + s.getTitle() + "("
+ realmId + "). ");
}
}
} // doUpdate_participant
/**
* update realted group realm setting according to parent site realm changes
* @param s
* @param realmId
*/
private void doUpdate_related_group_participants(Site s, String realmId) {
Collection groups = s.getGroups();
if (groups != null)
{
for (Iterator iGroups = groups.iterator(); iGroups.hasNext();)
{
Group g = (Group) iGroups.next();
try
{
Set gMembers = g.getMembers();
for (Iterator iGMembers = gMembers.iterator(); iGMembers.hasNext();)
{
Member gMember = (Member) iGMembers.next();
String gMemberId = gMember.getUserId();
Member siteMember = s.getMember(gMemberId);
if ( siteMember == null)
{
// user has been removed from the site
g.removeMember(gMemberId);
}
else
{
// if there is a difference between the role setting, remove the entry from group and add it back with correct role, all are marked "not provided"
if (!g.getUserRole(gMemberId).equals(siteMember.getRole()))
{
g.removeMember(gMemberId);
g.addMember(gMemberId, siteMember.getRole().getId(), siteMember.isActive(), false);
}
}
}
// commit
// post event about the participant update
EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_GROUP_MEMBERSHIP, g.getId(),false));
SiteService.save(s);
}
catch (Exception ee)
{
M_log.warn(this + ee.getMessage() + g.getId());
}
}
}
}
/**
* doUpdate_site_access
*
*/
public void doUpdate_site_access(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site sEdit = getStateSite(state);
ParameterParser params = data.getParameters();
String publishUnpublish = params.getString("publishunpublish");
String include = params.getString("include");
String joinable = params.getString("joinable");
if (sEdit != null) {
// editing existing site
// publish site or not
if (publishUnpublish != null
&& publishUnpublish.equalsIgnoreCase("publish")) {
sEdit.setPublished(true);
} else {
sEdit.setPublished(false);
}
// site public choice
if (include != null) {
// if there is pubview input, use it
sEdit.setPubView(include.equalsIgnoreCase("true") ? true
: false);
} else if (state.getAttribute(STATE_SITE_TYPE) != null) {
String type = (String) state.getAttribute(STATE_SITE_TYPE);
List publicSiteTypes = (List) state
.getAttribute(STATE_PUBLIC_SITE_TYPES);
List privateSiteTypes = (List) state
.getAttribute(STATE_PRIVATE_SITE_TYPES);
if (publicSiteTypes.contains(type)) {
// sites are always public
sEdit.setPubView(true);
} else if (privateSiteTypes.contains(type)) {
// site are always private
sEdit.setPubView(false);
}
} else {
sEdit.setPubView(false);
}
// publish site or not
if (joinable != null && joinable.equalsIgnoreCase("true")) {
state.setAttribute(STATE_JOINABLE, Boolean.TRUE);
sEdit.setJoinable(true);
String joinerRole = StringUtil.trimToNull(params
.getString("joinerRole"));
if (joinerRole != null) {
state.setAttribute(STATE_JOINERROLE, joinerRole);
sEdit.setJoinerRole(joinerRole);
} else {
state.setAttribute(STATE_JOINERROLE, "");
addAlert(state, rb.getString("java.joinsite") + " ");
}
} else {
state.setAttribute(STATE_JOINABLE, Boolean.FALSE);
state.removeAttribute(STATE_JOINERROLE);
sEdit.setJoinable(false);
sEdit.setJoinerRole(null);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
commitSite(sEdit);
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
// TODO: hard coding this frame id is fragile, portal dependent,
// and needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
state.removeAttribute(STATE_JOINABLE);
state.removeAttribute(STATE_JOINERROLE);
}
} else {
// adding new site
if (state.getAttribute(STATE_SITE_INFO) != null) {
SiteInfo siteInfo = (SiteInfo) state
.getAttribute(STATE_SITE_INFO);
if (publishUnpublish != null
&& publishUnpublish.equalsIgnoreCase("publish")) {
siteInfo.published = true;
} else {
siteInfo.published = false;
}
// site public choice
if (include != null) {
siteInfo.include = include.equalsIgnoreCase("true") ? true
: false;
} else if (StringUtil.trimToNull(siteInfo.site_type) != null) {
String type = StringUtil.trimToNull(siteInfo.site_type);
List publicSiteTypes = (List) state
.getAttribute(STATE_PUBLIC_SITE_TYPES);
List privateSiteTypes = (List) state
.getAttribute(STATE_PRIVATE_SITE_TYPES);
if (publicSiteTypes.contains(type)) {
// sites are always public
siteInfo.include = true;
} else if (privateSiteTypes.contains(type)) {
// site are always private
siteInfo.include = false;
}
} else {
siteInfo.include = false;
}
// joinable site or not
if (joinable != null && joinable.equalsIgnoreCase("true")) {
siteInfo.joinable = true;
String joinerRole = StringUtil.trimToNull(params
.getString("joinerRole"));
if (joinerRole != null) {
siteInfo.joinerRole = joinerRole;
} else {
addAlert(state, rb.getString("java.joinsite") + " ");
}
} else {
siteInfo.joinable = false;
siteInfo.joinerRole = null;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "10");
updateCurrentStep(state, true);
}
}
} // doUpdate_site_access
/**
* /* Actions for vm templates under the "chef_site" root. This method is
* called by doContinue. Each template has a hidden field with the value of
* template-index that becomes the value of index for the switch statement
* here. Some cases not implemented.
*/
private void actionForTemplate(String direction, int index,
ParameterParser params, SessionState state) {
// Continue - make any permanent changes, Back - keep any data entered
// on the form
boolean forward = direction.equals("continue") ? true : false;
SiteInfo siteInfo = new SiteInfo();
switch (index) {
case 0:
/*
* actionForTemplate chef_site-list.vm
*
*/
break;
case 1:
/*
* actionForTemplate chef_site-type.vm
*
*/
break;
case 2:
/*
* actionForTemplate chef_site-newSiteInformation.vm
*
*/
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
// defaults to be true
siteInfo.include = true;
state.setAttribute(STATE_SITE_INFO, siteInfo);
updateSiteInfo(params, state);
// alerts after clicking Continue but not Back
if (forward) {
if (StringUtil.trimToNull(siteInfo.title) == null) {
addAlert(state, rb.getString("java.reqfields"));
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
return;
}
}
updateSiteAttributes(state);
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, forward);
}
break;
case 3:
/*
* actionForTemplate chef_site-newSiteFeatures.vm
*
*/
if (forward) {
getFeatures(params, state, "18");
}
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, forward);
}
break;
case 4:
/*
* actionForTemplate chef_site-addRemoveFeature.vm
*
*/
break;
case 5:
/*
* actionForTemplate chef_site-addParticipant.vm
*
*/
if (forward) {
checkAddParticipant(params, state);
} else {
// remove related state variables
removeAddParticipantContext(state);
}
break;
case 8:
/*
* actionForTemplate chef_site-siteDeleteConfirm.vm
*
*/
break;
case 10:
/*
* actionForTemplate chef_site-newSiteConfirm.vm
*
*/
if (!forward) {
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, false);
}
}
break;
case 12:
/*
* actionForTemplate chef_site_siteInfo-list.vm
*
*/
break;
case 13:
/*
* actionForTemplate chef_site_siteInfo-editInfo.vm
*
*/
if (forward) {
Site Site = getStateSite(state);
if (siteTitleEditable(state, Site.getType()))
{
// site titel is editable and could not be null
String title = StringUtil.trimToNull(params
.getString("title"));
state.setAttribute(FORM_SITEINFO_TITLE, title);
if (title == null) {
addAlert(state, rb.getString("java.specify") + " ");
}
}
String description = StringUtil.trimToNull(params
.getString("description"));
state.setAttribute(FORM_SITEINFO_DESCRIPTION, description);
String short_description = StringUtil.trimToNull(params
.getString("short_description"));
state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION,
short_description);
String skin = params.getString("skin");
if (skin != null) {
// if there is a skin input for course site
skin = StringUtil.trimToNull(skin);
state.setAttribute(FORM_SITEINFO_SKIN, skin);
} else {
// if ther is a icon input for non-course site
String icon = StringUtil.trimToNull(params
.getString("icon"));
if (icon != null) {
if (icon.endsWith(PROTOCOL_STRING)) {
addAlert(state, rb.getString("alert.protocol"));
}
state.setAttribute(FORM_SITEINFO_ICON_URL, icon);
} else {
state.removeAttribute(FORM_SITEINFO_ICON_URL);
}
}
// site contact information
String contactName = StringUtil.trimToZero(params
.getString("siteContactName"));
state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName);
String email = StringUtil.trimToZero(params
.getString("siteContactEmail"));
String[] parts = email.split("@");
if (email.length() > 0
&& (email.indexOf("@") == -1 || parts.length != 2
|| parts[0].length() == 0 || !Validator
.checkEmailLocal(parts[0]))) {
// invalid email
addAlert(state, email + " " + rb.getString("java.invalid")
+ rb.getString("java.theemail"));
}
state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, email);
if (state.getAttribute(STATE_MESSAGE) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "14");
}
}
break;
case 14:
/*
* actionForTemplate chef_site_siteInfo-editInfoConfirm.vm
*
*/
break;
case 15:
/*
* actionForTemplate chef_site_siteInfo-addRemoveFeatureConfirm.vm
*
*/
break;
case 18:
/*
* actionForTemplate chef_siteInfo-editAccess.vm
*
*/
if (!forward) {
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, false);
}
}
case 19:
/*
* actionForTemplate chef_site-addParticipant-sameRole.vm
*
*/
String roleId = StringUtil.trimToNull(params
.getString("selectRole"));
if (roleId == null && forward) {
addAlert(state, rb.getString("java.pleasesel") + " ");
} else {
state.setAttribute("form_selectedRole", params
.getString("selectRole"));
}
break;
case 20:
/*
* actionForTemplate chef_site-addParticipant-differentRole.vm
*
*/
if (forward) {
getSelectedRoles(state, params, STATE_ADD_PARTICIPANTS);
}
break;
case 21:
/*
* actionForTemplate chef_site-addParticipant-notification.vm '
*/
if (params.getString("notify") == null) {
if (forward)
addAlert(state, rb.getString("java.pleasechoice") + " ");
} else {
state.setAttribute("form_selectedNotify", new Boolean(params
.getString("notify")));
}
break;
case 22:
/*
* actionForTemplate chef_site-addParticipant-confirm.vm
*
*/
break;
case 24:
/*
* actionForTemplate
* chef_site-siteInfo-editAccess-globalAccess-confirm.vm
*
*/
break;
case 26:
/*
* actionForTemplate chef_site-modifyENW.vm
*
*/
updateSelectedToolList(state, params, forward);
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, forward);
}
break;
case 27:
/*
* actionForTemplate chef_site-importSites.vm
*
*/
if (forward) {
Site existingSite = getStateSite(state);
if (existingSite != null) {
// revising a existing site's tool
if (select_import_tools(params, state)) {
Hashtable importTools = (Hashtable) state
.getAttribute(STATE_IMPORT_SITE_TOOL);
List selectedTools = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
importToolIntoSite(selectedTools, importTools,
existingSite);
existingSite = getStateSite(state); // refresh site for
// WC and News
if (state.getAttribute(STATE_MESSAGE) == null) {
commitSite(existingSite);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
}
} else {
// show alert and remain in current page
addAlert(state, rb.getString("java.toimporttool"));
}
} else {
// new site
select_import_tools(params, state);
}
} else {
// read form input about import tools
select_import_tools(params, state);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
updateCurrentStep(state, forward);
}
break;
case 28:
/*
* actionForTemplate chef_siteinfo-import.vm
*
*/
if (forward) {
if (params.getStrings("importSites") == null) {
addAlert(state, rb.getString("java.toimport") + " ");
state.removeAttribute(STATE_IMPORT_SITES);
} else {
List importSites = new ArrayList(Arrays.asList(params
.getStrings("importSites")));
Hashtable sites = new Hashtable();
for (index = 0; index < importSites.size(); index++) {
try {
Site s = SiteService.getSite((String) importSites
.get(index));
sites.put(s, new Vector());
} catch (IdUnusedException e) {
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
}
break;
case 29:
/*
* actionForTemplate chef_siteinfo-duplicate.vm
*
*/
if (forward) {
if (state.getAttribute(SITE_DUPLICATED) == null) {
if (StringUtil.trimToNull(params.getString("title")) == null) {
addAlert(state, rb.getString("java.dupli") + " ");
} else {
String title = params.getString("title");
state.setAttribute(SITE_DUPLICATED_NAME, title);
try {
String oSiteId = (String) state
.getAttribute(STATE_SITE_INSTANCE_ID);
String nSiteId = IdManager.createUuid();
Site site = SiteService.addSite(nSiteId,
getStateSite(state));
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
try {
site = SiteService.getSite(nSiteId);
// set title
site.setTitle(title);
// import tool content
List pageList = site.getPages();
if (!((pageList == null) || (pageList.size() == 0))) {
for (ListIterator i = pageList
.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
List pageToolList = page.getTools();
String toolId = ((ToolConfiguration) pageToolList
.get(0)).getTool().getId();
if (toolId
.equalsIgnoreCase("sakai.resources")) {
// handle
// resource
// tool
// specially
transferCopyEntities(
toolId,
ContentHostingService
.getSiteCollection(oSiteId),
ContentHostingService
.getSiteCollection(nSiteId));
} else {
// other
// tools
transferCopyEntities(toolId,
oSiteId, nSiteId);
}
}
}
} catch (Exception e1) {
// if goes here, IdService
// or SiteService has done
// something wrong.
M_log.warn(this + "Exception" + e1 + ":"
+ nSiteId + "when duplicating site");
}
if (site.getType().equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) {
// for course site, need to
// read in the input for
// term information
String termId = StringUtil.trimToNull(params
.getString("selectTerm"));
if (termId != null) {
AcademicSession term = cms.getAcademicSession(termId);
if (term != null) {
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.addProperty(PROP_SITE_TERM, term.getTitle());
rp.addProperty(PROP_SITE_TERM_EID, term.getEid());
} else {
M_log.warn("termId=" + termId + " not found");
}
}
}
try {
SiteService.save(site);
if (site.getType().equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE)))
{
// also remove the provider id attribute if any
String realm = SiteService.siteReference(site.getId());
try
{
AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realm);
realmEdit.setProviderGroupId(null);
AuthzGroupService.save(realmEdit);
} catch (GroupNotDefinedException e) {
M_log.warn(this + " IdUnusedException, not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.realm"));
} catch (Exception e) {
addAlert(state, this + rb.getString("java.problem"));
}
}
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
// TODO: hard coding this frame id
// is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
state.setAttribute(SITE_DUPLICATED, Boolean.TRUE);
} catch (IdInvalidException e) {
addAlert(state, rb.getString("java.siteinval"));
} catch (IdUsedException e) {
addAlert(state, rb.getString("java.sitebeenused")
+ " ");
} catch (PermissionException e) {
addAlert(state, rb.getString("java.allowcreate")
+ " ");
}
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// site duplication confirmed
state.removeAttribute(SITE_DUPLICATED);
state.removeAttribute(SITE_DUPLICATED_NAME);
// return to the list view
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
}
break;
case 33:
break;
case 36:
/*
* actionForTemplate chef_site-newSiteCourse.vm
*/
if (forward) {
List providerChosenList = new Vector();
if (params.getStrings("providerCourseAdd") == null) {
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (params.getString("manualAdds") == null) {
addAlert(state, rb.getString("java.manual") + " ");
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// The list of courses selected from provider listing
if (params.getStrings("providerCourseAdd") != null) {
providerChosenList = new ArrayList(Arrays.asList(params
.getStrings("providerCourseAdd"))); // list of
// course
// ids
String userId = (String) state
.getAttribute(STATE_INSTRUCTOR_SELECTED);
String currentUserId = (String) state
.getAttribute(STATE_CM_CURRENT_USERID);
if (userId == null
|| (userId != null && userId
.equals(currentUserId))) {
state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN,
providerChosenList);
state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS);
state.removeAttribute(FORM_ADDITIONAL);
state.removeAttribute(STATE_CM_AUTHORIZER_LIST);
} else {
// STATE_CM_AUTHORIZER_SECTIONS are SectionObject,
// so need to prepare it
// also in this page, u can pick either section from
// current user OR
// sections from another users but not both. -
// daisy's note 1 for now
// till we are ready to add more complexity
List sectionObjectList = prepareSectionObject(
providerChosenList, userId);
state.setAttribute(STATE_CM_AUTHORIZER_SECTIONS,
sectionObjectList);
state
.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
// set special instruction & we will keep
// STATE_CM_AUTHORIZER_LIST
String additional = StringUtil.trimToZero(params
.getString("additional"));
state.setAttribute(FORM_ADDITIONAL, additional);
}
}
collectNewSiteInfo(siteInfo, state, params,
providerChosenList);
}
// next step
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2));
}
break;
case 38:
break;
case 39:
break;
case 42:
/*
* actionForTemplate chef_site-gradtoolsConfirm.vm
*
*/
break;
case 43:
/*
* actionForTemplate chef_site-editClass.vm
*
*/
if (forward) {
if (params.getStrings("providerClassDeletes") == null
&& params.getStrings("manualClassDeletes") == null
&& params.getStrings("cmRequestedClassDeletes") == null
&& !direction.equals("back")) {
addAlert(state, rb.getString("java.classes"));
}
if (params.getStrings("providerClassDeletes") != null) {
// build the deletions list
List providerCourseList = (List) state
.getAttribute(SITE_PROVIDER_COURSE_LIST);
List providerCourseDeleteList = new ArrayList(Arrays
.asList(params.getStrings("providerClassDeletes")));
for (ListIterator i = providerCourseDeleteList
.listIterator(); i.hasNext();) {
providerCourseList.remove((String) i.next());
}
state.setAttribute(SITE_PROVIDER_COURSE_LIST,
providerCourseList);
}
if (params.getStrings("manualClassDeletes") != null) {
// build the deletions list
List manualCourseList = (List) state
.getAttribute(SITE_MANUAL_COURSE_LIST);
List manualCourseDeleteList = new ArrayList(Arrays
.asList(params.getStrings("manualClassDeletes")));
for (ListIterator i = manualCourseDeleteList.listIterator(); i
.hasNext();) {
manualCourseList.remove((String) i.next());
}
state.setAttribute(SITE_MANUAL_COURSE_LIST,
manualCourseList);
}
if (params.getStrings("cmRequestedClassDeletes") != null) {
// build the deletions list
List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS);
List<String> cmRequestedCourseDeleteList = new ArrayList(Arrays.asList(params.getStrings("cmRequestedClassDeletes")));
for (ListIterator i = cmRequestedCourseDeleteList.listIterator(); i
.hasNext();) {
String sectionId = (String) i.next();
try
{
SectionObject so = new SectionObject(cms.getSection(sectionId));
SectionObject soFound = null;
for (Iterator j = cmRequestedCourseList.iterator(); soFound == null && j.hasNext();)
{
SectionObject k = (SectionObject) j.next();
if (k.eid.equals(sectionId))
{
soFound = k;
}
}
if (soFound != null) cmRequestedCourseList.remove(soFound);
}
catch (Exception e)
{
M_log.warn(e.getMessage() + sectionId);
}
}
state.setAttribute(STATE_CM_REQUESTED_SECTIONS, cmRequestedCourseList);
}
updateCourseClasses(state, new Vector(), new Vector());
}
break;
case 44:
if (forward) {
AcademicSession a = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
Site site = getStateSite(state);
ResourcePropertiesEdit pEdit = site.getPropertiesEdit();
// update the course site property and realm based on the selection
updateCourseSiteSections(state, site.getId(), pEdit, a);
try
{
SiteService.save(site);
}
catch (Exception e)
{
M_log.warn(e.getMessage() + site.getId());
}
removeAddClassContext(state);
}
break;
case 49:
if (!forward) {
state.removeAttribute(SORTED_BY);
state.removeAttribute(SORTED_ASC);
}
break;
}
}// actionFor Template
/**
* update current step index within the site creation wizard
*
* @param state
* The SessionState object
* @param forward
* Moving forward or backward?
*/
private void updateCurrentStep(SessionState state, boolean forward) {
if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) {
int currentStep = ((Integer) state
.getAttribute(SITE_CREATE_CURRENT_STEP)).intValue();
if (forward) {
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(
currentStep + 1));
} else {
state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(
currentStep - 1));
}
}
}
/**
* remove related state variable for adding class
*
* @param state
* SessionState object
*/
private void removeAddClassContext(SessionState state) {
// remove related state variables
state.removeAttribute(STATE_ADD_CLASS_MANUAL);
state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
state.removeAttribute(STATE_AUTO_ADD);
state.removeAttribute(SITE_CREATE_TOTAL_STEPS);
state.removeAttribute(SITE_CREATE_CURRENT_STEP);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_CM_REQUESTED_SECTIONS);
state.removeAttribute(STATE_CM_SELECTED_SECTIONS);
sitePropertiesIntoState(state);
} // removeAddClassContext
private void updateCourseClasses(SessionState state, List notifyClasses,
List requestClasses) {
List providerCourseSectionList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
List manualCourseSectionList = (List) state.getAttribute(SITE_MANUAL_COURSE_LIST);
List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS);
Site site = getStateSite(state);
String id = site.getId();
String realmId = SiteService.siteReference(id);
if ((providerCourseSectionList == null)
|| (providerCourseSectionList.size() == 0)) {
// no section access so remove Provider Id
try {
AuthzGroup realmEdit1 = AuthzGroupService
.getAuthzGroup(realmId);
realmEdit1.setProviderGroupId(NULL_STRING);
AuthzGroupService.save(realmEdit1);
} catch (GroupNotDefinedException e) {
M_log.warn(this + " IdUnusedException, " + site.getTitle()
+ "(" + realmId
+ ") not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.cannotedit"));
return;
} catch (AuthzPermissionException e) {
M_log
.warn(this
+ " PermissionException, user does not have permission to edit AuthzGroup object "
+ site.getTitle() + "(" + realmId + "). ");
addAlert(state, rb.getString("java.notaccess"));
return;
}
}
if ((providerCourseSectionList != null)
&& (providerCourseSectionList.size() != 0)) {
// section access so rewrite Provider Id, don't need the current realm provider String
String externalRealm = buildExternalRealm(id, state,
providerCourseSectionList, null);
try {
AuthzGroup realmEdit2 = AuthzGroupService
.getAuthzGroup(realmId);
realmEdit2.setProviderGroupId(externalRealm);
AuthzGroupService.save(realmEdit2);
} catch (GroupNotDefinedException e) {
M_log.warn(this + " IdUnusedException, " + site.getTitle()
+ "(" + realmId
+ ") not found, or not an AuthzGroup object");
addAlert(state, rb.getString("java.cannotclasses"));
return;
} catch (AuthzPermissionException e) {
M_log
.warn(this
+ " PermissionException, user does not have permission to edit AuthzGroup object "
+ site.getTitle() + "(" + realmId + "). ");
addAlert(state, rb.getString("java.notaccess"));
return;
}
}
// the manual request course into properties
setSiteSectionProperty(manualCourseSectionList, site, PROP_SITE_REQUEST_COURSE);
// the cm request course into properties
setSiteSectionProperty(cmRequestedCourseList, site, STATE_CM_REQUESTED_SECTIONS);
// clean the related site groups
// if the group realm provider id is not listed for the site, remove the related group
for (Iterator iGroups = site.getGroups().iterator(); iGroups.hasNext();)
{
Group group = (Group) iGroups.next();
try
{
AuthzGroup gRealm = AuthzGroupService.getAuthzGroup(group.getReference());
String gProviderId = StringUtil.trimToNull(gRealm.getProviderGroupId());
if (gProviderId != null)
{
if ((manualCourseSectionList== null && cmRequestedCourseList == null)
|| (manualCourseSectionList != null && !manualCourseSectionList.contains(gProviderId) && cmRequestedCourseList == null)
|| (manualCourseSectionList == null && cmRequestedCourseList != null && !cmRequestedCourseList.contains(gProviderId))
|| (manualCourseSectionList != null && !manualCourseSectionList.contains(gProviderId) && cmRequestedCourseList != null && !cmRequestedCourseList.contains(gProviderId)))
{
AuthzGroupService.removeAuthzGroup(group.getReference());
}
}
}
catch (Exception e)
{
M_log.warn(this + ".updateCourseClasses: cannot remove authzgroup : " + group.getReference());
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
commitSite(site);
} else {
}
if (requestClasses != null && requestClasses.size() > 0
&& state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) {
try {
// send out class request notifications
sendSiteRequest(state, "change",
((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue(),
(List<SectionObject>) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS),
"manual");
} catch (Exception e) {
M_log.warn(this + e.toString());
}
}
if (notifyClasses != null && notifyClasses.size() > 0) {
try {
// send out class access confirmation notifications
sendSiteNotification(state, notifyClasses);
} catch (Exception e) {
M_log.warn(this + e.toString());
}
}
} // updateCourseClasses
private void setSiteSectionProperty(List courseSectionList, Site site, String propertyName) {
if ((courseSectionList != null) && (courseSectionList.size() != 0)) {
// store the requested sections in one site property
String sections = "";
for (int j = 0; j < courseSectionList.size();) {
sections = sections
+ (String) courseSectionList.get(j);
j++;
if (j < courseSectionList.size()) {
sections = sections + "+";
}
}
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.addProperty(propertyName, sections);
} else {
ResourcePropertiesEdit rp = site.getPropertiesEdit();
rp.removeProperty(propertyName);
}
}
/**
* Sets selected roles for multiple users
*
* @param params
* The ParameterParser object
* @param listName
* The state variable
*/
private void getSelectedRoles(SessionState state, ParameterParser params,
String listName) {
Hashtable pSelectedRoles = (Hashtable) state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
if (pSelectedRoles == null) {
pSelectedRoles = new Hashtable();
}
List userList = (List) state.getAttribute(listName);
for (int i = 0; i < userList.size(); i++) {
String userId = null;
if (listName.equalsIgnoreCase(STATE_ADD_PARTICIPANTS)) {
userId = ((Participant) userList.get(i)).getUniqname();
} else if (listName.equalsIgnoreCase(STATE_SELECTED_USER_LIST)) {
userId = (String) userList.get(i);
}
if (userId != null) {
String rId = StringUtil.trimToNull(params.getString("role"
+ userId));
if (rId == null) {
addAlert(state, rb.getString("java.rolefor") + " " + userId
+ ". ");
pSelectedRoles.remove(userId);
} else {
pSelectedRoles.put(userId, rId);
}
}
}
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, pSelectedRoles);
} // getSelectedRoles
/**
* dispatch function for changing participants roles
*/
public void doSiteinfo_edit_role(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
// dispatch
if (option.equalsIgnoreCase("same_role_true")) {
state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.TRUE);
state.setAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE, params
.getString("role_to_all"));
} else if (option.equalsIgnoreCase("same_role_false")) {
state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.FALSE);
state.removeAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE);
if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) == null) {
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES,
new Hashtable());
}
} else if (option.equalsIgnoreCase("continue")) {
doContinue(data);
} else if (option.equalsIgnoreCase("back")) {
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
doCancel(data);
}
} // doSiteinfo_edit_globalAccess
/**
* dispatch function for changing site global access
*/
public void doSiteinfo_edit_globalAccess(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
// dispatch
if (option.equalsIgnoreCase("joinable")) {
state.setAttribute("form_joinable", Boolean.TRUE);
state.setAttribute("form_joinerRole", getStateSite(state)
.getJoinerRole());
} else if (option.equalsIgnoreCase("unjoinable")) {
state.setAttribute("form_joinable", Boolean.FALSE);
state.removeAttribute("form_joinerRole");
} else if (option.equalsIgnoreCase("continue")) {
doContinue(data);
} else if (option.equalsIgnoreCase("cancel")) {
doCancel(data);
}
} // doSiteinfo_edit_globalAccess
/**
* save changes to site global access
*/
public void doSiteinfo_save_globalAccess(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
Site s = getStateSite(state);
boolean joinable = ((Boolean) state.getAttribute("form_joinable"))
.booleanValue();
s.setJoinable(joinable);
if (joinable) {
// set the joiner role
String joinerRole = (String) state.getAttribute("form_joinerRole");
s.setJoinerRole(joinerRole);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
// release site edit
commitSite(s);
state.setAttribute(STATE_TEMPLATE_INDEX, "18");
}
} // doSiteinfo_save_globalAccess
/**
* updateSiteAttributes
*
*/
private void updateSiteAttributes(SessionState state) {
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
} else {
M_log
.warn("SiteAction.updateSiteAttributes STATE_SITE_INFO == null");
return;
}
Site site = getStateSite(state);
if (site != null) {
if (StringUtil.trimToNull(siteInfo.title) != null) {
site.setTitle(siteInfo.title);
}
if (siteInfo.description != null) {
site.setDescription(siteInfo.description);
}
site.setPublished(siteInfo.published);
setAppearance(state, site, siteInfo.iconUrl);
site.setJoinable(siteInfo.joinable);
if (StringUtil.trimToNull(siteInfo.joinerRole) != null) {
site.setJoinerRole(siteInfo.joinerRole);
}
// Make changes and then put changed site back in state
String id = site.getId();
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
if (SiteService.allowUpdateSite(id)) {
try {
SiteService.getSite(id);
state.setAttribute(STATE_SITE_INSTANCE_ID, id);
} catch (IdUnusedException e) {
M_log.warn("SiteAction.commitSite IdUnusedException "
+ siteInfo.getTitle() + "(" + id + ") not found");
}
}
// no permission
else {
addAlert(state, rb.getString("java.makechanges"));
M_log.warn("SiteAction.commitSite PermissionException "
+ siteInfo.getTitle() + "(" + id + ")");
}
}
} // updateSiteAttributes
/**
* %%% legacy properties, to be removed
*/
private void updateSiteInfo(ParameterParser params, SessionState state) {
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
siteInfo.site_type = (String) state.getAttribute(STATE_SITE_TYPE);
if (params.getString("title") != null) {
siteInfo.title = params.getString("title");
}
if (params.getString("description") != null) {
siteInfo.description = params.getString("description");
}
if (params.getString("short_description") != null) {
siteInfo.short_description = params.getString("short_description");
}
if (params.getString("additional") != null) {
siteInfo.additional = params.getString("additional");
}
if (params.getString("iconUrl") != null) {
siteInfo.iconUrl = params.getString("iconUrl");
} else {
siteInfo.iconUrl = params.getString("skin");
}
if (params.getString("joinerRole") != null) {
siteInfo.joinerRole = params.getString("joinerRole");
}
if (params.getString("joinable") != null) {
boolean joinable = params.getBoolean("joinable");
siteInfo.joinable = joinable;
if (!joinable)
siteInfo.joinerRole = NULL_STRING;
}
if (params.getString("itemStatus") != null) {
siteInfo.published = Boolean
.valueOf(params.getString("itemStatus")).booleanValue();
}
// site contact information
String name = StringUtil
.trimToZero(params.getString("siteContactName"));
siteInfo.site_contact_name = name;
String email = StringUtil.trimToZero(params
.getString("siteContactEmail"));
if (email != null) {
String[] parts = email.split("@");
if (email.length() > 0
&& (email.indexOf("@") == -1 || parts.length != 2
|| parts[0].length() == 0 || !Validator
.checkEmailLocal(parts[0]))) {
// invalid email
addAlert(state, email + " " + rb.getString("java.invalid")
+ rb.getString("java.theemail"));
}
siteInfo.site_contact_email = email;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
} // updateSiteInfo
/**
* getExternalRealmId
*
*/
private String getExternalRealmId(SessionState state) {
String realmId = SiteService.siteReference((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
String rv = null;
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
rv = realm.getProviderGroupId();
} catch (GroupNotDefinedException e) {
M_log.warn("SiteAction.getExternalRealmId, site realm not found");
}
return rv;
} // getExternalRealmId
/**
* getParticipantList
*
*/
private Collection getParticipantList(SessionState state) {
List members = new Vector();
String realmId = SiteService.siteReference((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
List providerCourseList = null;
providerCourseList = getProviderCourseList(StringUtil
.trimToNull(getExternalRealmId(state)));
if (providerCourseList != null && providerCourseList.size() > 0) {
state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
}
Collection participants = prepareParticipants(realmId, providerCourseList);
state.setAttribute(STATE_PARTICIPANT_LIST, participants);
return participants;
} // getParticipantList
private Collection prepareParticipants(String realmId, List providerCourseList) {
Map participantsMap = new ConcurrentHashMap();
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
realm.getProviderGroupId();
// iterate through the provider list first
for (Iterator i=providerCourseList.iterator(); i.hasNext();)
{
String providerCourseEid = (String) i.next();
try
{
Section section = cms.getSection(providerCourseEid);
if (section != null)
{
// in case of Section eid
EnrollmentSet enrollmentSet = section.getEnrollmentSet();
addParticipantsFromEnrollmentSet(participantsMap, realm, providerCourseEid, enrollmentSet, section.getTitle());
// add memberships
Set memberships = cms.getSectionMemberships(providerCourseEid);
addParticipantsFromMemberships(participantsMap, realm, providerCourseEid, memberships, section.getTitle());
}
}
catch (IdNotFoundException e)
{
M_log.warn("SiteAction prepareParticipants " + e.getMessage() + " sectionId=" + providerCourseEid);
}
}
// now for those not provided users
Set grants = realm.getMembers();
for (Iterator i = grants.iterator(); i.hasNext();) {
Member g = (Member) i.next();
try {
User user = UserDirectoryService.getUserByEid(g.getUserEid());
String userId = user.getId();
if (!participantsMap.containsKey(userId))
{
Participant participant;
if (participantsMap.containsKey(userId))
{
participant = (Participant) participantsMap.get(userId);
}
else
{
participant = new Participant();
}
participant.name = user.getSortName();
participant.uniqname = userId;
participant.role = g.getRole()!=null?g.getRole().getId():"";
participant.removeable = true;
participant.active = g.isActive();
participantsMap.put(userId, participant);
}
} catch (UserNotDefinedException e) {
// deal with missing user quietly without throwing a
// warning message
M_log.warn(e.getMessage());
}
}
} catch (GroupNotDefinedException ee) {
M_log.warn(this + " IdUnusedException " + realmId);
}
return participantsMap.values();
}
/**
* Add participant from provider-defined membership set
* @param participants
* @param realm
* @param providerCourseEid
* @param memberships
*/
private void addParticipantsFromMemberships(Map participantsMap, AuthzGroup realm, String providerCourseEid, Set memberships, String sectionTitle) {
if (memberships != null)
{
for (Iterator mIterator = memberships.iterator();mIterator.hasNext();)
{
Membership m = (Membership) mIterator.next();
try
{
User user = UserDirectoryService.getUserByEid(m.getUserId());
String userId = user.getId();
Member member = realm.getMember(userId);
if (member != null && member.isProvided())
{
// get or add provided participant
Participant participant;
if (participantsMap.containsKey(userId))
{
participant = (Participant) participantsMap.get(userId);
if (!participant.getSectionEidList().contains(sectionTitle)) {
participant.section = participant.section.concat(", <br />" + sectionTitle);
}
}
else
{
participant = new Participant();
participant.credits = "";
participant.name = user.getSortName();
participant.providerRole = member.getRole()!=null?member.getRole().getId():"";
participant.regId = "";
participant.removeable = false;
participant.role = member.getRole()!=null?member.getRole().getId():"";
participant.addSectionEidToList(sectionTitle);
participant.uniqname = userId;
participant.active=member.isActive();
}
participantsMap.put(userId, participant);
}
} catch (UserNotDefinedException exception) {
// deal with missing user quietly without throwing a
// warning message
M_log.warn(exception);
}
}
}
}
/**
* Add participant from provider-defined enrollment set
* @param participants
* @param realm
* @param providerCourseEid
* @param enrollmentSet
*/
private void addParticipantsFromEnrollmentSet(Map participantsMap, AuthzGroup realm, String providerCourseEid, EnrollmentSet enrollmentSet, String sectionTitle) {
if (enrollmentSet != null)
{
Set enrollments = cms.getEnrollments(enrollmentSet.getEid());
if (enrollments != null)
{
for (Iterator eIterator = enrollments.iterator();eIterator.hasNext();)
{
Enrollment e = (Enrollment) eIterator.next();
try
{
User user = UserDirectoryService.getUserByEid(e.getUserId());
String userId = user.getId();
Member member = realm.getMember(userId);
if (member != null && member.isProvided())
{
try
{
// get or add provided participant
Participant participant;
if (participantsMap.containsKey(userId))
{
participant = (Participant) participantsMap.get(userId);
//does this section contain the eid already
if (!participant.getSectionEidList().contains(sectionTitle)) {
participant.addSectionEidToList(sectionTitle);
}
participant.credits = participant.credits.concat(", <br />" + e.getCredits());
}
else
{
participant = new Participant();
participant.credits = e.getCredits();
participant.name = user.getSortName();
participant.providerRole = member.getRole()!=null?member.getRole().getId():"";
participant.regId = "";
participant.removeable = false;
participant.role = member.getRole()!=null?member.getRole().getId():"";
participant.addSectionEidToList(sectionTitle);
participant.uniqname = userId;
participant.active = member.isActive();
}
participantsMap.put(userId, participant);
}
catch (Exception ee)
{
M_log.warn(ee.getMessage());
}
}
} catch (UserNotDefinedException exception) {
// deal with missing user quietly without throwing a
// warning message
M_log.warn(exception.getMessage());
}
}
}
}
}
/**
* getRoles
*
*/
private List getRoles(SessionState state) {
List roles = new Vector();
String realmId = SiteService.siteReference((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
try {
AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);
roles.addAll(realm.getRoles());
Collections.sort(roles);
} catch (GroupNotDefinedException e) {
M_log.warn("SiteAction.getRoles IdUnusedException " + realmId);
}
return roles;
} // getRoles
private void addSynopticTool(SitePage page, String toolId,
String toolTitle, String layoutHint) {
// Add synoptic announcements tool
ToolConfiguration tool = page.addTool();
Tool reg = ToolManager.getTool(toolId);
tool.setTool(toolId, reg);
tool.setTitle(toolTitle);
tool.setLayoutHints(layoutHint);
}
private void getRevisedFeatures(ParameterParser params, SessionState state) {
Site site = getStateSite(state);
// get the list of Worksite Setup configured pages
List wSetupPageList = (List) state
.getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST);
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
WorksiteSetupPage wSetupPage = new WorksiteSetupPage();
WorksiteSetupPage wSetupHome = new WorksiteSetupPage();
List pageList = new Vector();
// declare some flags used in making decisions about Home, whether to
// add, remove, or do nothing
boolean homeInChosenList = false;
boolean homeInWSetupPageList = false;
List chosenList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// if features were selected, diff wSetupPageList and chosenList to get
// page adds and removes
// boolean values for adding synoptic views
boolean hasAnnouncement = false;
boolean hasSchedule = false;
boolean hasChat = false;
boolean hasDiscussion = false;
boolean hasEmail = false;
boolean hasNewSiteInfo = false;
boolean hasMessageCenter = false;
// Special case - Worksite Setup Home comes from a hardcoded checkbox on
// the vm template rather than toolRegistrationList
// see if Home was chosen
for (ListIterator j = chosenList.listIterator(); j.hasNext();) {
String choice = (String) j.next();
if (choice.equalsIgnoreCase(HOME_TOOL_ID)) {
homeInChosenList = true;
} else if (choice.equals("sakai.mailbox")) {
hasEmail = true;
String alias = StringUtil.trimToNull((String) state
.getAttribute(STATE_TOOL_EMAIL_ADDRESS));
if (alias != null) {
if (!Validator.checkEmailLocal(alias)) {
addAlert(state, rb.getString("java.theemail"));
} else {
try {
String channelReference = mailArchiveChannelReference(site
.getId());
// first, clear any alias set to this channel
AliasService.removeTargetAliases(channelReference); // check
// to
// see
// whether
// the
// alias
// has
// been
// used
try {
String target = AliasService.getTarget(alias);
if (target != null) {
addAlert(state, rb
.getString("java.emailinuse")
+ " ");
}
} catch (IdUnusedException ee) {
try {
AliasService.setAlias(alias,
channelReference);
} catch (IdUsedException exception) {
} catch (IdInvalidException exception) {
} catch (PermissionException exception) {
}
}
} catch (PermissionException exception) {
}
}
}
} else if (choice.equals("sakai.announcements")) {
hasAnnouncement = true;
} else if (choice.equals("sakai.schedule")) {
hasSchedule = true;
} else if (choice.equals("sakai.chat")) {
hasChat = true;
} else if (choice.equals("sakai.discussion")) {
hasDiscussion = true;
} else if (choice.equals("sakai.messages") || choice.equals("sakai.forums") || choice.equals("sakai.messagecenter")) {
hasMessageCenter = true;
}
}
// see if Home and/or Help in the wSetupPageList (can just check title
// here, because we checked patterns before adding to the list)
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) {
wSetupPage = (WorksiteSetupPage) i.next();
if (wSetupPage.getToolId().equals(HOME_TOOL_ID)) {
homeInWSetupPageList = true;
}
}
if (homeInChosenList) {
SitePage page = null;
// Were the synoptic views of Announcement, Discussioin, Chat
// existing before the editing
boolean hadAnnouncement = false, hadDiscussion = false, hadChat = false, hadSchedule = false, hadMessageCenter = false;
if (homeInWSetupPageList) {
if (!SiteService.isUserSite(site.getId())) {
// for non-myworkspace site, if Home is chosen and Home is
// in the wSetupPageList, remove synoptic tools
WorksiteSetupPage homePage = new WorksiteSetupPage();
for (ListIterator i = wSetupPageList.listIterator(); i
.hasNext();) {
WorksiteSetupPage comparePage = (WorksiteSetupPage) i
.next();
if ((comparePage.getToolId()).equals(HOME_TOOL_ID)) {
homePage = comparePage;
}
}
page = site.getPage(homePage.getPageId());
List toolList = page.getTools();
List removeToolList = new Vector();
// get those synoptic tools
for (ListIterator iToolList = toolList.listIterator(); iToolList
.hasNext();) {
ToolConfiguration tool = (ToolConfiguration) iToolList
.next();
Tool t = tool.getTool();
if (t!= null)
{
if (t.getId().equals("sakai.synoptic.announcement")) {
hadAnnouncement = true;
if (!hasAnnouncement) {
removeToolList.add(tool);// if Announcement
// tool isn't
// selected, remove
// the synotic
// Announcement
}
}
else if (t.getId().equals(TOOL_ID_SUMMARY_CALENDAR)) {
hadSchedule = true;
if (!hasSchedule || !notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR)) {
// if Schedule tool isn't selected, or the summary calendar tool is stealthed or hidden, remove the synotic Schedule
removeToolList.add(tool);
}
}
else if (t.getId().equals("sakai.synoptic.discussion")) {
hadDiscussion = true;
if (!hasDiscussion) {
removeToolList.add(tool);// if Discussion
// tool isn't
// selected, remove
// the synoptic
// Discussion
}
}
else if (t.getId().equals("sakai.synoptic.chat")) {
hadChat = true;
if (!hasChat) {
removeToolList.add(tool);// if Chat tool
// isn't selected,
// remove the
// synoptic Chat
}
}
else if (t.getId().equals("sakai.synoptic.messagecenter")) {
hadMessageCenter = true;
if (!hasMessageCenter) {
removeToolList.add(tool);// if Messages and/or Forums tools
// isn't selected,
// remove the
// synoptic Message Center tool
}
}
}
}
// remove those synoptic tools
for (ListIterator rToolList = removeToolList.listIterator(); rToolList
.hasNext();) {
page.removeTool((ToolConfiguration) rToolList.next());
}
}
} else {
// if Home is chosen and Home is not in wSetupPageList, add Home
// to site and wSetupPageList
page = site.addPage();
page.setTitle(rb.getString("java.home"));
wSetupHome.pageId = page.getId();
wSetupHome.pageTitle = page.getTitle();
wSetupHome.toolId = HOME_TOOL_ID;
wSetupPageList.add(wSetupHome);
// Add worksite information tool
ToolConfiguration tool = page.addTool();
Tool reg = ToolManager.getTool("sakai.iframe.site");
tool.setTool("sakai.iframe.site", reg);
tool.setTitle(reg.getTitle());
tool.setLayoutHints("0,0");
}
if (!SiteService.isUserSite(site.getId())) {
// add synoptical tools to home tool in non-myworkspace site
try {
if (hasAnnouncement && !hadAnnouncement) {
// Add synoptic announcements tool
addSynopticTool(page, "sakai.synoptic.announcement", rb
.getString("java.recann"), "0,1");
}
if (hasDiscussion && !hadDiscussion) {
// Add synoptic discussion tool
addSynopticTool(page, "sakai.synoptic.discussion", rb
.getString("java.recdisc"), "1,1");
}
if (hasChat && !hadChat) {
// Add synoptic chat tool
addSynopticTool(page, "sakai.synoptic.chat", rb
.getString("java.recent"), "2,1");
}
if (hasSchedule && !hadSchedule) {
// Add synoptic schedule tool if not stealth or hidden
if (notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR))
addSynopticTool(page, TOOL_ID_SUMMARY_CALENDAR, rb
.getString("java.reccal"), "3,1");
}
if (hasMessageCenter && !hadMessageCenter) {
// Add synoptic Message Center
addSynopticTool(page, "sakai.synoptic.messagecenter", rb
.getString("java.recmsg"), "4,1");
}
if (hasAnnouncement || hasDiscussion || hasChat
|| hasSchedule || hasMessageCenter) {
page.setLayout(SitePage.LAYOUT_DOUBLE_COL);
} else {
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
}
} catch (Exception e) {
M_log.warn("SiteAction getRevisedFeatures Exception: " + e.getMessage());
}
}
} // add Home
// if Home is in wSetupPageList and not chosen, remove Home feature from
// wSetupPageList and site
if (!homeInChosenList && homeInWSetupPageList) {
// remove Home from wSetupPageList
WorksiteSetupPage removePage = new WorksiteSetupPage();
for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) {
WorksiteSetupPage comparePage = (WorksiteSetupPage) i.next();
if (comparePage.getToolId().equals(HOME_TOOL_ID)) {
removePage = comparePage;
}
}
SitePage siteHome = site.getPage(removePage.getPageId());
site.removePage(siteHome);
wSetupPageList.remove(removePage);
}
// declare flags used in making decisions about whether to add, remove,
// or do nothing
boolean inChosenList;
boolean inWSetupPageList;
Set categories = new HashSet();
categories.add((String) state.getAttribute(STATE_SITE_TYPE));
Set toolRegistrationList = ToolManager.findTools(categories, null);
// first looking for any tool for removal
Vector removePageIds = new Vector();
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) {
wSetupPage = (WorksiteSetupPage) k.next();
String pageToolId = wSetupPage.getToolId();
// use page id + tool id for multiple tool instances
if (isMultipleInstancesAllowed(findOriginalToolId(state, pageToolId))) {
pageToolId = wSetupPage.getPageId() + pageToolId;
}
inChosenList = false;
for (ListIterator j = chosenList.listIterator(); j.hasNext();) {
String toolId = (String) j.next();
if (pageToolId.equals(toolId)) {
inChosenList = true;
}
}
if (!inChosenList) {
removePageIds.add(wSetupPage.getPageId());
}
}
for (int i = 0; i < removePageIds.size(); i++) {
// if the tool exists in the wSetupPageList, remove it from the site
String removeId = (String) removePageIds.get(i);
SitePage sitePage = site.getPage(removeId);
site.removePage(sitePage);
// and remove it from wSetupPageList
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) {
wSetupPage = (WorksiteSetupPage) k.next();
if (!wSetupPage.getPageId().equals(removeId)) {
wSetupPage = null;
}
}
if (wSetupPage != null) {
wSetupPageList.remove(wSetupPage);
}
}
// then looking for any tool to add
for (ListIterator j = orderToolIds(state,
(String) state.getAttribute(STATE_SITE_TYPE), chosenList)
.listIterator(); j.hasNext();) {
String toolId = (String) j.next();
// Is the tool in the wSetupPageList?
inWSetupPageList = false;
for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) {
wSetupPage = (WorksiteSetupPage) k.next();
String pageToolId = wSetupPage.getToolId();
// use page Id + toolId for multiple tool instances
if (isMultipleInstancesAllowed(findOriginalToolId(state, pageToolId))) {
pageToolId = wSetupPage.getPageId() + pageToolId;
}
if (pageToolId.equals(toolId)) {
inWSetupPageList = true;
// but for tool of multiple instances, need to change the title
if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) {
SitePage pEdit = (SitePage) site
.getPage(wSetupPage.pageId);
pEdit.setTitle((String) multipleToolIdTitleMap.get(toolId));
List toolList = pEdit.getTools();
for (ListIterator jTool = toolList.listIterator(); jTool
.hasNext();) {
ToolConfiguration tool = (ToolConfiguration) jTool
.next();
String tId = tool.getTool().getId();
if (isMultipleInstancesAllowed(findOriginalToolId(state, tId))) {
// set tool title
tool.setTitle((String) multipleToolIdTitleMap.get(toolId));
}
}
}
}
}
if (inWSetupPageList) {
// if the tool already in the list, do nothing so to save the
// option settings
} else {
// if in chosen list but not in wSetupPageList, add it to the
// site (one tool on a page)
// if Site Info tool is being newly added
if (toolId.equals("sakai.siteinfo")) {
hasNewSiteInfo = true;
}
Tool toolRegFound = null;
for (Iterator i = toolRegistrationList.iterator(); i.hasNext();) {
Tool toolReg = (Tool) i.next();
if ((toolId.indexOf("assignment") != -1 && toolId
.equals(toolReg.getId()))
|| (toolId.indexOf("assignment") == -1 && toolId
.indexOf(toolReg.getId()) != -1)) {
toolRegFound = toolReg;
}
}
if (toolRegFound != null) {
// we know such a tool, so add it
WorksiteSetupPage addPage = new WorksiteSetupPage();
SitePage page = site.addPage();
addPage.pageId = page.getId();
if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) {
// set tool title
page.setTitle((String) multipleToolIdTitleMap.get(toolId));
} else {
// other tools with default title
page.setTitle(toolRegFound.getTitle());
}
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool(toolRegFound.getId(), toolRegFound);
addPage.toolId = toolId;
wSetupPageList.add(addPage);
// set tool title
if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) {
// set tool title
tool.setTitle((String) multipleToolIdTitleMap.get(toolId));
} else {
tool.setTitle(toolRegFound.getTitle());
}
}
}
} // for
if (homeInChosenList) {
// Order tools - move Home to the top - first find it
SitePage homePage = null;
pageList = site.getPages();
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
if (rb.getString("java.home").equals(page.getTitle()))// if
// ("Home".equals(page.getTitle()))
{
homePage = page;
break;
}
}
}
// if found, move it
if (homePage != null) {
// move home from it's index to the first position
int homePosition = pageList.indexOf(homePage);
for (int n = 0; n < homePosition; n++) {
homePage.moveUp();
}
}
}
// if Site Info is newly added, more it to the last
if (hasNewSiteInfo) {
SitePage siteInfoPage = null;
pageList = site.getPages();
String[] toolIds = { "sakai.siteinfo" };
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); siteInfoPage == null
&& i.hasNext();) {
SitePage page = (SitePage) i.next();
int s = page.getTools(toolIds).size();
if (s > 0) {
siteInfoPage = page;
}
}
}
// if found, move it
if (siteInfoPage != null) {
// move home from it's index to the first position
int siteInfoPosition = pageList.indexOf(siteInfoPage);
for (int n = siteInfoPosition; n < pageList.size(); n++) {
siteInfoPage.moveDown();
}
}
}
// if there is no email tool chosen
if (!hasEmail) {
state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS);
}
// commit
commitSite(site);
} // getRevisedFeatures
/**
* Is the tool stealthed or hidden
* @param toolId
* @return
*/
private boolean notStealthOrHiddenTool(String toolId) {
return (ToolManager.getTool(toolId) != null
&& !ServerConfigurationService
.getString(
"[email protected]")
.contains(toolId)
&& !ServerConfigurationService
.getString(
"[email protected]")
.contains(toolId));
}
/**
* getFeatures gets features for a new site
*
*/
private void getFeatures(ParameterParser params, SessionState state, String continuePageIndex) {
List idsSelected = new Vector();
List existTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null? new Vector():(List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
// to reset the state variable of the multiple tool instances
Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET):new HashSet();
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
boolean goToToolConfigPage = false;
boolean homeSelected = false;
// Add new pages and tools, if any
if (params.getStrings("selectedTools") == null) {
addAlert(state, rb.getString("atleastonetool"));
} else {
List l = new ArrayList(Arrays.asList(params
.getStrings("selectedTools"))); // toolId's & titles of
// chosen tools
for (int i = 0; i < l.size(); i++) {
String toolId = (String) l.get(i);
if (toolId.equals(HOME_TOOL_ID)) {
homeSelected = true;
} else if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId)))
{
// if user is adding either EmailArchive tool, News tool
// or Web Content tool, go to the Customize page for the
// tool
if (!existTools.contains(toolId)) {
goToToolConfigPage = true;
multipleToolIdSet.add(toolId);
multipleToolIdTitleMap.put(toolId, ToolManager.getTool(toolId).getTitle());
}
if (toolId.equals("sakai.mailbox")) {
// get the email alias when an Email Archive tool
// has been selected
String channelReference = mailArchiveChannelReference((String) state
.getAttribute(STATE_SITE_INSTANCE_ID));
List aliases = AliasService.getAliases(
channelReference, 1, 1);
if (aliases.size() > 0) {
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS,
((Alias) aliases.get(0)).getId());
}
}
}
idsSelected.add(toolId);
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(
homeSelected));
}
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List of ToolRegistration toolId's
// in case of import
String importString = params.getString("import");
if (importString != null
&& importString.equalsIgnoreCase(Boolean.TRUE.toString())) {
state.setAttribute(STATE_IMPORT, Boolean.TRUE);
List importSites = new Vector();
if (params.getStrings("importSites") != null) {
importSites = new ArrayList(Arrays.asList(params
.getStrings("importSites")));
}
if (importSites.size() == 0) {
addAlert(state, rb.getString("java.toimport") + " ");
} else {
Hashtable sites = new Hashtable();
for (int index = 0; index < importSites.size(); index++) {
try {
Site s = SiteService.getSite((String) importSites
.get(index));
if (!sites.containsKey(s)) {
sites.put(s, new Vector());
}
} catch (IdUnusedException e) {
}
}
state.setAttribute(STATE_IMPORT_SITES, sites);
}
} else {
state.removeAttribute(STATE_IMPORT);
}
// of
// ToolRegistration
// toolId's
if (state.getAttribute(STATE_MESSAGE) == null) {
if (state.getAttribute(STATE_IMPORT) != null) {
// go to import tool page
state.setAttribute(STATE_TEMPLATE_INDEX, "27");
} else if (goToToolConfigPage) {
// go to the configuration page for multiple instances of tools
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
} else {
// go to next page
state.setAttribute(STATE_TEMPLATE_INDEX, continuePageIndex);
}
state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet);
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
}
} // getFeatures
/**
* addFeatures adds features to a new site
*
*/
private void addFeatures(SessionState state) {
List toolRegistrationList = (Vector) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET);
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
Site site = getStateSite(state);
List pageList = new Vector();
int moves = 0;
boolean hasHome = false;
boolean hasAnnouncement = false;
boolean hasSchedule = false;
boolean hasChat = false;
boolean hasDiscussion = false;
boolean hasSiteInfo = false;
boolean hasMessageCenter = false;
List chosenList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// tools to be imported from other sites?
Hashtable importTools = null;
if (state.getAttribute(STATE_IMPORT_SITE_TOOL) != null) {
importTools = (Hashtable) state.getAttribute(STATE_IMPORT_SITE_TOOL);
}
// for tools other than home
if (chosenList.contains(HOME_TOOL_ID)) {
// add home tool later
hasHome = true;
}
// order the id list
chosenList = orderToolIds(state, site.getType(), chosenList);
if (chosenList.size() > 0) {
Tool toolRegFound = null;
for (ListIterator i = chosenList.listIterator(); i.hasNext();) {
String toolId = (String) i.next();
// find the tool in the tool registration list
toolRegFound = null;
for (int j = 0; j < toolRegistrationList.size()
&& toolRegFound == null; j++) {
MyTool tool = (MyTool) toolRegistrationList.get(j);
if ((toolId.indexOf("assignment") != -1 && toolId
.equals(tool.getId()))
|| (toolId.indexOf("assignment") == -1 && toolId
.indexOf(tool.getId()) != -1)) {
toolRegFound = ToolManager.getTool(tool.getId());
}
}
if (toolRegFound != null) {
String originToolId = findOriginalToolId(state, toolId);
if (isMultipleInstancesAllowed(originToolId)) {
if (originToolId != null)
{
// adding multiple tool instance
String title = (String) multipleToolIdTitleMap.get(toolId);
SitePage page = site.addPage();
page.setTitle(title); // the visible label on the tool
// menu
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool(originToolId, ToolManager
.getTool(originToolId));
tool.setTitle(title);
tool.setLayoutHints("0,0");
}
} else {
SitePage page = site.addPage();
page.setTitle(toolRegFound.getTitle()); // the visible
// label on the
// tool menu
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
ToolConfiguration tool = page.addTool();
tool.setTool(toolRegFound.getId(), toolRegFound);
tool.setLayoutHints("0,0");
} // Other features
}
// booleans for synoptic views
if (toolId.equals("sakai.announcements")) {
hasAnnouncement = true;
} else if (toolId.equals("sakai.schedule")) {
hasSchedule = true;
} else if (toolId.equals("sakai.chat")) {
hasChat = true;
} else if (toolId.equals("sakai.discussion")) {
hasDiscussion = true;
} else if (toolId.equals("sakai.siteinfo")) {
hasSiteInfo = true;
} else if (toolId.equals("sakai.messages") || toolId.equals("sakai.forums") || toolId.equals("sakai.messagecenter")) {
hasMessageCenter = true;
}
} // for
// add home tool
if (hasHome) {
// Home is a special case, with several tools on the page.
// "home" is hard coded in chef_site-addRemoveFeatures.vm.
try {
SitePage page = site.addPage();
page.setTitle(rb.getString("java.home")); // the visible
// label on the
// tool menu
if (hasAnnouncement || hasDiscussion || hasChat
|| hasSchedule) {
page.setLayout(SitePage.LAYOUT_DOUBLE_COL);
} else {
page.setLayout(SitePage.LAYOUT_SINGLE_COL);
}
// Add worksite information tool
ToolConfiguration tool = page.addTool();
Tool wsInfoTool = ToolManager.getTool("sakai.iframe.site");
tool.setTool("sakai.iframe.site", wsInfoTool);
tool.setTitle(wsInfoTool != null?wsInfoTool.getTitle():"");
tool.setLayoutHints("0,0");
if (hasAnnouncement) {
// Add synoptic announcements tool
tool = page.addTool();
tool.setTool("sakai.synoptic.announcement", ToolManager
.getTool("sakai.synoptic.announcement"));
tool.setTitle(rb.getString("java.recann"));
tool.setLayoutHints("0,1");
}
if (hasDiscussion) {
// Add synoptic announcements tool
tool = page.addTool();
tool.setTool("sakai.synoptic.discussion", ToolManager
.getTool("sakai.synoptic.discussion"));
tool.setTitle("Recent Discussion Items");
tool.setLayoutHints("1,1");
}
if (hasChat) {
// Add synoptic chat tool
tool = page.addTool();
tool.setTool("sakai.synoptic.chat", ToolManager
.getTool("sakai.synoptic.chat"));
tool.setTitle("Recent Chat Messages");
tool.setLayoutHints("2,1");
}
if (hasSchedule && notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR)) {
// Add synoptic schedule tool
tool = page.addTool();
tool.setTool(TOOL_ID_SUMMARY_CALENDAR, ToolManager
.getTool(TOOL_ID_SUMMARY_CALENDAR));
tool.setTitle(rb.getString("java.reccal"));
tool.setLayoutHints("3,1");
}
if (hasMessageCenter) {
// Add synoptic Message Center tool
tool = page.addTool();
tool.setTool("sakai.synoptic.messagecenter", ToolManager
.getTool("sakai.synoptic.messagecenter"));
tool.setTitle(rb.getString("java.recmsg"));
tool.setLayoutHints("4,1");
}
} catch (Exception e) {
M_log.warn("SiteAction addFeatures Exception:" + e.getMessage());
}
state.setAttribute(STATE_TOOL_HOME_SELECTED, Boolean.TRUE);
// Order tools - move Home to the top
pageList = site.getPages();
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
if ((page.getTitle()).equals(rb.getString("java.home"))) {
moves = pageList.indexOf(page);
for (int n = 0; n < moves; n++) {
page.moveUp();
}
}
}
}
} // Home feature
// move Site Info tool, if selected, to the end of tool list
if (hasSiteInfo) {
SitePage siteInfoPage = null;
pageList = site.getPages();
String[] toolIds = { "sakai.siteinfo" };
if (pageList != null && pageList.size() != 0) {
for (ListIterator i = pageList.listIterator(); siteInfoPage == null
&& i.hasNext();) {
SitePage page = (SitePage) i.next();
int s = page.getTools(toolIds).size();
if (s > 0) {
siteInfoPage = page;
}
}
}
// if found, move it
if (siteInfoPage != null) {
// move home from it's index to the first position
int siteInfoPosition = pageList.indexOf(siteInfoPage);
for (int n = siteInfoPosition; n < pageList.size(); n++) {
siteInfoPage.moveDown();
}
}
} // Site Info
}
// commit
commitSite(site);
// import
importToolIntoSite(chosenList, importTools, site);
} // addFeatures
// import tool content into site
private void importToolIntoSite(List toolIds, Hashtable importTools,
Site site) {
if (importTools != null) {
// import resources first
boolean resourcesImported = false;
for (int i = 0; i < toolIds.size() && !resourcesImported; i++) {
String toolId = (String) toolIds.get(i);
if (toolId.equalsIgnoreCase("sakai.resources")
&& importTools.containsKey(toolId)) {
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
String fromSiteCollectionId = ContentHostingService
.getSiteCollection(fromSiteId);
String toSiteCollectionId = ContentHostingService
.getSiteCollection(toSiteId);
transferCopyEntities(toolId, fromSiteCollectionId,
toSiteCollectionId);
resourcesImported = true;
}
}
}
// ijmport other tools then
for (int i = 0; i < toolIds.size(); i++) {
String toolId = (String) toolIds.get(i);
if (!toolId.equalsIgnoreCase("sakai.resources")
&& importTools.containsKey(toolId)) {
List importSiteIds = (List) importTools.get(toolId);
for (int k = 0; k < importSiteIds.size(); k++) {
String fromSiteId = (String) importSiteIds.get(k);
String toSiteId = site.getId();
transferCopyEntities(toolId, fromSiteId, toSiteId);
}
}
}
}
} // importToolIntoSite
public void saveSiteStatus(SessionState state, boolean published) {
Site site = getStateSite(state);
site.setPublished(published);
} // saveSiteStatus
public void commitSite(Site site, boolean published) {
site.setPublished(published);
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
} // commitSite
public void commitSite(Site site) {
try {
SiteService.save(site);
} catch (IdUnusedException e) {
// TODO:
} catch (PermissionException e) {
// TODO:
}
}// commitSite
private boolean isValidDomain(String email) {
String invalidNonOfficialAccountString = ServerConfigurationService
.getString("invalidNonOfficialAccountString", null);
if (invalidNonOfficialAccountString != null) {
String[] invalidDomains = invalidNonOfficialAccountString.split(",");
for (int i = 0; i < invalidDomains.length; i++) {
String domain = invalidDomains[i].trim();
if (email.toLowerCase().indexOf(domain.toLowerCase()) != -1) {
return false;
}
}
}
return true;
}
private void checkAddParticipant(ParameterParser params, SessionState state) {
// get the participants to be added
int i;
Vector pList = new Vector();
HashSet existingUsers = new HashSet();
Site site = null;
String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
try {
site = SiteService.getSite(siteId);
} catch (IdUnusedException e) {
addAlert(state, rb.getString("java.specif") + " " + siteId);
}
// accept officialAccounts and/or nonOfficialAccount account names
String officialAccounts = "";
String nonOfficialAccounts = "";
// check that there is something with which to work
officialAccounts = StringUtil.trimToNull((params
.getString("officialAccount")));
nonOfficialAccounts = StringUtil.trimToNull(params
.getString("nonOfficialAccount"));
state.setAttribute("officialAccountValue", officialAccounts);
state.setAttribute("nonOfficialAccountValue", nonOfficialAccounts);
// if there is no uniquname or nonOfficialAccount entered
if (officialAccounts == null && nonOfficialAccounts == null) {
addAlert(state, rb.getString("java.guest"));
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
return;
}
String at = "@";
if (officialAccounts != null) {
// adding officialAccounts
String[] officialAccountArray = officialAccounts
.split("\r\n");
for (i = 0; i < officialAccountArray.length; i++) {
String officialAccount = StringUtil
.trimToNull(officialAccountArray[i].replaceAll(
"[\t\r\n]", ""));
// if there is some text, try to use it
if (officialAccount != null) {
// automaticially add nonOfficialAccount account
Participant participant = new Participant();
try {
//Changed user lookup to satisfy BSP-1010 (jholtzman)
User u = null;
// First try looking for the user by their email address
Collection usersWithEmail = UserDirectoryService.findUsersByEmail(officialAccount);
if(usersWithEmail != null) {
if(usersWithEmail.size() == 0) {
// If the collection is empty, we didn't find any users with this email address
M_log.info("Unable to find users with email " + officialAccount);
} else if (usersWithEmail.size() == 1) {
// We found one user with this email address. Use it.
u = (User)usersWithEmail.iterator().next();
} else if (usersWithEmail.size() > 1) {
// If we have multiple users with this email address, pick one and log this error condition
// TODO Should we not pick a user? Throw an exception?
M_log.warn("Found multiple user with email " + officialAccount);
u = (User)usersWithEmail.iterator().next();
}
}
// We didn't find anyone via email address, so try getting the user by EID
if(u == null) {
u = UserDirectoryService.getUserByEid(officialAccount);
if (u != null)
M_log.info("found user with eid " + officialAccount);
}
if (site != null && site.getUserRole(u.getId()) != null) {
// user already exists in the site, cannot be added
// again
existingUsers.add(officialAccount);
} else {
participant.name = u.getDisplayName();
participant.uniqname = u.getEid();
participant.active = true;
pList.add(participant);
}
} catch (UserNotDefinedException e) {
addAlert(state, officialAccount + " " + rb.getString("java.username") + " ");
}
}
}
} // officialAccounts
if (nonOfficialAccounts != null) {
String[] nonOfficialAccountArray = nonOfficialAccounts.split("\r\n");
for (i = 0; i < nonOfficialAccountArray.length; i++) {
String nonOfficialAccount = nonOfficialAccountArray[i];
// if there is some text, try to use it
nonOfficialAccount.replaceAll("[ \t\r\n]", "");
// remove the trailing dots and empty space
while (nonOfficialAccount.endsWith(".")
|| nonOfficialAccount.endsWith(" ")) {
nonOfficialAccount = nonOfficialAccount.substring(0,
nonOfficialAccount.length() - 1);
}
if (nonOfficialAccount != null && nonOfficialAccount.length() > 0) {
String[] parts = nonOfficialAccount.split(at);
if (nonOfficialAccount.indexOf(at) == -1) {
// must be a valid email address
addAlert(state, nonOfficialAccount + " "
+ rb.getString("java.emailaddress"));
} else if ((parts.length != 2) || (parts[0].length() == 0)) {
// must have both id and address part
addAlert(state, nonOfficialAccount + " "
+ rb.getString("java.notemailid"));
} else if (!Validator.checkEmailLocal(parts[0])) {
addAlert(state, nonOfficialAccount + " "
+ rb.getString("java.emailaddress")
+ rb.getString("java.theemail"));
} else if (nonOfficialAccount != null
&& !isValidDomain(nonOfficialAccount)) {
// wrong string inside nonOfficialAccount id
addAlert(state, nonOfficialAccount + " "
+ rb.getString("java.emailaddress") + " ");
} else {
Participant participant = new Participant();
try {
// if the nonOfficialAccount user already exists
User u = UserDirectoryService
.getUserByEid(nonOfficialAccount);
if (site != null
&& site.getUserRole(u.getId()) != null) {
// user already exists in the site, cannot be
// added again
existingUsers.add(nonOfficialAccount);
} else {
participant.name = u.getDisplayName();
participant.uniqname = nonOfficialAccount;
participant.active = true;
pList.add(participant);
}
} catch (UserNotDefinedException e) {
// if the nonOfficialAccount user is not in the system
// yet
participant.name = nonOfficialAccount;
participant.uniqname = nonOfficialAccount; // TODO:
// what
// would
// the
// UDS
// case
// this
// name
// to?
// -ggolden
participant.active = true;
pList.add(participant);
}
}
} // if
} //
} // nonOfficialAccounts
boolean same_role = true;
if (params.getString("same_role") == null) {
addAlert(state, rb.getString("java.roletype") + " ");
} else {
same_role = params.getString("same_role").equals("true") ? true
: false;
state.setAttribute("form_same_role", new Boolean(same_role));
}
if (state.getAttribute(STATE_MESSAGE) != null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
} else {
if (same_role) {
state.setAttribute(STATE_TEMPLATE_INDEX, "19");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "20");
}
}
// remove duplicate or existing user from participant list
pList = removeDuplicateParticipants(pList, state);
state.setAttribute(STATE_ADD_PARTICIPANTS, pList);
// if the add participant list is empty after above removal, stay in the
// current page
if (pList.size() == 0) {
state.setAttribute(STATE_TEMPLATE_INDEX, "5");
}
// add alert for attempting to add existing site user(s)
if (!existingUsers.isEmpty()) {
int count = 0;
String accounts = "";
for (Iterator eIterator = existingUsers.iterator(); eIterator
.hasNext();) {
if (count == 0) {
accounts = (String) eIterator.next();
} else {
accounts = accounts + ", " + (String) eIterator.next();
}
count++;
}
addAlert(state, rb.getString("add.existingpart.1") + accounts
+ rb.getString("add.existingpart.2"));
}
return;
} // checkAddParticipant
private Vector removeDuplicateParticipants(List pList, SessionState state) {
// check the uniqness of list member
Set s = new HashSet();
Set uniqnameSet = new HashSet();
Vector rv = new Vector();
for (int i = 0; i < pList.size(); i++) {
Participant p = (Participant) pList.get(i);
if (!uniqnameSet.contains(p.getUniqname())) {
// no entry for the account yet
rv.add(p);
uniqnameSet.add(p.getUniqname());
} else {
// found duplicates
s.add(p.getUniqname());
}
}
if (!s.isEmpty()) {
int count = 0;
String accounts = "";
for (Iterator i = s.iterator(); i.hasNext();) {
if (count == 0) {
accounts = (String) i.next();
} else {
accounts = accounts + ", " + (String) i.next();
}
count++;
}
if (count == 1) {
addAlert(state, rb.getString("add.duplicatedpart.single")
+ accounts + ".");
} else {
addAlert(state, rb.getString("add.duplicatedpart") + accounts
+ ".");
}
}
return rv;
}
public void doAdd_participant(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String siteTitle = getStateSite(state).getTitle();
String nonOfficialAccountLabel = ServerConfigurationService.getString(
"nonOfficialAccountLabel", "");
Hashtable selectedRoles = (Hashtable) state
.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
boolean notify = false;
if (state.getAttribute("form_selectedNotify") != null) {
notify = ((Boolean) state.getAttribute("form_selectedNotify"))
.booleanValue();
}
boolean same_role = ((Boolean) state.getAttribute("form_same_role"))
.booleanValue();
Hashtable eIdRoles = new Hashtable();
List addParticipantList = (List) state
.getAttribute(STATE_ADD_PARTICIPANTS);
for (int i = 0; i < addParticipantList.size(); i++) {
Participant p = (Participant) addParticipantList.get(i);
String eId = p.getEid();
// role defaults to same role
String role = (String) state.getAttribute("form_selectedRole");
if (!same_role) {
// if all added participants have different role
role = (String) selectedRoles.get(eId);
}
boolean officialAccount = eId.indexOf(EMAIL_CHAR) == -1;
if (officialAccount) {
// if this is a officialAccount
// update the hashtable
eIdRoles.put(eId, role);
} else {
// if this is an nonOfficialAccount
try {
UserDirectoryService.getUserByEid(eId);
} catch (UserNotDefinedException e) {
// if there is no such user yet, add the user
try {
UserEdit uEdit = UserDirectoryService
.addUser(null, eId);
// set email address
uEdit.setEmail(eId);
// set the guest user type
uEdit.setType("guest");
// set password to a positive random number
Random generator = new Random(System
.currentTimeMillis());
Integer num = new Integer(generator
.nextInt(Integer.MAX_VALUE));
if (num.intValue() < 0)
num = new Integer(num.intValue() * -1);
String pw = num.toString();
uEdit.setPassword(pw);
// and save
UserDirectoryService.commitEdit(uEdit);
boolean notifyNewUserEmail = (ServerConfigurationService
.getString("notifyNewUserEmail", Boolean.TRUE
.toString()))
.equalsIgnoreCase(Boolean.TRUE.toString());
if (notifyNewUserEmail) {
userNotificationProvider.notifyNewUserEmail(uEdit, pw, siteTitle);
}
} catch (UserIdInvalidException ee) {
addAlert(state, nonOfficialAccountLabel + " id " + eId
+ " " + rb.getString("java.isinval"));
M_log.warn(this
+ " UserDirectoryService addUser exception "
+ e.getMessage());
} catch (UserAlreadyDefinedException ee) {
addAlert(state, "The " + nonOfficialAccountLabel + " "
+ eId + " " + rb.getString("java.beenused"));
M_log.warn(this
+ " UserDirectoryService addUser exception "
+ e.getMessage());
} catch (UserPermissionException ee) {
addAlert(state, rb.getString("java.haveadd") + " "
+ eId);
M_log.warn(this
+ " UserDirectoryService addUser exception "
+ e.getMessage());
}
}
if (state.getAttribute(STATE_MESSAGE) == null) {
eIdRoles.put(eId, role);
}
}
}
// batch add and updates the successful added list
List addedParticipantEIds = addUsersRealm(state, eIdRoles, notify,
false);
// update the not added user list
String notAddedOfficialAccounts = null;
String notAddedNonOfficialAccounts = null;
for (Iterator iEIds = eIdRoles.keySet().iterator(); iEIds.hasNext();) {
String iEId = (String) iEIds.next();
if (!addedParticipantEIds.contains(iEId)) {
if (iEId.indexOf(EMAIL_CHAR) == -1) {
// no email in eid
notAddedOfficialAccounts = notAddedOfficialAccounts
.concat(iEId + "\n");
} else {
// email in eid
notAddedNonOfficialAccounts = notAddedNonOfficialAccounts
.concat(iEId + "\n");
}
}
}
if (addedParticipantEIds.size() != 0
&& (notAddedOfficialAccounts != null || notAddedNonOfficialAccounts != null)) {
// at lease one officialAccount account or an nonOfficialAccount
// account added, and there are also failures
addAlert(state, rb.getString("java.allusers"));
}
if (notAddedOfficialAccounts == null
&& notAddedNonOfficialAccounts == null) {
// all account has been added successfully
removeAddParticipantContext(state);
} else {
state.setAttribute("officialAccountValue",
notAddedOfficialAccounts);
state.setAttribute("nonOfficialAccountValue",
notAddedNonOfficialAccounts);
}
if (state.getAttribute(STATE_MESSAGE) != null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "22");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "12");
}
return;
} // doAdd_participant
/**
* remove related state variable for adding participants
*
* @param state
* SessionState object
*/
private void removeAddParticipantContext(SessionState state) {
// remove related state variables
state.removeAttribute("form_selectedRole");
state.removeAttribute("officialAccountValue");
state.removeAttribute("nonOfficialAccountValue");
state.removeAttribute("form_same_role");
state.removeAttribute("form_selectedNotify");
state.removeAttribute(STATE_ADD_PARTICIPANTS);
state.removeAttribute(STATE_SELECTED_USER_LIST);
state.removeAttribute(STATE_SELECTED_PARTICIPANT_ROLES);
} // removeAddParticipantContext
private String getSetupRequestEmailAddress() {
String from = ServerConfigurationService.getString("setup.request",
null);
if (from == null) {
from = "postmaster@".concat(ServerConfigurationService
.getServerName());
M_log.warn(this + " - no 'setup.request' in configuration, using: "+ from);
}
return from;
}
/*
* Given a list of user eids, add users to realm If the user account does
* not exist yet inside the user directory, assign role to it @return A list
* of eids for successfully added users
*/
private List addUsersRealm(SessionState state, Hashtable eIdRoles,
boolean notify, boolean nonOfficialAccount) {
// return the list of user eids for successfully added user
List addedUserEIds = new Vector();
StringBuilder message = new StringBuilder();
if (eIdRoles != null && !eIdRoles.isEmpty()) {
// get the current site
Site sEdit = getStateSite(state);
if (sEdit != null) {
// get realm object
String realmId = sEdit.getReference();
try {
AuthzGroup realmEdit = AuthzGroupService
.getAuthzGroup(realmId);
for (Iterator eIds = eIdRoles.keySet().iterator(); eIds
.hasNext();) {
String eId = (String) eIds.next();
String role = (String) eIdRoles.get(eId);
try {
User user = UserDirectoryService.getUserByEid(eId);
if (AuthzGroupService.allowUpdate(realmId)
|| SiteService
.allowUpdateSiteMembership(sEdit
.getId())) {
realmEdit.addMember(user.getId(), role, true,
false);
addedUserEIds.add(eId);
// send notification
if (notify) {
String emailId = user.getEmail();
String userName = user.getDisplayName();
// send notification email
if (this.userNotificationProvider == null)
M_log.warn("notification provider is null!");
userNotificationProvider.notifyAddedParticipant(nonOfficialAccount, user, sEdit.getTitle());
}
}
} catch (UserNotDefinedException e) {
message.append(eId + " "
+ rb.getString("java.account") + " \n");
} // try
} // for
try {
AuthzGroupService.save(realmEdit);
} catch (GroupNotDefinedException ee) {
message.append(rb.getString("java.realm") + realmId);
} catch (AuthzPermissionException ee) {
message.append(rb.getString("java.permeditsite")
+ realmId);
}
} catch (GroupNotDefinedException eee) {
message.append(rb.getString("java.realm") + realmId);
} catch (Exception eee) {
M_log.warn("SiteActionaddUsersRealm " + eee.getMessage() + " realmId=" + realmId);
}
}
}
if (message.length() != 0) {
addAlert(state, message.toString());
} // if
return addedUserEIds;
} // addUsersRealm
/**
* addNewSite is called when the site has enough information to create a new
* site
*
*/
private void addNewSite(ParameterParser params, SessionState state) {
if (getStateSite(state) != null) {
// There is a Site in state already, so use it rather than creating
// a new Site
return;
}
// If cleanState() has removed SiteInfo, get a new instance into state
SiteInfo siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
String id = StringUtil.trimToNull(siteInfo.getSiteId());
if (id == null) {
// get id
id = IdManager.createUuid();
siteInfo.site_id = id;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (state.getAttribute(STATE_MESSAGE) == null) {
try {
Site site = SiteService.addSite(id, siteInfo.site_type);
String title = StringUtil.trimToNull(siteInfo.title);
String description = siteInfo.description;
setAppearance(state, site, siteInfo.iconUrl);
site.setDescription(description);
if (title != null) {
site.setTitle(title);
}
site.setType(siteInfo.site_type);
ResourcePropertiesEdit rp = site.getPropertiesEdit();
site.setShortDescription(siteInfo.short_description);
site.setPubView(siteInfo.include);
site.setJoinable(siteInfo.joinable);
site.setJoinerRole(siteInfo.joinerRole);
site.setPublished(siteInfo.published);
// site contact information
rp.addProperty(PROP_SITE_CONTACT_NAME,
siteInfo.site_contact_name);
rp.addProperty(PROP_SITE_CONTACT_EMAIL,
siteInfo.site_contact_email);
state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId());
// commit newly added site in order to enable related realm
commitSite(site);
} catch (IdUsedException e) {
addAlert(state, rb.getString("java.sitewithid") + " " + id
+ " " + rb.getString("java.exists"));
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("template-index"));
return;
} catch (IdInvalidException e) {
addAlert(state, rb.getString("java.thesiteid") + " " + id + " "
+ rb.getString("java.notvalid"));
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("template-index"));
return;
} catch (PermissionException e) {
addAlert(state, rb.getString("java.permission") + " " + id
+ ".");
state.setAttribute(STATE_TEMPLATE_INDEX, params
.getString("template-index"));
return;
}
}
} // addNewSite
/**
* %%% legacy properties, to be cleaned up
*
*/
private void sitePropertiesIntoState(SessionState state) {
try {
Site site = getStateSite(state);
SiteInfo siteInfo = new SiteInfo();
if (site != null)
{
// set from site attributes
siteInfo.title = site.getTitle();
siteInfo.description = site.getDescription();
siteInfo.iconUrl = site.getIconUrl();
siteInfo.infoUrl = site.getInfoUrl();
siteInfo.joinable = site.isJoinable();
siteInfo.joinerRole = site.getJoinerRole();
siteInfo.published = site.isPublished();
siteInfo.include = site.isPubView();
siteInfo.short_description = site.getShortDescription();
}
siteInfo.additional = "";
state.setAttribute(STATE_SITE_TYPE, siteInfo.site_type);
state.setAttribute(STATE_SITE_INFO, siteInfo);
} catch (Exception e) {
M_log.warn("SiteAction.sitePropertiesIntoState " + e.getMessage());
}
} // sitePropertiesIntoState
/**
* pageMatchesPattern returns true if a SitePage matches a WorkSite Setup
* pattern
*
*/
private boolean pageMatchesPattern(SessionState state, SitePage page) {
List pageToolList = page.getTools();
// if no tools on the page, return false
if (pageToolList == null || pageToolList.size() == 0) {
return false;
}
// for the case where the page has one tool
ToolConfiguration toolConfiguration = (ToolConfiguration) pageToolList
.get(0);
// don't compare tool properties, which may be changed using Options
List toolList = new Vector();
int count = pageToolList.size();
boolean match = false;
// check Worksite Setup Home pattern
if (page.getTitle() != null
&& page.getTitle().equals(rb.getString("java.home"))) {
return true;
} // Home
else if (page.getTitle() != null
&& page.getTitle().equals(rb.getString("java.help"))) {
// if the count of tools on the page doesn't match, return false
if (count != 1) {
return false;
}
// if the page layout doesn't match, return false
if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) {
return false;
}
// if tooId isn't sakai.contactSupport, return false
if (!(toolConfiguration.getTool().getId())
.equals("sakai.contactSupport")) {
return false;
}
return true;
} // Help
else if (page.getTitle() != null && page.getTitle().equals("Chat")) {
// if the count of tools on the page doesn't match, return false
if (count != 1) {
return false;
}
// if the page layout doesn't match, return false
if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) {
return false;
}
// if the tool doesn't match, return false
if (!(toolConfiguration.getTool().getId()).equals("sakai.chat")) {
return false;
}
// if the channel doesn't match value for main channel, return false
String channel = toolConfiguration.getPlacementConfig()
.getProperty("channel");
if (channel == null) {
return false;
}
if (!(channel.equals(NULL_STRING))) {
return false;
}
return true;
} // Chat
else {
// if the count of tools on the page doesn't match, return false
if (count != 1) {
return false;
}
// if the page layout doesn't match, return false
if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) {
return false;
}
toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
if (pageToolList != null || pageToolList.size() != 0) {
// if tool attributes don't match, return false
match = false;
for (ListIterator i = toolList.listIterator(); i.hasNext();) {
MyTool tool = (MyTool) i.next();
if (toolConfiguration.getTitle() != null) {
if (toolConfiguration.getTool() != null
&& toolConfiguration.getTool().getId().indexOf(
tool.getId()) != -1) {
match = true;
}
}
}
if (!match) {
return false;
}
}
} // Others
return true;
} // pageMatchesPattern
/**
* siteToolsIntoState is the replacement for siteToolsIntoState_ Make a list
* of pages and tools that match WorkSite Setup configurations into state
*/
private void siteToolsIntoState(SessionState state) {
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
String wSetupTool = NULL_STRING;
List wSetupPageList = new Vector();
Site site = getStateSite(state);
List pageList = site.getPages();
// Put up tool lists filtered by category
String type = site.getType();
if (type == null) {
if (SiteService.isUserSite(site.getId())) {
type = "myworkspace";
} else if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) {
// for those sites without type, use the tool set for default
// site type
type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE);
}
}
if (type == null) {
M_log.warn(this + ": - unknown STATE_SITE_TYPE");
} else {
state.setAttribute(STATE_SITE_TYPE, type);
}
// set tool registration list
setToolRegistrationList(state, type);
List toolRegList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
// for the selected tools
boolean check_home = false;
Vector idSelected = new Vector();
if (!((pageList == null) || (pageList.size() == 0))) {
for (ListIterator i = pageList.listIterator(); i.hasNext();) {
SitePage page = (SitePage) i.next();
// collect the pages consistent with Worksite Setup patterns
if (pageMatchesPattern(state, page)) {
if (page.getTitle().equals(rb.getString("java.home"))) {
wSetupTool = HOME_TOOL_ID;
check_home = true;
}
else
{
List pageToolList = page.getTools();
wSetupTool = ((ToolConfiguration) pageToolList.get(0)).getTool().getId();
if (isMultipleInstancesAllowed(findOriginalToolId(state, wSetupTool)))
{
String mId = page.getId() + wSetupTool;
idSelected.add(mId);
multipleToolIdTitleMap.put(mId, page.getTitle());
MyTool newTool = new MyTool();
newTool.title = ToolManager.getTool(wSetupTool).getTitle();
newTool.id = mId;
newTool.selected = false;
boolean hasThisMultipleTool = false;
int j = 0;
for (; j < toolRegList.size() && !hasThisMultipleTool; j++) {
MyTool t = (MyTool) toolRegList.get(j);
if (t.getId().equals(wSetupTool)) {
hasThisMultipleTool = true;
newTool.description = t.getDescription();
}
}
if (hasThisMultipleTool) {
toolRegList.add(j - 1, newTool);
} else {
toolRegList.add(newTool);
}
}
else
{
idSelected.add(wSetupTool);
}
}
WorksiteSetupPage wSetupPage = new WorksiteSetupPage();
wSetupPage.pageId = page.getId();
wSetupPage.pageTitle = page.getTitle();
wSetupPage.toolId = wSetupTool;
wSetupPageList.add(wSetupPage);
}
}
}
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(check_home));
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idSelected); // List
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolRegList);
// of
// ToolRegistration
// toolId's
state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST,idSelected); // List of ToolRegistration toolId's
state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME, Boolean.valueOf(check_home));
state.setAttribute(STATE_WORKSITE_SETUP_PAGE_LIST, wSetupPageList);
} // siteToolsIntoState
/**
* reset the state variables used in edit tools mode
*
* @state The SessionState object
*/
private void removeEditToolState(SessionState state) {
state.removeAttribute(STATE_TOOL_HOME_SELECTED);
state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // List
// of
// ToolRegistration
// toolId's
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // List
// of
// ToolRegistration
// toolId's
state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME);
state.removeAttribute(STATE_WORKSITE_SETUP_PAGE_LIST);
state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET);
//state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP);
}
private List orderToolIds(SessionState state, String type, List toolIdList) {
List rv = new Vector();
if (state.getAttribute(STATE_TOOL_HOME_SELECTED) != null
&& ((Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED))
.booleanValue()) {
rv.add(HOME_TOOL_ID);
}
// look for null site type
if (type != null && toolIdList != null) {
Set categories = new HashSet();
categories.add(type);
Set tools = ToolManager.findTools(categories, null);
SortedIterator i = new SortedIterator(tools.iterator(),
new ToolComparator());
for (; i.hasNext();) {
String tool_id = ((Tool) i.next()).getId();
for (ListIterator j = toolIdList.listIterator(); j.hasNext();) {
String toolId = (String) j.next();
if (toolId.indexOf("assignment") != -1
&& toolId.equals(tool_id)
|| toolId.indexOf("assignment") == -1
&& toolId.indexOf(tool_id) != -1) {
rv.add(toolId);
}
}
}
}
return rv;
} // orderToolIds
private void setupFormNamesAndConstants(SessionState state) {
TimeBreakdown timeBreakdown = (TimeService.newTime()).breakdownLocal();
String mycopyright = COPYRIGHT_SYMBOL + " " + timeBreakdown.getYear()
+ ", " + UserDirectoryService.getCurrentUser().getDisplayName()
+ ". All Rights Reserved. ";
state.setAttribute(STATE_MY_COPYRIGHT, mycopyright);
state.setAttribute(STATE_SITE_INSTANCE_ID, null);
state.setAttribute(STATE_INITIALIZED, Boolean.TRUE.toString());
SiteInfo siteInfo = new SiteInfo();
Participant participant = new Participant();
participant.name = NULL_STRING;
participant.uniqname = NULL_STRING;
participant.active = true;
state.setAttribute(STATE_SITE_INFO, siteInfo);
state.setAttribute("form_participantToAdd", participant);
state.setAttribute(FORM_ADDITIONAL, NULL_STRING);
// legacy
state.setAttribute(FORM_HONORIFIC, "0");
state.setAttribute(FORM_REUSE, "0");
state.setAttribute(FORM_RELATED_CLASS, "0");
state.setAttribute(FORM_RELATED_PROJECT, "0");
state.setAttribute(FORM_INSTITUTION, "0");
// sundry form variables
state.setAttribute(FORM_PHONE, "");
state.setAttribute(FORM_EMAIL, "");
state.setAttribute(FORM_SUBJECT, "");
state.setAttribute(FORM_DESCRIPTION, "");
state.setAttribute(FORM_TITLE, "");
state.setAttribute(FORM_NAME, "");
state.setAttribute(FORM_SHORT_DESCRIPTION, "");
} // setupFormNamesAndConstants
/**
* setupSkins
*
*/
private void setupIcons(SessionState state) {
List icons = new Vector();
String[] iconNames = null;
String[] iconUrls = null;
String[] iconSkins = null;
// get icon information
if (ServerConfigurationService.getStrings("iconNames") != null) {
iconNames = ServerConfigurationService.getStrings("iconNames");
}
if (ServerConfigurationService.getStrings("iconUrls") != null) {
iconUrls = ServerConfigurationService.getStrings("iconUrls");
}
if (ServerConfigurationService.getStrings("iconSkins") != null) {
iconSkins = ServerConfigurationService.getStrings("iconSkins");
}
if ((iconNames != null) && (iconUrls != null) && (iconSkins != null)
&& (iconNames.length == iconUrls.length)
&& (iconNames.length == iconSkins.length)) {
for (int i = 0; i < iconNames.length; i++) {
MyIcon s = new MyIcon(StringUtil.trimToNull((String) iconNames[i]),
StringUtil.trimToNull((String) iconUrls[i]), StringUtil
.trimToNull((String) iconSkins[i]));
icons.add(s);
}
}
state.setAttribute(STATE_ICONS, icons);
}
private void setAppearance(SessionState state, Site edit, String iconUrl) {
// set the icon
edit.setIconUrl(iconUrl);
if (iconUrl == null) {
// this is the default case - no icon, no (default) skin
edit.setSkin(null);
return;
}
// if this icon is in the config appearance list, find a skin to set
List icons = (List) state.getAttribute(STATE_ICONS);
for (Iterator i = icons.iterator(); i.hasNext();) {
Object icon = (Object) i.next();
if (icon instanceof MyIcon && !StringUtil.different(((MyIcon) icon).getUrl(), iconUrl)) {
edit.setSkin(((MyIcon) icon).getSkin());
return;
}
}
}
/**
* A dispatch funtion when selecting course features
*/
public void doAdd_features(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
String option = params.getString("option");
// to reset the state variable of the multiple tool instances
Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET):new HashSet();
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
// dispatch
if (option.startsWith("add_")) {
// this could be format of originalToolId plus number of multiplication
String addToolId = option.substring("add_".length(), option.length());
// find the original tool id
String originToolId = findOriginalToolId(state, addToolId);
if (originToolId != null)
{
Tool tool = ToolManager.getTool(originToolId);
if (tool != null)
{
updateSelectedToolList(state, params, false);
insertTool(state, originToolId, tool.getTitle(), tool.getDescription(), Integer.parseInt(params.getString("num_"+ addToolId)));
state.setAttribute(STATE_TEMPLATE_INDEX, "26");
}
}
} else if (option.equalsIgnoreCase("import")) {
// import or not
updateSelectedToolList(state, params, false);
String importSites = params.getString("import");
if (importSites != null
&& importSites.equalsIgnoreCase(Boolean.TRUE.toString())) {
state.setAttribute(STATE_IMPORT, Boolean.TRUE);
if (importSites.equalsIgnoreCase(Boolean.TRUE.toString())) {
state.removeAttribute(STATE_IMPORT);
state.removeAttribute(STATE_IMPORT_SITES);
state.removeAttribute(STATE_IMPORT_SITE_TOOL);
}
} else {
state.removeAttribute(STATE_IMPORT);
}
} else if (option.equalsIgnoreCase("continue")) {
// continue
updateSelectedToolList(state, params, false);
doContinue(data);
} else if (option.equalsIgnoreCase("back")) {
// back
doBack(data);
} else if (option.equalsIgnoreCase("cancel")) {
// cancel
doCancel_create(data);
}
} // doAdd_features
/**
* update the selected tool list
*
* @param params
* The ParameterParser object
* @param verifyData
* Need to verify input data or not
*/
private void updateSelectedToolList(SessionState state,
ParameterParser params, boolean verifyData) {
List selectedTools = new ArrayList(Arrays.asList(params
.getStrings("selectedTools")));
Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET);
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
boolean has_home = false;
String emailId = null;
for (int i = 0; i < selectedTools.size(); i++)
{
String id = (String) selectedTools.get(i);
if (id.equalsIgnoreCase(HOME_TOOL_ID)) {
has_home = true;
}
else if (findOriginalToolId(state, id) != null)
{
String title = StringUtil.trimToNull(params
.getString("title_" + id));
if (title != null)
{
// save the titles entered
multipleToolIdTitleMap.put(id, title);
}
} else if (id.equalsIgnoreCase("sakai.mailbox")) {
// if Email archive tool is selected, check the email alias
emailId = StringUtil.trimToNull(params.getString("emailId"));
if (verifyData) {
if (emailId == null) {
addAlert(state, rb.getString("java.emailarchive") + " ");
} else {
if (!Validator.checkEmailLocal(emailId)) {
addAlert(state, rb.getString("java.theemail"));
} else {
// check to see whether the alias has been used by
// other sites
try {
String target = AliasService.getTarget(emailId);
if (target != null) {
if (state
.getAttribute(STATE_SITE_INSTANCE_ID) != null) {
String siteId = (String) state
.getAttribute(STATE_SITE_INSTANCE_ID);
String channelReference = mailArchiveChannelReference(siteId);
if (!target.equals(channelReference)) {
// the email alias is not used by
// current site
addAlert(state, rb.getString("java.emailinuse") + " ");
}
} else {
addAlert(state, rb.getString("java.emailinuse") + " ");
}
}
} catch (IdUnusedException ee) {
}
}
}
}
}
}
// update the state objects
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(has_home));
state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, emailId);
} // updateSelectedToolList
/**
* find the tool in the tool list and insert another tool instance to the list
* @param state
* @param toolId
* @param defaultTitle
* @param defaultDescription
* @param insertTimes
*/
private void insertTool(SessionState state, String toolId, String defaultTitle, String defaultDescription, int insertTimes) {
// the list of available tools
List toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST);
List oTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null? new Vector():(List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
// get the map of titles of multiple tool instances
Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap();
int toolListedTimes = 0;
int index = 0;
int insertIndex = 0;
while (index < toolList.size()) {
MyTool tListed = (MyTool) toolList.get(index);
if (tListed.getId().indexOf(toolId) != -1 && !oTools.contains(tListed.getId())) {
toolListedTimes++;
}
if (toolListedTimes > 0 && insertIndex == 0) {
// update the insert index
insertIndex = index;
}
index++;
}
List toolSelected = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
// insert multiple tools
for (int i = 0; i < insertTimes; i++) {
toolSelected.add(toolId + toolListedTimes);
// We need to insert a specific tool entry only if all the specific
// tool entries have been selected
MyTool newTool = new MyTool();
newTool.title = defaultTitle;
newTool.id = toolId + toolListedTimes;
newTool.description = defaultDescription;
toolList.add(insertIndex, newTool);
toolListedTimes++;
// add title
multipleToolIdTitleMap.put(newTool.id, defaultTitle);
}
state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolList);
state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolSelected);
} // insertTool
/**
*
* set selected participant role Hashtable
*/
private void setSelectedParticipantRoles(SessionState state) {
List selectedUserIds = (List) state
.getAttribute(STATE_SELECTED_USER_LIST);
List participantList = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST));
List selectedParticipantList = new Vector();
Hashtable selectedParticipantRoles = new Hashtable();
if (!selectedUserIds.isEmpty() && participantList != null) {
for (int i = 0; i < participantList.size(); i++) {
String id = "";
Object o = (Object) participantList.get(i);
if (o.getClass().equals(Participant.class)) {
// get participant roles
id = ((Participant) o).getUniqname();
selectedParticipantRoles.put(id, ((Participant) o)
.getRole());
}
if (selectedUserIds.contains(id)) {
selectedParticipantList.add(participantList.get(i));
}
}
}
state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES,
selectedParticipantRoles);
state
.setAttribute(STATE_SELECTED_PARTICIPANTS,
selectedParticipantList);
} // setSelectedParticipantRol3es
/**
* the SiteComparator class
*/
private class SiteComparator implements Comparator {
Collator collator = Collator.getInstance();
/**
* the criteria
*/
String m_criterion = null;
String m_asc = null;
/**
* constructor
*
* @param criteria
* The sort criteria string
* @param asc
* The sort order string. TRUE_STRING if ascending; "false"
* otherwise.
*/
public SiteComparator(String criterion, String asc) {
m_criterion = criterion;
m_asc = asc;
} // constructor
/**
* implementing the Comparator compare function
*
* @param o1
* The first object
* @param o2
* The second object
* @return The compare result. 1 is o1 < o2; -1 otherwise
*/
public int compare(Object o1, Object o2) {
int result = -1;
if (m_criterion == null)
m_criterion = SORTED_BY_TITLE;
/** *********** for sorting site list ****************** */
if (m_criterion.equals(SORTED_BY_TITLE)) {
// sorted by the worksite title
String s1 = ((Site) o1).getTitle();
String s2 = ((Site) o2).getTitle();
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_DESCRIPTION)) {
// sorted by the site short description
String s1 = ((Site) o1).getShortDescription();
String s2 = ((Site) o2).getShortDescription();
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_TYPE)) {
// sorted by the site type
String s1 = ((Site) o1).getType();
String s2 = ((Site) o2).getType();
result = compareString(s1, s2);
} else if (m_criterion.equals(SortType.CREATED_BY_ASC.toString())) {
// sorted by the site creator
String s1 = ((Site) o1).getProperties().getProperty(
"CHEF:creator");
String s2 = ((Site) o2).getProperties().getProperty(
"CHEF:creator");
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_STATUS)) {
// sort by the status, published or unpublished
int i1 = ((Site) o1).isPublished() ? 1 : 0;
int i2 = ((Site) o2).isPublished() ? 1 : 0;
if (i1 > i2) {
result = 1;
} else {
result = -1;
}
} else if (m_criterion.equals(SORTED_BY_JOINABLE)) {
// sort by whether the site is joinable or not
boolean b1 = ((Site) o1).isJoinable();
boolean b2 = ((Site) o2).isJoinable();
result = compareBoolean(b1, b2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_NAME)) {
// sort by whether the site is joinable or not
String s1 = null;
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getName();
}
String s2 = null;
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getName();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_UNIQNAME)) {
// sort by whether the site is joinable or not
String s1 = null;
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getUniqname();
}
String s2 = null;
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getUniqname();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_ROLE)) {
String s1 = "";
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getRole();
}
String s2 = "";
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getRole();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_COURSE)) {
// sort by whether the site is joinable or not
String s1 = null;
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getSection();
}
String s2 = null;
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getSection();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_ID)) {
String s1 = null;
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getRegId();
}
String s2 = null;
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getRegId();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_CREDITS)) {
String s1 = null;
if (o1.getClass().equals(Participant.class)) {
s1 = ((Participant) o1).getCredits();
}
String s2 = null;
if (o2.getClass().equals(Participant.class)) {
s2 = ((Participant) o2).getCredits();
}
result = compareString(s1, s2);
} else if (m_criterion.equals(SORTED_BY_PARTICIPANT_STATUS)) {
boolean a1 = true;
if (o1.getClass().equals(Participant.class)) {
a1 = ((Participant) o1).isActive();
}
boolean a2 = true;
if (o2.getClass().equals(Participant.class)) {
a2 = ((Participant) o2).isActive();
}
// let the active users show first when sort ascendingly
result = -compareBoolean(a1, a2);
} else if (m_criterion.equals(SORTED_BY_CREATION_DATE)) {
// sort by the site's creation date
Time t1 = null;
Time t2 = null;
// get the times
try {
t1 = ((Site) o1).getProperties().getTimeProperty(
ResourceProperties.PROP_CREATION_DATE);
} catch (EntityPropertyNotDefinedException e) {
} catch (EntityPropertyTypeException e) {
}
try {
t2 = ((Site) o2).getProperties().getTimeProperty(
ResourceProperties.PROP_CREATION_DATE);
} catch (EntityPropertyNotDefinedException e) {
} catch (EntityPropertyTypeException e) {
}
if (t1 == null) {
result = -1;
} else if (t2 == null) {
result = 1;
} else if (t1.before(t2)) {
result = -1;
} else {
result = 1;
}
} else if (m_criterion.equals(rb.getString("group.title"))) {
// sorted by the group title
String s1 = ((Group) o1).getTitle();
String s2 = ((Group) o2).getTitle();
result = compareString(s1, s2);
} else if (m_criterion.equals(rb.getString("group.number"))) {
// sorted by the group title
int n1 = ((Group) o1).getMembers().size();
int n2 = ((Group) o2).getMembers().size();
result = (n1 > n2) ? 1 : -1;
} else if (m_criterion.equals(SORTED_BY_MEMBER_NAME)) {
// sorted by the member name
String s1 = null;
String s2 = null;
try {
s1 = UserDirectoryService
.getUser(((Member) o1).getUserId()).getSortName();
} catch (Exception ignore) {
}
try {
s2 = UserDirectoryService
.getUser(((Member) o2).getUserId()).getSortName();
} catch (Exception ignore) {
}
result = compareString(s1, s2);
}
if (m_asc == null)
m_asc = Boolean.TRUE.toString();
// sort ascending or descending
if (m_asc.equals(Boolean.FALSE.toString())) {
result = -result;
}
return result;
} // compare
private int compareBoolean(boolean b1, boolean b2) {
int result;
if (b1 == b2) {
result = 0;
} else if (b1 == true) {
result = 1;
} else {
result = -1;
}
return result;
}
private int compareString(String s1, String s2) {
int result;
if (s1 == null && s2 == null) {
result = 0;
} else if (s2 == null) {
result = 1;
} else if (s1 == null) {
result = -1;
} else {
result = collator.compare(s1, s2);
}
return result;
}
} // SiteComparator
private class ToolComparator implements Comparator {
/**
* implementing the Comparator compare function
*
* @param o1
* The first object
* @param o2
* The second object
* @return The compare result. 1 is o1 < o2; 0 is o1.equals(o2); -1
* otherwise
*/
public int compare(Object o1, Object o2) {
try {
return ((Tool) o1).getTitle().compareTo(((Tool) o2).getTitle());
} catch (Exception e) {
}
return -1;
} // compare
} // ToolComparator
public class MyIcon {
protected String m_name = null;
protected String m_url = null;
protected String m_skin = null;
public MyIcon(String name, String url, String skin) {
m_name = name;
m_url = url;
m_skin = skin;
}
public String getName() {
return m_name;
}
public String getUrl() {
return m_url;
}
public String getSkin() {
return m_skin;
}
}
// a utility class for working with ToolConfigurations and ToolRegistrations
// %%% convert featureList from IdAndText to Tool so getFeatures item.id =
// chosen-feature.id is a direct mapping of data
public class MyTool {
public String id = NULL_STRING;
public String title = NULL_STRING;
public String description = NULL_STRING;
public boolean selected = false;
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public boolean getSelected() {
return selected;
}
}
/*
* WorksiteSetupPage is a utility class for working with site pages
* configured by Worksite Setup
*
*/
public class WorksiteSetupPage {
public String pageId = NULL_STRING;
public String pageTitle = NULL_STRING;
public String toolId = NULL_STRING;
public String getPageId() {
return pageId;
}
public String getPageTitle() {
return pageTitle;
}
public String getToolId() {
return toolId;
}
} // WorksiteSetupPage
/**
* Participant in site access roles
*
*/
public class Participant {
public String name = NULL_STRING;
// Note: uniqname is really a user ID
public String uniqname = NULL_STRING;
public String role = NULL_STRING;
/** role from provider */
public String providerRole = NULL_STRING;
/** The member credits */
protected String credits = NULL_STRING;
/** The section */
public String section = NULL_STRING;
private Set sectionEidList;
/** The regestration id */
public String regId = NULL_STRING;
/** removeable if not from provider */
public boolean removeable = true;
/** the status, active vs. inactive */
public boolean active = true;
public String getName() {
return name;
}
public String getUniqname() {
return uniqname;
}
public String getRole() {
return role;
} // cast to Role
public String getProviderRole() {
return providerRole;
}
public boolean isRemoveable() {
return removeable;
}
public boolean isActive() {
return active;
}
// extra info from provider
public String getCredits() {
return credits;
} // getCredits
public String getSection() {
if (sectionEidList == null)
return "";
StringBuilder sb = new StringBuilder();
Iterator it = sectionEidList.iterator();
for (int i = 0; i < sectionEidList.size(); i ++) {
String sectionEid = (String)it.next();
if (i < 0)
sb.append(",<br />");
sb.append(sectionEid);
}
return sb.toString();
} // getSection
public Set getSectionEidList() {
if (sectionEidList == null)
sectionEidList = new HashSet();
return sectionEidList;
}
public void addSectionEidToList(String eid) {
if (sectionEidList == null)
sectionEidList = new HashSet();
sectionEidList.add(eid);
}
public String getRegId() {
return regId;
} // getRegId
/**
* Access the user eid, if we can find it - fall back to the id if not.
*
* @return The user eid.
*/
public String getEid() {
try {
return UserDirectoryService.getUserEid(uniqname);
} catch (UserNotDefinedException e) {
return uniqname;
}
}
/**
* Access the user display id, if we can find it - fall back to the id
* if not.
*
* @return The user display id.
*/
public String getDisplayId() {
try {
User user = UserDirectoryService.getUser(uniqname);
return user.getDisplayId();
} catch (UserNotDefinedException e) {
return uniqname;
}
}
} // Participant
public class SiteInfo {
public String site_id = NULL_STRING; // getId of Resource
public String external_id = NULL_STRING; // if matches site_id
// connects site with U-M
// course information
public String site_type = "";
public String iconUrl = NULL_STRING;
public String infoUrl = NULL_STRING;
public boolean joinable = false;
public String joinerRole = NULL_STRING;
public String title = NULL_STRING; // the short name of the site
public String short_description = NULL_STRING; // the short (20 char)
// description of the
// site
public String description = NULL_STRING; // the longer description of
// the site
public String additional = NULL_STRING; // additional information on
// crosslists, etc.
public boolean published = false;
public boolean include = true; // include the site in the Sites index;
// default is true.
public String site_contact_name = NULL_STRING; // site contact name
public String site_contact_email = NULL_STRING; // site contact email
public String getSiteId() {
return site_id;
}
public String getSiteType() {
return site_type;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getIconUrl() {
return iconUrl;
}
public String getInfoUrll() {
return infoUrl;
}
public boolean getJoinable() {
return joinable;
}
public String getJoinerRole() {
return joinerRole;
}
public String getAdditional() {
return additional;
}
public boolean getPublished() {
return published;
}
public boolean getInclude() {
return include;
}
public String getSiteContactName() {
return site_contact_name;
}
public String getSiteContactEmail() {
return site_contact_email;
}
} // SiteInfo
// dissertation tool related
/**
* doFinish_grad_tools is called when creation of a Grad Tools site is
* confirmed
*/
public void doFinish_grad_tools(RunData data) {
SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
ParameterParser params = data.getParameters();
// set up for the coming template
state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("continue"));
int index = Integer.valueOf(params.getString("template-index"))
.intValue();
actionForTemplate("continue", index, params, state);
// add the pre-configured Grad Tools tools to a new site
addGradToolsFeatures(state);
// TODO: hard coding this frame id is fragile, portal dependent, and
// needs to be fixed -ggolden
// schedulePeerFrameRefresh("sitenav");
scheduleTopRefresh();
resetPaging(state);
}// doFinish_grad_tools
/**
* addGradToolsFeatures adds features to a new Grad Tools student site
*
*/
private void addGradToolsFeatures(SessionState state) {
Site edit = null;
Site template = null;
// get a unique id
String id = IdManager.createUuid();
// get the Grad Tools student site template
try {
template = SiteService.getSite(SITE_GTS_TEMPLATE);
} catch (Exception e) {
if (Log.isWarnEnabled())
M_log.warn("addGradToolsFeatures template " + e);
}
if (template != null) {
// create a new site based on the template
try {
edit = SiteService.addSite(id, template);
} catch (Exception e) {
if (Log.isWarnEnabled())
M_log.warn("addGradToolsFeatures add/edit site " + e);
}
// set the tab, etc.
if (edit != null) {
SiteInfo siteInfo = (SiteInfo) state
.getAttribute(STATE_SITE_INFO);
edit.setShortDescription(siteInfo.short_description);
edit.setTitle(siteInfo.title);
edit.setPublished(true);
edit.setPubView(false);
edit.setType(SITE_TYPE_GRADTOOLS_STUDENT);
// ResourcePropertiesEdit rpe = edit.getPropertiesEdit();
try {
SiteService.save(edit);
} catch (Exception e) {
if (Log.isWarnEnabled())
M_log.warn("addGradToolsFeartures commitEdit " + e);
}
// now that the site and realm exist, we can set the email alias
// set the GradToolsStudent site alias as:
// gradtools-uniqname@servername
String alias = "gradtools-"
+ SessionManager.getCurrentSessionUserId();
String channelReference = mailArchiveChannelReference(id);
try {
AliasService.setAlias(alias, channelReference);
} catch (IdUsedException ee) {
addAlert(state, rb.getString("java.alias") + " " + alias
+ " " + rb.getString("java.exists"));
} catch (IdInvalidException ee) {
addAlert(state, rb.getString("java.alias") + " " + alias
+ " " + rb.getString("java.isinval"));
} catch (PermissionException ee) {
M_log.warn(SessionManager.getCurrentSessionUserId()
+ " does not have permission to add alias. ");
}
}
}
} // addGradToolsFeatures
/**
* handle with add site options
*
*/
public void doAdd_site_option(RunData data) {
String option = data.getParameters().getString("option");
if (option.equals("finish")) {
doFinish(data);
} else if (option.equals("cancel")) {
doCancel_create(data);
} else if (option.equals("back")) {
doBack(data);
}
} // doAdd_site_option
/**
* handle with duplicate site options
*
*/
public void doDuplicate_site_option(RunData data) {
String option = data.getParameters().getString("option");
if (option.equals("duplicate")) {
doContinue(data);
} else if (option.equals("cancel")) {
doCancel(data);
} else if (option.equals("finish")) {
doContinue(data);
}
} // doDuplicate_site_option
/**
* Special check against the Dissertation service, which might not be
* here...
*
* @return
*/
protected boolean isGradToolsCandidate(String userId) {
// DissertationService.isCandidate(userId) - but the hard way
Object service = ComponentManager
.get("org.sakaiproject.api.app.dissertation.DissertationService");
if (service == null)
return false;
// the method signature
Class[] signature = new Class[1];
signature[0] = String.class;
// the method name
String methodName = "isCandidate";
// find a method of this class with this name and signature
try {
Method method = service.getClass().getMethod(methodName, signature);
// the parameters
Object[] args = new Object[1];
args[0] = userId;
// make the call
Boolean rv = (Boolean) method.invoke(service, args);
return rv.booleanValue();
} catch (Throwable t) {
}
return false;
}
/**
* User has a Grad Tools student site
*
* @return
*/
protected boolean hasGradToolsStudentSite(String userId) {
boolean has = false;
int n = 0;
try {
n = SiteService.countSites(
org.sakaiproject.site.api.SiteService.SelectionType.UPDATE,
SITE_TYPE_GRADTOOLS_STUDENT, null, null);
if (n > 0)
has = true;
} catch (Exception e) {
if (Log.isWarnEnabled())
M_log.warn("hasGradToolsStudentSite " + e);
}
return has;
}// hasGradToolsStudentSite
/**
* Get the mail archive channel reference for the main container placement
* for this site.
*
* @param siteId
* The site id.
* @return The mail archive channel reference for this site.
*/
protected String mailArchiveChannelReference(String siteId) {
Object m = ComponentManager
.get("org.sakaiproject.mailarchive.api.MailArchiveService");
if (m != null) {
return "/mailarchive"+Entity.SEPARATOR+"channel"+Entity.SEPARATOR+siteId+Entity.SEPARATOR+SiteService.MAIN_CONTAINER;
} else {
return "";
}
}
/**
* Transfer a copy of all entites from another context for any entity
* producer that claims this tool id.
*
* @param toolId
* The tool id.
* @param fromContext
* The context to import from.
* @param toContext
* The context to import into.
*/
protected void transferCopyEntities(String toolId, String fromContext,
String toContext) {
// TODO: used to offer to resources first - why? still needed? -ggolden
// offer to all EntityProducers
for (Iterator i = EntityManager.getEntityProducers().iterator(); i
.hasNext();) {
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer) {
try {
EntityTransferrer et = (EntityTransferrer) ep;
// if this producer claims this tool id
if (ArrayUtil.contains(et.myToolIds(), toolId)) {
et.transferCopyEntities(fromContext, toContext,
new Vector());
}
} catch (Throwable t) {
M_log.warn(
"Error encountered while asking EntityTransfer to transferCopyEntities from: "
+ fromContext + " to: " + toContext, t);
}
}
}
}
/**
* @return Get a list of all tools that support the import (transfer copy)
* option
*/
protected Set importTools() {
HashSet rv = new HashSet();
// offer to all EntityProducers
for (Iterator i = EntityManager.getEntityProducers().iterator(); i
.hasNext();) {
EntityProducer ep = (EntityProducer) i.next();
if (ep instanceof EntityTransferrer) {
EntityTransferrer et = (EntityTransferrer) ep;
String[] tools = et.myToolIds();
if (tools != null) {
for (int t = 0; t < tools.length; t++) {
rv.add(tools[t]);
}
}
}
}
return rv;
}
/**
* @param state
* @return Get a list of all tools that should be included as options for
* import
*/
protected List getToolsAvailableForImport(SessionState state) {
// The Web Content and News tools do not follow the standard rules for
// import
// Even if the current site does not contain the tool, News and WC will
// be
// an option if the imported site contains it
boolean displayWebContent = false;
boolean displayNews = false;
Set importSites = ((Hashtable) state.getAttribute(STATE_IMPORT_SITES))
.keySet();
Iterator sitesIter = importSites.iterator();
while (sitesIter.hasNext()) {
Site site = (Site) sitesIter.next();
if (site.getToolForCommonId("sakai.iframe") != null)
displayWebContent = true;
if (site.getToolForCommonId("sakai.news") != null)
displayNews = true;
}
List toolsOnImportList = (List) state
.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST);
if (displayWebContent && !toolsOnImportList.contains("sakai.iframe"))
toolsOnImportList.add("sakai.iframe");
if (displayNews && !toolsOnImportList.contains("sakai.news"))
toolsOnImportList.add("sakai.news");
return toolsOnImportList;
} // getToolsAvailableForImport
private void setTermListForContext(Context context, SessionState state,
boolean upcomingOnly) {
List terms;
if (upcomingOnly) {
terms = cms != null?cms.getCurrentAcademicSessions():null;
} else { // get all
terms = cms != null?cms.getAcademicSessions():null;
}
if (terms != null && terms.size() > 0) {
context.put("termList", terms);
}
} // setTermListForContext
private void setSelectedTermForContext(Context context, SessionState state,
String stateAttribute) {
if (state.getAttribute(stateAttribute) != null) {
context.put("selectedTerm", state.getAttribute(stateAttribute));
}
} // setSelectedTermForContext
/**
* rewrote for 2.4
*
* @param userId
* @param academicSessionEid
* @param courseOfferingHash
* @param sectionHash
*/
private void prepareCourseAndSectionMap(String userId,
String academicSessionEid, HashMap courseOfferingHash,
HashMap sectionHash) {
// looking for list of courseOffering and sections that should be
// included in
// the selection list. The course offering must be offered
// 1. in the specific academic Session
// 2. that the specified user has right to attach its section to a
// course site
// map = (section.eid, sakai rolename)
if (groupProvider == null)
{
M_log.warn("Group provider not found");
return;
}
Map map = groupProvider.getGroupRolesForUser(userId);
if (map == null)
return;
Set keys = map.keySet();
Set roleSet = getRolesAllowedToAttachSection();
for (Iterator i = keys.iterator(); i.hasNext();) {
String sectionEid = (String) i.next();
String role = (String) map.get(sectionEid);
if (includeRole(role, roleSet)) {
Section section = null;
getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section);
}
}
// now consider those user with affiliated sections
List affiliatedSectionEids = affiliatedSectionProvider.getAffiliatedSectionEids(userId, academicSessionEid);
if (affiliatedSectionEids != null)
{
for (int k = 0; k < affiliatedSectionEids.size(); k++) {
String sectionEid = (String) affiliatedSectionEids.get(k);
Section section = null;
getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section);
}
}
} // prepareCourseAndSectionMap
private void getCourseOfferingAndSectionMap(String academicSessionEid, HashMap courseOfferingHash, HashMap sectionHash, String sectionEid, Section section) {
try {
section = cms.getSection(sectionEid);
} catch (IdNotFoundException e) {
M_log.warn(e.getMessage());
}
if (section != null) {
String courseOfferingEid = section.getCourseOfferingEid();
CourseOffering courseOffering = cms
.getCourseOffering(courseOfferingEid);
String sessionEid = courseOffering.getAcademicSession()
.getEid();
if (academicSessionEid.equals(sessionEid)) {
// a long way to the conclusion that yes, this course
// offering
// should be included in the selected list. Sigh...
// -daisyf
ArrayList sectionList = (ArrayList) sectionHash
.get(courseOffering.getEid());
if (sectionList == null) {
sectionList = new ArrayList();
}
sectionList.add(new SectionObject(section));
sectionHash.put(courseOffering.getEid(), sectionList);
courseOfferingHash.put(courseOffering.getEid(),
courseOffering);
}
}
}
/**
* for 2.4
*
* @param role
* @return
*/
private boolean includeRole(String role, Set roleSet) {
boolean includeRole = false;
for (Iterator i = roleSet.iterator(); i.hasNext();) {
String r = (String) i.next();
if (r.equals(role)) {
includeRole = true;
break;
}
}
return includeRole;
} // includeRole
protected Set getRolesAllowedToAttachSection() {
// Use !site.template.[site_type]
String azgId = "!site.template.course";
AuthzGroup azgTemplate;
try {
azgTemplate = AuthzGroupService.getAuthzGroup(azgId);
} catch (GroupNotDefinedException e) {
M_log.warn("Could not find authz group " + azgId);
return new HashSet();
}
Set roles = azgTemplate.getRolesIsAllowed("site.upd");
roles.addAll(azgTemplate.getRolesIsAllowed("realm.upd"));
return roles;
} // getRolesAllowedToAttachSection
/**
* Here, we will preapre two HashMap: 1. courseOfferingHash stores
* courseOfferingId and CourseOffering 2. sectionHash stores
* courseOfferingId and a list of its Section We sorted the CourseOffering
* by its eid & title and went through them one at a time to construct the
* CourseObject that is used for the displayed in velocity. Each
* CourseObject will contains a list of CourseOfferingObject(again used for
* vm display). Usually, a CourseObject would only contain one
* CourseOfferingObject. A CourseObject containing multiple
* CourseOfferingObject implies that this is a cross-listing situation.
*
* @param userId
* @param academicSessionEid
* @return
*/
private List prepareCourseAndSectionListing(String userId,
String academicSessionEid, SessionState state) {
// courseOfferingHash = (courseOfferingEid, vourseOffering)
// sectionHash = (courseOfferingEid, list of sections)
HashMap courseOfferingHash = new HashMap();
HashMap sectionHash = new HashMap();
prepareCourseAndSectionMap(userId, academicSessionEid,
courseOfferingHash, sectionHash);
// courseOfferingHash & sectionHash should now be filled with stuffs
// put section list in state for later use
state.setAttribute(STATE_PROVIDER_SECTION_LIST,
getSectionList(sectionHash));
ArrayList offeringList = new ArrayList();
Set keys = courseOfferingHash.keySet();
for (Iterator i = keys.iterator(); i.hasNext();) {
CourseOffering o = (CourseOffering) courseOfferingHash
.get((String) i.next());
offeringList.add(o);
}
Collection offeringListSorted = sortOffering(offeringList);
ArrayList resultedList = new ArrayList();
// use this to keep track of courseOffering that we have dealt with
// already
// this is important 'cos cross-listed offering is dealt with together
// with its
// equivalents
ArrayList dealtWith = new ArrayList();
for (Iterator j = offeringListSorted.iterator(); j.hasNext();) {
CourseOffering o = (CourseOffering) j.next();
if (!dealtWith.contains(o.getEid())) {
// 1. construct list of CourseOfferingObject for CourseObject
ArrayList l = new ArrayList();
CourseOfferingObject coo = new CourseOfferingObject(o,
(ArrayList) sectionHash.get(o.getEid()));
l.add(coo);
// 2. check if course offering is cross-listed
Set set = cms.getEquivalentCourseOfferings(o.getEid());
if (set != null)
{
for (Iterator k = set.iterator(); k.hasNext();) {
CourseOffering eo = (CourseOffering) k.next();
if (courseOfferingHash.containsKey(eo.getEid())) {
// => cross-listed, then list them together
CourseOfferingObject coo_equivalent = new CourseOfferingObject(
eo, (ArrayList) sectionHash.get(eo.getEid()));
l.add(coo_equivalent);
dealtWith.add(eo.getEid());
}
}
}
CourseObject co = new CourseObject(o, l);
dealtWith.add(o.getEid());
resultedList.add(co);
}
}
return resultedList;
} // prepareCourseAndSectionListing
/**
* Sort CourseOffering by order of eid, title uisng velocity SortTool
*
* @param offeringList
* @return
*/
private Collection sortOffering(ArrayList offeringList) {
return sortCmObject(offeringList);
/*
* List propsList = new ArrayList(); propsList.add("eid");
* propsList.add("title"); SortTool sort = new SortTool(); return
* sort.sort(offeringList, propsList);
*/
} // sortOffering
/**
* sort any Cm object such as CourseOffering, CourseOfferingObject,
* SectionObject provided object has getter & setter for eid & title
*
* @param list
* @return
*/
private Collection sortCmObject(List list) {
if (list != null) {
List propsList = new ArrayList();
propsList.add("eid");
propsList.add("title");
SortTool sort = new SortTool();
return sort.sort(list, propsList);
} else {
return list;
}
} // sortCmObject
/**
* this object is used for displaying purposes in chef_site-newSiteCourse.vm
*/
public class SectionObject {
public Section section;
public String eid;
public String title;
public String category;
public String categoryDescription;
public boolean isLecture;
public boolean attached;
public String authorizer;
public SectionObject(Section section) {
this.section = section;
this.eid = section.getEid();
this.title = section.getTitle();
this.category = section.getCategory();
this.categoryDescription = cms
.getSectionCategoryDescription(section.getCategory());
if ("01.lct".equals(section.getCategory())) {
this.isLecture = true;
} else {
this.isLecture = false;
}
Set set = authzGroupService.getAuthzGroupIds(section.getEid());
if (set != null && !set.isEmpty()) {
this.attached = true;
} else {
this.attached = false;
}
}
public Section getSection() {
return section;
}
public String getEid() {
return eid;
}
public String getTitle() {
return title;
}
public String getCategory() {
return category;
}
public String getCategoryDescription() {
return categoryDescription;
}
public boolean getIsLecture() {
return isLecture;
}
public boolean getAttached() {
return attached;
}
public String getAuthorizer() {
return authorizer;
}
public void setAuthorizer(String authorizer) {
this.authorizer = authorizer;
}
} // SectionObject constructor
/**
* this object is used for displaying purposes in chef_site-newSiteCourse.vm
*/
public class CourseObject {
public String eid;
public String title;
public List courseOfferingObjects;
public CourseObject(CourseOffering offering, List courseOfferingObjects) {
this.eid = offering.getEid();
this.title = offering.getTitle();
this.courseOfferingObjects = courseOfferingObjects;
}
public String getEid() {
return eid;
}
public String getTitle() {
return title;
}
public List getCourseOfferingObjects() {
return courseOfferingObjects;
}
} // CourseObject constructor
/**
* this object is used for displaying purposes in chef_site-newSiteCourse.vm
*/
public class CourseOfferingObject {
public String eid;
public String title;
public List sections;
public CourseOfferingObject(CourseOffering offering,
List unsortedSections) {
List propsList = new ArrayList();
propsList.add("category");
propsList.add("eid");
SortTool sort = new SortTool();
this.sections = new ArrayList();
if (unsortedSections != null) {
this.sections = (List) sort.sort(unsortedSections, propsList);
}
this.eid = offering.getEid();
this.title = offering.getTitle();
}
public String getEid() {
return eid;
}
public String getTitle() {
return title;
}
public List getSections() {
return sections;
}
} // CourseOfferingObject constructor
/**
* get campus user directory for dispaly in chef_newSiteCourse.vm
*
* @return
*/
private String getCampusDirectory() {
return ServerConfigurationService.getString(
"site-manage.campusUserDirectory", null);
} // getCampusDirectory
private void removeAnyFlagedSection(SessionState state,
ParameterParser params) {
List all = new ArrayList();
List providerCourseList = (List) state
.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
if (providerCourseList != null && providerCourseList.size() > 0) {
all.addAll(providerCourseList);
}
List manualCourseList = (List) state
.getAttribute(SITE_MANUAL_COURSE_LIST);
if (manualCourseList != null && manualCourseList.size() > 0) {
all.addAll(manualCourseList);
}
for (int i = 0; i < all.size(); i++) {
String eid = (String) all.get(i);
String field = "removeSection" + eid;
String toRemove = params.getString(field);
if ("true".equals(toRemove)) {
// eid is in either providerCourseList or manualCourseList
// either way, just remove it
if (providerCourseList != null)
providerCourseList.remove(eid);
if (manualCourseList != null)
manualCourseList.remove(eid);
}
}
List<SectionObject> requestedCMSections = (List<SectionObject>) state
.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (requestedCMSections != null) {
for (int i = 0; i < requestedCMSections.size(); i++) {
SectionObject so = (SectionObject) requestedCMSections.get(i);
String field = "removeSection" + so.getEid();
String toRemove = params.getString(field);
if ("true".equals(toRemove)) {
requestedCMSections.remove(so);
}
}
if (requestedCMSections.size() == 0)
state.removeAttribute(STATE_CM_REQUESTED_SECTIONS);
}
List<SectionObject> authorizerSections = (List<SectionObject>) state
.getAttribute(STATE_CM_AUTHORIZER_SECTIONS);
if (authorizerSections != null) {
for (int i = 0; i < authorizerSections.size(); i++) {
SectionObject so = (SectionObject) authorizerSections.get(i);
String field = "removeSection" + so.getEid();
String toRemove = params.getString(field);
if ("true".equals(toRemove)) {
authorizerSections.remove(so);
}
}
if (authorizerSections.size() == 0)
state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS);
}
// if list is empty, set to null. This is important 'cos null is
// the indication that the list is empty in the code. See case 2 on line
// 1081
if (manualCourseList != null && manualCourseList.size() == 0)
manualCourseList = null;
if (providerCourseList != null && providerCourseList.size() == 0)
providerCourseList = null;
}
private void collectNewSiteInfo(SiteInfo siteInfo, SessionState state,
ParameterParser params, List providerChosenList) {
if (state.getAttribute(STATE_MESSAGE) == null) {
siteInfo = new SiteInfo();
if (state.getAttribute(STATE_SITE_INFO) != null) {
siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
}
// site title is the title of the 1st section selected -
// daisyf's note
if (providerChosenList != null && providerChosenList.size() >= 1) {
String title = prepareTitle((List) state
.getAttribute(STATE_PROVIDER_SECTION_LIST),
providerChosenList);
siteInfo.title = title;
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
if (params.getString("manualAdds") != null
&& ("true").equals(params.getString("manualAdds"))) {
// if creating a new site
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(
1));
} else if (params.getString("findCourse") != null
&& ("true").equals(params.getString("findCourse"))) {
state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN,
providerChosenList);
prepFindPage(state);
} else {
// no manual add
state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER);
state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS);
state.removeAttribute(STATE_SITE_QUEST_UNIQNAME);
if (getStateSite(state) != null) {
// if revising a site, go to the confirmation
// page of adding classes
//state.setAttribute(STATE_TEMPLATE_INDEX, "37");
} else {
// if creating a site, go the the site
// information entry page
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
}
}
}
}
/**
* By default, courseManagement is implemented
*
* @return
*/
private boolean courseManagementIsImplemented() {
boolean returnValue = true;
String isImplemented = ServerConfigurationService.getString(
"site-manage.courseManagementSystemImplemented", "true");
if (("false").equals(isImplemented))
returnValue = false;
return returnValue;
}
private List getCMSections(String offeringEid) {
if (offeringEid == null || offeringEid.trim().length() == 0)
return null;
if (cms != null) {
Set sections = cms.getSections(offeringEid);
Collection c = sortCmObject(new ArrayList(sections));
return (List) c;
}
return new ArrayList(0);
}
private List getCMCourseOfferings(String subjectEid, String termID) {
if (subjectEid == null || subjectEid.trim().length() == 0
|| termID == null || termID.trim().length() == 0)
return null;
if (cms != null) {
Set offerings = cms.getCourseOfferingsInCourseSet(subjectEid);// ,
// termID);
ArrayList returnList = new ArrayList();
Iterator coIt = offerings.iterator();
while (coIt.hasNext()) {
CourseOffering co = (CourseOffering) coIt.next();
AcademicSession as = co.getAcademicSession();
if (as != null && as.getEid().equals(termID))
returnList.add(co);
}
Collection c = sortCmObject(returnList);
return (List) c;
}
return new ArrayList(0);
}
private List<String> getCMLevelLabels() {
List<String> rv = new Vector<String>();
Set courseSets = cms.getCourseSets();
String currentLevel = "";
rv = addCategories(rv, courseSets);
// course and section exist in the CourseManagementService
rv.add(rb.getString("cm.level.course"));
rv.add(rb.getString("cm.level.section"));
return rv;
}
/**
* a recursive function to add courseset categories
* @param rv
* @param courseSets
*/
private List<String> addCategories(List<String> rv, Set courseSets) {
if (courseSets != null)
{
for (Iterator i = courseSets.iterator(); i.hasNext();)
{
// get the CourseSet object level
CourseSet cs = (CourseSet) i.next();
String level = cs.getCategory();
if (!rv.contains(level))
{
rv.add(level);
}
try
{
// recursively add child categories
rv = addCategories(rv, cms.getChildCourseSets(cs.getEid()));
}
catch (IdNotFoundException e)
{
// current CourseSet not found
}
}
}
return rv;
}
private void prepFindPage(SessionState state) {
final List cmLevels = getCMLevelLabels(), selections = (List) state
.getAttribute(STATE_CM_LEVEL_SELECTIONS);
int lvlSz = 0;
if (cmLevels == null || (lvlSz = cmLevels.size()) < 1) {
// TODO: no cm levels configured, redirect to manual add
return;
}
if (selections != null && selections.size() == lvlSz) {
Section sect = cms.getSection((String) selections.get(selections
.size() - 1));
SectionObject so = new SectionObject(sect);
state.setAttribute(STATE_CM_SELECTED_SECTION, so);
} else
state.removeAttribute(STATE_CM_SELECTED_SECTION);
state.setAttribute(STATE_CM_LEVELS, cmLevels);
state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections);
// check the configuration setting for choosing next screen
Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean("wsetup.skipCourseSectionSelection", Boolean.FALSE);
if (!skipCourseSectionSelection.booleanValue())
{
// go to the course/section selection page
state.setAttribute(STATE_TEMPLATE_INDEX, "53");
}
else
{
// skip the course/section selection page, go directly into the manually create course page
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
}
}
private void addRequestedSection(SessionState state) {
SectionObject so = (SectionObject) state
.getAttribute(STATE_CM_SELECTED_SECTION);
String uniqueName = (String) state
.getAttribute(STATE_SITE_QUEST_UNIQNAME);
if (so == null)
return;
so.setAuthorizer(uniqueName);
if (getStateSite(state) == null)
{
// creating new site
List<SectionObject> requestedSections = (List<SectionObject>) state.getAttribute(STATE_CM_REQUESTED_SECTIONS);
if (requestedSections == null) {
requestedSections = new ArrayList<SectionObject>();
}
// don't add duplicates
if (!requestedSections.contains(so))
requestedSections.add(so);
// if the title has not yet been set and there is just
// one section, set the title to that section's EID
if (requestedSections.size() == 1) {
SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO);
if (siteInfo == null) {
siteInfo = new SiteInfo();
}
if (siteInfo.title == null || siteInfo.title.trim().length() == 0) {
siteInfo.title = so.getEid();
}
state.setAttribute(STATE_SITE_INFO, siteInfo);
}
state.setAttribute(STATE_CM_REQUESTED_SECTIONS, requestedSections);
state.removeAttribute(STATE_CM_SELECTED_SECTION);
}
else
{
// editing site
state.setAttribute(STATE_CM_SELECTED_SECTION, so);
List<SectionObject> cmSelectedSections = (List<SectionObject>) state.getAttribute(STATE_CM_SELECTED_SECTIONS);
if (cmSelectedSections == null) {
cmSelectedSections = new ArrayList<SectionObject>();
}
// don't add duplicates
if (!cmSelectedSections.contains(so))
cmSelectedSections.add(so);
state.setAttribute(STATE_CM_SELECTED_SECTIONS, cmSelectedSections);
state.removeAttribute(STATE_CM_SELECTED_SECTION);
}
state.removeAttribute(STATE_CM_LEVEL_SELECTIONS);
}
public void doFind_course(RunData data) {
final SessionState state = ((JetspeedRunData) data)
.getPortletSessionState(((JetspeedRunData) data).getJs_peid());
final ParameterParser params = data.getParameters();
final String option = params.get("option");
if (option != null)
{
if ("continue".equals(option))
{
String uniqname = StringUtil.trimToNull(params
.getString("uniqname"));
state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname);
if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null
&& !((Boolean) state
.getAttribute(STATE_FUTURE_TERM_SELECTED))
.booleanValue())
{
// if a future term is selected, do not check authorization
// uniqname
if (uniqname == null)
{
addAlert(state, rb.getString("java.author")
+ " "
+ ServerConfigurationService
.getString("officialAccountName")
+ ". ");
}
else
{
try
{
UserDirectoryService.getUserByEid(uniqname);
addRequestedSection(state);
}
catch (UserNotDefinedException e)
{
addAlert(
state,
rb.getString("java.validAuthor1")
+ " "
+ ServerConfigurationService
.getString("officialAccountName")
+ " "
+ rb.getString("java.validAuthor2"));
}
}
}
else
{
addRequestedSection(state);
}
if (state.getAttribute(STATE_MESSAGE) == null) {
if (getStateSite(state) == null) {
state.setAttribute(STATE_TEMPLATE_INDEX, "2");
} else {
state.setAttribute(STATE_TEMPLATE_INDEX, "44");
}
}
doContinue(data);
return;
} else if ("back".equals(option)) {
doBack(data);
return;
} else if ("cancel".equals(option)) {
if (getStateSite(state) == null)
{
doCancel_create(data);// cancel from new site creation
}
else
{
doCancel(data);// cancel from site info editing
}
return;
} else if (option.equals("add")) {
addRequestedSection(state);
return;
} else if (option.equals("manual")) {
// TODO: send to case 37
state.setAttribute(STATE_TEMPLATE_INDEX, "37");
state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(
1));
return;
} else if (option.equals("remove"))
removeAnyFlagedSection(state, params);
}
final List selections = new ArrayList(3);
int cmLevel = getCMLevelLabels().size();
String deptChanged = params.get("deptChanged");
if ("true".equals(deptChanged)) {
// when dept changes, remove selection on courseOffering and
// courseSection
cmLevel = 1;
}
for (int i = 0; i < cmLevel; i++) {
String val = params.get("idField_" + i);
if (val == null || val.trim().length() < 1) {
break;
}
selections.add(val);
}
state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections);
prepFindPage(state);
}
/**
* return the title of the 1st section in the chosen list that has an
* enrollment set. No discrimination on section category
*
* @param sectionList
* @param chosenList
* @return
*/
private String prepareTitle(List sectionList, List chosenList) {
String title = null;
HashMap map = new HashMap();
for (Iterator i = sectionList.iterator(); i.hasNext();) {
SectionObject o = (SectionObject) i.next();
map.put(o.getEid(), o.getSection());
}
for (int j = 0; j < chosenList.size(); j++) {
String eid = (String) chosenList.get(j);
Section s = (Section) map.get(eid);
// we will always has a title regardless but we prefer it to be the
// 1st section on the chosen list that has an enrollment set
if (j == 0) {
title = s.getTitle();
}
if (s.getEnrollmentSet() != null) {
title = s.getTitle();
break;
}
}
return title;
} // prepareTitle
/**
* return an ArrayList of SectionObject
*
* @param sectionHash
* contains an ArrayList collection of SectionObject
* @return
*/
private ArrayList getSectionList(HashMap sectionHash) {
ArrayList list = new ArrayList();
// values is an ArrayList of section
Collection c = sectionHash.values();
for (Iterator i = c.iterator(); i.hasNext();) {
ArrayList l = (ArrayList) i.next();
list.addAll(l);
}
return list;
}
private String getAuthorizers(SessionState state) {
String authorizers = "";
ArrayList list = (ArrayList) state
.getAttribute(STATE_CM_AUTHORIZER_LIST);
if (list != null) {
for (int i = 0; i < list.size(); i++) {
if (i == 0) {
authorizers = (String) list.get(i);
} else {
authorizers = authorizers + ", " + list.get(i);
}
}
}
return authorizers;
}
private List prepareSectionObject(List sectionList, String userId) {
ArrayList list = new ArrayList();
if (sectionList != null) {
for (int i = 0; i < sectionList.size(); i++) {
String sectionEid = (String) sectionList.get(i);
Section s = cms.getSection(sectionEid);
SectionObject so = new SectionObject(s);
so.setAuthorizer(userId);
list.add(so);
}
}
return list;
}
/**
* change collection object to list object
* @param c
* @return
*/
private List collectionToList(Collection c)
{
List rv = new Vector();
if (c!=null)
{
for (Iterator i = c.iterator(); i.hasNext();)
{
rv.add(i.next());
}
}
return rv;
}
}
| fix to SAK-12948:SiteAction: Nullpointer exception always generated by a specific part of the code and a two other minor issues [Static code review]
git-svn-id: 19a9fd284f7506c72ea2840aac2b5d740703d7e8@41227 66ffb92e-73f9-0310-93c1-f5514f145a0a
| site-manage/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java | fix to SAK-12948:SiteAction: Nullpointer exception always generated by a specific part of the code and a two other minor issues [Static code review] | <ide><path>ite-manage/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java
<ide> .split("\r\n");
<ide>
<ide> for (i = 0; i < officialAccountArray.length; i++) {
<del> String officialAccount = StringUtil
<del> .trimToNull(officialAccountArray[i].replaceAll(
<del> "[\t\r\n]", ""));
<add> String officialAccount = StringUtil.trimToNull(officialAccountArray[i].replaceAll("[\t\r\n]", ""));
<ide> // if there is some text, try to use it
<ide> if (officialAccount != null) {
<ide> // automaticially add nonOfficialAccount account
<ide> // We didn't find anyone via email address, so try getting the user by EID
<ide> if(u == null) {
<ide> u = UserDirectoryService.getUserByEid(officialAccount);
<del> if (u != null)
<del> M_log.info("found user with eid " + officialAccount);
<ide> }
<ide>
<del> if (site != null && site.getUserRole(u.getId()) != null) {
<del> // user already exists in the site, cannot be added
<del> // again
<del> existingUsers.add(officialAccount);
<del> } else {
<del> participant.name = u.getDisplayName();
<del> participant.uniqname = u.getEid();
<del> participant.active = true;
<del> pList.add(participant);
<add> if (u != null)
<add> {
<add> M_log.info("found user with eid " + officialAccount);
<add> if (site != null && site.getUserRole(u.getId()) != null) {
<add> // user already exists in the site, cannot be added
<add> // again
<add> existingUsers.add(officialAccount);
<add> } else {
<add> participant.name = u.getDisplayName();
<add> participant.uniqname = u.getEid();
<add> participant.active = true;
<add> pList.add(participant);
<add> }
<ide> }
<ide> } catch (UserNotDefinedException e) {
<ide> addAlert(state, officialAccount + " " + rb.getString("java.username") + " ");
<ide> if (nonOfficialAccounts != null) {
<ide> String[] nonOfficialAccountArray = nonOfficialAccounts.split("\r\n");
<ide> for (i = 0; i < nonOfficialAccountArray.length; i++) {
<del> String nonOfficialAccount = nonOfficialAccountArray[i];
<del>
<del> // if there is some text, try to use it
<del> nonOfficialAccount.replaceAll("[ \t\r\n]", "");
<del>
<del> // remove the trailing dots and empty space
<del> while (nonOfficialAccount.endsWith(".")
<del> || nonOfficialAccount.endsWith(" ")) {
<add> String nonOfficialAccount = StringUtil.trimToNull(nonOfficialAccountArray[i].replaceAll("[ \t\r\n]", ""));
<add>
<add> // remove the trailing dots
<add> while (nonOfficialAccount != null && nonOfficialAccount.endsWith(".")) {
<ide> nonOfficialAccount = nonOfficialAccount.substring(0,
<ide> nonOfficialAccount.length() - 1);
<ide> }
<ide> false);
<ide>
<ide> // update the not added user list
<del> String notAddedOfficialAccounts = null;
<del> String notAddedNonOfficialAccounts = null;
<add> String notAddedOfficialAccounts = NULL_STRING;
<add> String notAddedNonOfficialAccounts = NULL_STRING;
<ide> for (Iterator iEIds = eIdRoles.keySet().iterator(); iEIds.hasNext();) {
<ide> String iEId = (String) iEIds.next();
<ide> if (!addedParticipantEIds.contains(iEId)) {
<ide> }
<ide>
<ide> if (addedParticipantEIds.size() != 0
<del> && (notAddedOfficialAccounts != null || notAddedNonOfficialAccounts != null)) {
<add> && (!notAddedOfficialAccounts.equals(NULL_STRING) || !notAddedNonOfficialAccounts.equals(NULL_STRING))) {
<ide> // at lease one officialAccount account or an nonOfficialAccount
<ide> // account added, and there are also failures
<ide> addAlert(state, rb.getString("java.allusers"));
<ide> }
<ide>
<del> if (notAddedOfficialAccounts == null
<del> && notAddedNonOfficialAccounts == null) {
<add> if (notAddedOfficialAccounts.equals(NULL_STRING)
<add> && notAddedNonOfficialAccounts.equals(NULL_STRING)) {
<ide> // all account has been added successfully
<ide> removeAddParticipantContext(state);
<ide> } else {
<ide> String userName = user.getDisplayName();
<ide> // send notification email
<ide> if (this.userNotificationProvider == null)
<add> {
<ide> M_log.warn("notification provider is null!");
<del> userNotificationProvider.notifyAddedParticipant(nonOfficialAccount, user, sEdit.getTitle());
<add> }
<add> else
<add> {
<add> userNotificationProvider.notifyAddedParticipant(nonOfficialAccount, user, sEdit.getTitle());
<add> }
<ide>
<ide> }
<ide> } |
|
Java | lgpl-2.1 | d1c79b49ad66ed1aebf3261d717923d8ca8c57e0 | 0 | spotbugs/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,KengoTODA/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,sewe/spotbugs,sewe/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,sewe/spotbugs,johnscancella/spotbugs,sewe/spotbugs | /*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2003, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.detect;
import edu.umd.cs.findbugs.*;
import java.util.*;
import java.io.PrintStream;
import org.apache.bcel.classfile.*;
import java.util.zip.*;
import java.io.*;
import edu.umd.cs.pugh.visitclass.Constants2;
public class InitializationChain extends BytecodeScanningDetector implements Constants2 {
Set<String> requires = new TreeSet<String>();
Map<String, Set<String>> classRequires = new TreeMap<String, Set<String>>();
private BugReporter bugReporter;
private boolean instanceCreated;
private boolean instanceCreatedWarningGiven;
private static final boolean DEBUG = Boolean.getBoolean("ic.debug");
public InitializationChain(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
public void visit(Code obj) {
instanceCreated = false;
instanceCreatedWarningGiven = false;
if (!methodName.equals("<clinit>")) return;
super.visit(obj);
requires.remove(betterClassName);
if (betterClassName.equals("java.lang.System")) {
requires.add("java.io.FileInputStream");
requires.add("java.io.FileOutputStream");
requires.add("java.io.BufferedInputStream");
requires.add("java.io.BufferedOutputStream");
requires.add("java.io.PrintStream");
}
if (!requires.isEmpty()) {
classRequires.put(betterClassName,requires);
requires = new TreeSet<String>();
}
}
public void sawOpcode(int seen) {
if (seen == PUTSTATIC && classConstant.equals(className)) {
if (instanceCreated && !instanceCreatedWarningGiven) {
String okSig = "L" + className + ";";
if (!okSig.equals(sigConstant)) {
System.out.println("Instance created in static initializer before static field " + nameConstant + " assigned");
System.out.println("Class is " + className);
instanceCreatedWarningGiven = true;
}
}
}
else if (seen == NEW && classConstant.equals(className)) {
instanceCreated = true;
}
else if (seen == PUTSTATIC || seen == GETSTATIC || seen == INVOKESTATIC
|| seen == NEW)
if (PC + 6 < codeBytes.length)
requires.add(betterClassConstant);
}
public void compute() {
Set<String> allClasses = classRequires.keySet();
Set<String> emptyClasses = new TreeSet<String>();
for(Iterator i = allClasses.iterator(); i.hasNext(); ) {
String c = (String) i.next();
Set<String> needs = classRequires.get(c);
needs.retainAll(allClasses);
Set<String> extra = new TreeSet<String>();
for(Iterator j = needs.iterator(); j.hasNext(); )
extra.addAll(classRequires.get(j.next()));
needs.addAll(extra);
needs.retainAll(allClasses);
classRequires.put(c,needs);
if (needs.isEmpty()) emptyClasses.add(c);
}
for(Iterator i = emptyClasses.iterator(); i.hasNext(); ) {
String c = (String) i.next();
classRequires.remove(c);
}
}
public void report() {
if (DEBUG) System.out.println("Finishing computation");
compute();
compute();
compute();
compute();
compute();
compute();
compute();
compute();
Set<String> allClasses = classRequires.keySet();
for(Iterator<String> i = allClasses.iterator(); i.hasNext(); ) {
String c = i.next();
if (DEBUG) System.out.println("Class " + c + " requires:");
for(Iterator<String> j = (classRequires.get(c)).iterator();
j.hasNext(); ) {
String needs = j.next();
if (DEBUG) System.out.println(" " + needs);
Set<String> s = classRequires.get(needs);
if (s != null && s.contains(c) && c.compareTo(needs) < 0)
bugReporter.reportBug(new BugInstance("IC_INIT_CIRCULARITY", NORMAL_PRIORITY)
.addClass(c)
.addClass(needs));
}
}
}
}
| findbugs/src/java/edu/umd/cs/findbugs/detect/InitializationChain.java | /*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2003, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.detect;
import edu.umd.cs.findbugs.*;
import java.util.*;
import java.io.PrintStream;
import org.apache.bcel.classfile.*;
import java.util.zip.*;
import java.io.*;
import edu.umd.cs.pugh.visitclass.Constants2;
public class InitializationChain extends BytecodeScanningDetector implements Constants2 {
Set<String> requires = new TreeSet<String>();
Map<String, Set<String>> classRequires = new TreeMap<String, Set<String>>();
private BugReporter bugReporter;
private boolean instanceCreated;
private boolean instanceCreatedWarningGiven;
private static final boolean DEBUG = Boolean.getBoolean("ic.debug");
public InitializationChain(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
public void visit(Code obj) {
instanceCreated = false;
instanceCreatedWarningGiven = false;
if (!methodName.equals("<clinit>")) return;
super.visit(obj);
requires.remove(betterClassName);
if (betterClassName.equals("java.lang.System")) {
requires.add("java.io.FileInputStream");
requires.add("java.io.FileOutputStream");
requires.add("java.io.BufferedInputStream");
requires.add("java.io.BufferedOutputStream");
requires.add("java.io.PrintStream");
}
if (!requires.isEmpty()) {
classRequires.put(betterClassName,requires);
requires = new TreeSet<String>();
}
}
public void sawOpcode(int seen) {
if (seen == PUTSTATIC)
System.out.println("Saw putstatic " + nameConstant);
if (seen == PUTSTATIC && classConstant.equals(className)) {
if (instanceCreated && !instanceCreatedWarningGiven) {
String okSig = "L" + className + ";";
if (!okSig.equals(sigConstant)) {
System.out.println("Instance created in static initializer before static field " + nameConstant + " assigned");
System.out.println("Class is " + className);
instanceCreatedWarningGiven = true;
}
}
}
else if (seen == NEW && classConstant.equals(className)) {
instanceCreated = true;
}
else if (seen == PUTSTATIC || seen == GETSTATIC || seen == INVOKESTATIC
|| seen == NEW)
if (PC + 6 < codeBytes.length)
requires.add(betterClassConstant);
}
public void compute() {
Set<String> allClasses = classRequires.keySet();
Set<String> emptyClasses = new TreeSet<String>();
for(Iterator i = allClasses.iterator(); i.hasNext(); ) {
String c = (String) i.next();
Set<String> needs = classRequires.get(c);
needs.retainAll(allClasses);
Set<String> extra = new TreeSet<String>();
for(Iterator j = needs.iterator(); j.hasNext(); )
extra.addAll(classRequires.get(j.next()));
needs.addAll(extra);
needs.retainAll(allClasses);
classRequires.put(c,needs);
if (needs.isEmpty()) emptyClasses.add(c);
}
for(Iterator i = emptyClasses.iterator(); i.hasNext(); ) {
String c = (String) i.next();
classRequires.remove(c);
}
}
public void report() {
if (DEBUG) System.out.println("Finishing computation");
compute();
compute();
compute();
compute();
compute();
compute();
compute();
compute();
Set<String> allClasses = classRequires.keySet();
for(Iterator<String> i = allClasses.iterator(); i.hasNext(); ) {
String c = i.next();
if (DEBUG) System.out.println("Class " + c + " requires:");
for(Iterator<String> j = (classRequires.get(c)).iterator();
j.hasNext(); ) {
String needs = j.next();
if (DEBUG) System.out.println(" " + needs);
Set<String> s = classRequires.get(needs);
if (s != null && s.contains(c) && c.compareTo(needs) < 0)
bugReporter.reportBug(new BugInstance("IC_INIT_CIRCULARITY", NORMAL_PRIORITY)
.addClass(c)
.addClass(needs));
}
}
}
}
| Removed useless debugging info
git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@906 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
| findbugs/src/java/edu/umd/cs/findbugs/detect/InitializationChain.java | Removed useless debugging info | <ide><path>indbugs/src/java/edu/umd/cs/findbugs/detect/InitializationChain.java
<ide> public void sawOpcode(int seen) {
<ide>
<ide>
<del> if (seen == PUTSTATIC)
<del> System.out.println("Saw putstatic " + nameConstant);
<ide> if (seen == PUTSTATIC && classConstant.equals(className)) {
<ide> if (instanceCreated && !instanceCreatedWarningGiven) {
<ide> String okSig = "L" + className + ";"; |
|
Java | mit | 6e5c441403b722fb3f2758996b9b67c6846a9beb | 0 | DemigodsRPG/Demigods3 | package com.censoredsoftware.Demigods.Episodes.Demo.Deity.Insignian;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.scheduler.BukkitRunnable;
import com.censoredsoftware.Demigods.Engine.Object.Ability.Ability;
import com.censoredsoftware.Demigods.Engine.Object.Ability.AbilityInfo;
import com.censoredsoftware.Demigods.Engine.Object.Ability.Devotion;
import com.censoredsoftware.Demigods.Engine.Object.Deity.Deity;
import com.censoredsoftware.Demigods.Engine.Object.Deity.DeityInfo;
import com.censoredsoftware.Demigods.Engine.Utility.StructureUtility;
import com.censoredsoftware.Demigods.Engine.Utility.UnicodeUtility;
import com.censoredsoftware.Demigods.Engine.Utility.ZoneUtility;
public class OmegaX17 extends Deity
{
private static String name = "OmegaX17", alliance = "Insignian", permission = "demigods.insignian.omega";
private static ChatColor color = ChatColor.BLACK;
private static Set<Material> claimItems = new HashSet<Material>()
{
{
add(Material.TNT);
}
};
private static List<String> lore = new ArrayList<String>()
{
{
add(" ");
add(ChatColor.AQUA + " Demigods > " + ChatColor.RESET + color + name);
add(ChatColor.RESET + "-----------------------------------------------------");
add(ChatColor.YELLOW + " Claim Items:");
for(Material item : claimItems)
{
add(ChatColor.GRAY + " " + UnicodeUtility.rightwardArrow() + " " + ChatColor.WHITE + item.name());
}
add(ChatColor.YELLOW + " Abilities:");
}
};
private static Type type = Type.DEMO;
private static Set<Ability> abilities = new HashSet<Ability>()
{
{
add(new SplosionWalking());
add(new NoSplosion());
}
};
public OmegaX17()
{
super(new DeityInfo(name, alliance, permission, color, claimItems, lore, type), abilities);
}
}
class SplosionWalking extends Ability
{
private static String deity = "OmegaX17", name = "Explosion Walking", command = null, permission = "demigods.insignian.omega";
private static int cost = 0, delay = 0, repeat = 20;
private static AbilityInfo info;
private static List<String> details = new ArrayList<String>()
{
{
add(ChatColor.GRAY + " " + UnicodeUtility.rightwardArrow() + " " + ChatColor.WHITE + "The end of all things.");
}
};
private static Devotion.Type type = Devotion.Type.STEALTH;
protected SplosionWalking()
{
super(info = new AbilityInfo(deity, name, command, permission, cost, delay, repeat, details, type), null, new BukkitRunnable()
{
@Override
public void run()
{
for(Player online : Bukkit.getOnlinePlayers())
{
if(Deity.canUseDeitySilent(online, "OmegaX17") && online.getLocation().getBlock().getRelative(BlockFace.DOWN).getType().isSolid() && !online.isFlying() && !ZoneUtility.zoneNoPVP(online.getLocation()) && !StructureUtility.isTrespassingInNoGriefingZone(online)) doIt(online);
}
}
public void doIt(Player player)
{
player.getWorld().createExplosion(player.getLocation(), 400F, false);
}
});
}
}
class NoSplosion extends Ability
{
private static String deity = "OmegaX17", name = "No Explosion Damage", command = null, permission = "demigods.insignian.omega";
private static int cost = 0, delay = 0, repeat = 0;
private static List<String> details = new ArrayList<String>()
{
{
add(ChatColor.GRAY + " " + UnicodeUtility.rightwardArrow() + " " + ChatColor.WHITE + "Take no damage from explosions.");
}
};
private static Devotion.Type type = Devotion.Type.PASSIVE;
protected NoSplosion()
{
super(new AbilityInfo(deity, name, command, permission, cost, delay, repeat, details, type), new Listener()
{
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityDamange(EntityDamageEvent damageEvent)
{
if(damageEvent.getEntity() instanceof Player)
{
Player player = (Player) damageEvent.getEntity();
if(!Deity.canUseDeitySilent(player, deity)) return;
// If the player receives falling damage, cancel it
if(damageEvent.getCause() == EntityDamageEvent.DamageCause.BLOCK_EXPLOSION || damageEvent.getCause() == EntityDamageEvent.DamageCause.ENTITY_EXPLOSION) damageEvent.setCancelled(true);
}
}
}, null);
}
}
| src/main/java/com/censoredsoftware/Demigods/Episodes/Demo/Deity/Insignian/OmegaX17.java | package com.censoredsoftware.Demigods.Episodes.Demo.Deity.Insignian;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.scheduler.BukkitRunnable;
import com.censoredsoftware.Demigods.Engine.Object.Ability.Ability;
import com.censoredsoftware.Demigods.Engine.Object.Ability.AbilityInfo;
import com.censoredsoftware.Demigods.Engine.Object.Ability.Devotion;
import com.censoredsoftware.Demigods.Engine.Object.Deity.Deity;
import com.censoredsoftware.Demigods.Engine.Object.Deity.DeityInfo;
import com.censoredsoftware.Demigods.Engine.Utility.StructureUtility;
import com.censoredsoftware.Demigods.Engine.Utility.UnicodeUtility;
import com.censoredsoftware.Demigods.Engine.Utility.ZoneUtility;
public class OmegaX17 extends Deity
{
private static String name = "OmegaX17", alliance = "Insignian", permission = "demigods.insignian.omega";
private static ChatColor color = ChatColor.BLACK;
private static Set<Material> claimItems = new HashSet<Material>()
{
{
add(Material.TNT);
}
};
private static List<String> lore = new ArrayList<String>()
{
{
add(" ");
add(ChatColor.AQUA + " Demigods > " + ChatColor.RESET + color + name);
add(ChatColor.RESET + "-----------------------------------------------------");
add(ChatColor.YELLOW + " Claim Items:");
for(Material item : claimItems)
{
add(ChatColor.GRAY + " " + UnicodeUtility.rightwardArrow() + " " + ChatColor.WHITE + item.name());
}
add(ChatColor.YELLOW + " Abilities:");
}
};
private static Type type = Type.DEMO;
private static Set<Ability> abilities = new HashSet<Ability>()
{
{
add(new SplosionWalking());
add(new NoSplosion());
}
};
public OmegaX17()
{
super(new DeityInfo(name, alliance, permission, color, claimItems, lore, type), abilities);
}
}
class SplosionWalking extends Ability
{
private static String deity = "OmegaX17", name = "Explosion Walking", command = null, permission = "demigods.insignian.omega";
private static int cost = 0, delay = 0, repeat = 1;
private static AbilityInfo info;
private static List<String> details = new ArrayList<String>()
{
{
add(ChatColor.GRAY + " " + UnicodeUtility.rightwardArrow() + " " + ChatColor.WHITE + "The end of all things.");
}
};
private static Devotion.Type type = Devotion.Type.STEALTH;
protected SplosionWalking()
{
super(info = new AbilityInfo(deity, name, command, permission, cost, delay, repeat, details, type), null, new BukkitRunnable()
{
@Override
public void run()
{
for(Player online : Bukkit.getOnlinePlayers())
{
if(Deity.canUseDeitySilent(online, "OmegaX17") && online.getLocation().getBlock().getRelative(BlockFace.DOWN).getType().isSolid() && !online.isFlying() && !ZoneUtility.zoneNoPVP(online.getLocation()) && !StructureUtility.isTrespassingInNoGriefingZone(online)) doIt(online);
}
}
public void doIt(Player player)
{
player.getWorld().createExplosion(player.getLocation(), 40F, false);
}
});
}
}
class NoSplosion extends Ability
{
private static String deity = "OmegaX17", name = "No Explosion Damage", command = null, permission = "demigods.insignian.omega";
private static int cost = 0, delay = 0, repeat = 0;
private static List<String> details = new ArrayList<String>()
{
{
add(ChatColor.GRAY + " " + UnicodeUtility.rightwardArrow() + " " + ChatColor.WHITE + "Take no damage from explosions.");
}
};
private static Devotion.Type type = Devotion.Type.PASSIVE;
protected NoSplosion()
{
super(new AbilityInfo(deity, name, command, permission, cost, delay, repeat, details, type), new Listener()
{
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityDamange(EntityDamageEvent damageEvent)
{
if(damageEvent.getEntity() instanceof Player)
{
Player player = (Player) damageEvent.getEntity();
if(!Deity.canUseDeitySilent(player, deity)) return;
// If the player receives falling damage, cancel it
if(damageEvent.getCause() == EntityDamageEvent.DamageCause.BLOCK_EXPLOSION || damageEvent.getCause() == EntityDamageEvent.DamageCause.ENTITY_EXPLOSION) damageEvent.setCancelled(true);
}
}
}, null);
}
}
| The logical conclusion.
| src/main/java/com/censoredsoftware/Demigods/Episodes/Demo/Deity/Insignian/OmegaX17.java | The logical conclusion. | <ide><path>rc/main/java/com/censoredsoftware/Demigods/Episodes/Demo/Deity/Insignian/OmegaX17.java
<ide> class SplosionWalking extends Ability
<ide> {
<ide> private static String deity = "OmegaX17", name = "Explosion Walking", command = null, permission = "demigods.insignian.omega";
<del> private static int cost = 0, delay = 0, repeat = 1;
<add> private static int cost = 0, delay = 0, repeat = 20;
<ide> private static AbilityInfo info;
<ide> private static List<String> details = new ArrayList<String>()
<ide> {
<ide>
<ide> public void doIt(Player player)
<ide> {
<del> player.getWorld().createExplosion(player.getLocation(), 40F, false);
<add> player.getWorld().createExplosion(player.getLocation(), 400F, false);
<ide> }
<ide> });
<ide> } |
|
JavaScript | mit | e3d6d6c3ae34e5e4c5dcd09cee62ae7c1deca545 | 0 | PetrHeinz/gods-play,PetrHeinz/gods-play | const MENU_OFFSET = 10
const MENU_INFO_TEXT_MARGIN = 5
const MENU_INFO_TEXT_WIDTH = 400
export default class MenuInterface {
/**
* @param {PIXI.Container} stage
* @param {Game} game
*/
constructor (stage, game) {
/** @type {PIXI.Container} */
this.stage = stage
/** @type {Game} */
this.game = game
/** @type {PIXI.Text|null} */
this.playerText = null
/** @type {PIXI.Text[]} */
this.statusTexts = []
/** @type {number} */
this.textOffset = 0
}
initialize () {
this.createPlayerText()
this.updatePlayerText(this.game.getPlayerOnTurn())
this.game.events.listen('turnEnded', data => this.updatePlayerText(data.playerOnTurn))
this.game.events.listen('playerGainedMana', data => this.updatePlayerText(data.player))
this.game.events.listen('playerCastedSpell', data => this.updatePlayerText(data.player))
this.game.events.listen('playerRefreshed', data => this.updatePlayerText(data.player))
this.updateGameState(this.game.state)
this.game.events.listen('gameStateChanged', data => this.updateGameState(data.state))
}
createPlayerText () {
this.playerText = new PIXI.Text('', {fill: 0xFFFFFF})
this.playerText.x = MENU_OFFSET
this.playerText.y = MENU_OFFSET
this.stage.addChild(this.playerText)
}
/**
* @param {Player} player
*/
updatePlayerText (player) {
let playerTextLines = [
'On turn: ' + player.name,
'Mana: ' + player.mana,
'Action pts: ' + player.actionPoints
]
this.playerText.text = playerTextLines.join('\n')
}
/**
* @param {State} state
*/
updateGameState (state) {
let self = this
this.statusTexts.forEach(function (text) {
self.stage.removeChild(text)
})
this.statusTexts = []
this.textOffset = MENU_OFFSET + self.playerText.height
this.textOffset += MENU_OFFSET
state.getActions().forEach(action => this.addStateAction(action))
this.textOffset += MENU_OFFSET
state.getInfoTexts().forEach(infoText => this.addStateInfoText(infoText))
}
/**
* @param {Action} action
*/
addStateAction (action) {
let labelText = '▸' + action.label
let text = new PIXI.Text(labelText, {
fill: 0xFFFFFF
})
text.interactive = true
text.on('mouseup', action.callback)
text.x = MENU_OFFSET
text.y = this.textOffset
this.textOffset += text.height
this.statusTexts.push(text)
this.stage.addChild(text)
}
/**
* @param {string} infoText
*/
addStateInfoText (infoText) {
let text = new PIXI.Text(infoText, {
fill: 0xAAAAAA,
wordWrap: true,
wordWrapWidth: MENU_INFO_TEXT_WIDTH
})
text.x = MENU_OFFSET
text.y = this.textOffset
this.textOffset += text.height + MENU_INFO_TEXT_MARGIN
this.statusTexts.push(text)
this.stage.addChild(text)
}
}
| src/Interface/MenuInterface.js | const MENU_OFFSET = 10
const MENU_INFO_TEXT_MARGIN = 5
const MENU_INFO_TEXT_WIDTH = 400
export default class MenuInterface {
/**
* @param {PIXI.Container} stage
* @param {Game} game
*/
constructor (stage, game) {
/** @type {PIXI.Container} */
this.stage = stage
/** @type {Game} */
this.game = game
/** @type {PIXI.Text|null} */
this.playerText = null
/** @type {PIXI.Text[]} */
this.statusTexts = []
}
initialize () {
this.createPlayerText()
this.updatePlayerText(this.game.getPlayerOnTurn())
this.game.events.listen('turnEnded', data => this.updatePlayerText(data.playerOnTurn))
this.game.events.listen('playerGainedMana', data => this.updatePlayerText(data.player))
this.game.events.listen('playerCastedSpell', data => this.updatePlayerText(data.player))
this.game.events.listen('playerRefreshed', data => this.updatePlayerText(data.player))
this.updateGameState(this.game.state)
this.game.events.listen('gameStateChanged', data => this.updateGameState(data.state))
}
createPlayerText () {
this.playerText = new PIXI.Text('', {fill: 0xFFFFFF})
this.playerText.x = MENU_OFFSET
this.playerText.y = MENU_OFFSET
this.stage.addChild(this.playerText)
}
/**
* @param {Player} player
*/
updatePlayerText (player) {
let playerTextLines = [
'On turn: ' + player.name,
'Mana: ' + player.mana,
'Action pts: ' + player.actionPoints
]
this.playerText.text = playerTextLines.join('\n')
}
/**
* @param {State} state
*/
updateGameState (state) {
let self = this
this.statusTexts.forEach(function (text) {
self.stage.removeChild(text)
})
this.statusTexts = []
let textsHeight = MENU_OFFSET + self.playerText.height + MENU_OFFSET
state.getActions().forEach(function (action) {
let text = new PIXI.Text(
'▸' + action.label,
{fill: 0xFFFFFF}
)
text.interactive = true
text.on('mouseup', action.callback)
text.x = MENU_OFFSET
text.y = textsHeight
textsHeight += text.height
self.statusTexts.push(text)
self.stage.addChild(text)
})
textsHeight += MENU_OFFSET
state.getInfoTexts().forEach(function (statusInfoText) {
let text = new PIXI.Text(statusInfoText, {
fill: 0xAAAAAA,
wordWrap: true,
wordWrapWidth: MENU_INFO_TEXT_WIDTH
})
text.x = MENU_OFFSET
text.y = textsHeight
textsHeight += text.height + MENU_INFO_TEXT_MARGIN
self.statusTexts.push(text)
self.stage.addChild(text)
})
}
}
| MenuInterface refactoring: extraction of private methods from updateGameState
| src/Interface/MenuInterface.js | MenuInterface refactoring: extraction of private methods from updateGameState | <ide><path>rc/Interface/MenuInterface.js
<ide>
<ide> /** @type {PIXI.Text[]} */
<ide> this.statusTexts = []
<add>
<add> /** @type {number} */
<add> this.textOffset = 0
<ide> }
<ide>
<ide> initialize () {
<ide> })
<ide>
<ide> this.statusTexts = []
<del> let textsHeight = MENU_OFFSET + self.playerText.height + MENU_OFFSET
<add> this.textOffset = MENU_OFFSET + self.playerText.height
<ide>
<del> state.getActions().forEach(function (action) {
<del> let text = new PIXI.Text(
<del> '▸' + action.label,
<del> {fill: 0xFFFFFF}
<del> )
<add> this.textOffset += MENU_OFFSET
<add> state.getActions().forEach(action => this.addStateAction(action))
<ide>
<del> text.interactive = true
<del> text.on('mouseup', action.callback)
<del> text.x = MENU_OFFSET
<del> text.y = textsHeight
<del> textsHeight += text.height
<add> this.textOffset += MENU_OFFSET
<add> state.getInfoTexts().forEach(infoText => this.addStateInfoText(infoText))
<add> }
<ide>
<del> self.statusTexts.push(text)
<del> self.stage.addChild(text)
<add> /**
<add> * @param {Action} action
<add> */
<add> addStateAction (action) {
<add> let labelText = '▸' + action.label
<add> let text = new PIXI.Text(labelText, {
<add> fill: 0xFFFFFF
<ide> })
<ide>
<del> textsHeight += MENU_OFFSET
<add> text.interactive = true
<add> text.on('mouseup', action.callback)
<ide>
<del> state.getInfoTexts().forEach(function (statusInfoText) {
<del> let text = new PIXI.Text(statusInfoText, {
<del> fill: 0xAAAAAA,
<del> wordWrap: true,
<del> wordWrapWidth: MENU_INFO_TEXT_WIDTH
<del> })
<add> text.x = MENU_OFFSET
<add> text.y = this.textOffset
<add> this.textOffset += text.height
<ide>
<del> text.x = MENU_OFFSET
<del> text.y = textsHeight
<del> textsHeight += text.height + MENU_INFO_TEXT_MARGIN
<add> this.statusTexts.push(text)
<add> this.stage.addChild(text)
<add> }
<ide>
<del> self.statusTexts.push(text)
<del> self.stage.addChild(text)
<add> /**
<add> * @param {string} infoText
<add> */
<add> addStateInfoText (infoText) {
<add> let text = new PIXI.Text(infoText, {
<add> fill: 0xAAAAAA,
<add> wordWrap: true,
<add> wordWrapWidth: MENU_INFO_TEXT_WIDTH
<ide> })
<add>
<add> text.x = MENU_OFFSET
<add> text.y = this.textOffset
<add> this.textOffset += text.height + MENU_INFO_TEXT_MARGIN
<add>
<add> this.statusTexts.push(text)
<add> this.stage.addChild(text)
<ide> }
<ide> } |
|
Java | lgpl-2.1 | 53d58f9d403804f2dc5738ce18f8d9dc7fac0258 | 0 | mbatchelor/pentaho-platform-plugin-reporting,mbatchelor/pentaho-platform-plugin-reporting,mbatchelor/pentaho-platform-plugin-reporting | package org.pentaho.reporting.platform.plugin.cache;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.event.CacheEventListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.platform.api.engine.ILogoutListener;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.engine.core.system.PentahoSessionHolder;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.ReportProcessingException;
import org.pentaho.reporting.libraries.repository.ContentIOException;
import org.pentaho.reporting.platform.plugin.output.ReportOutputHandler;
/**
* This cache stores the report-output-handler on a map inside the user's session.
*
* @author Thomas Morgner.
*/
public class DefaultReportCache implements ReportCache
{
private static String SESSION_ATTRIBUTE = DefaultReportCache.class.getName() + "-Cache";
private static final String CACHE_NAME = "report-output-handlers";
private static final Log logger = LogFactory.getLog(DefaultReportCache.class);
private static class LogoutHandler implements ILogoutListener
{
private LogoutHandler()
{
}
public void onLogout(final IPentahoSession session)
{
logger.debug("Shutting down session " + session.getId());
final Object attribute = session.getAttribute(SESSION_ATTRIBUTE);
if (attribute instanceof CacheManager == false)
{
logger.debug("Shutting down session " + session.getId() + ": No cache manager found");
return;
}
final CacheManager manager = (CacheManager) attribute;
if (manager.cacheExists(CACHE_NAME))
{
final Cache cache = manager.getCache(CACHE_NAME);
//noinspection unchecked
final List<Object> keys = new ArrayList<Object>(cache.getKeys());
logger.debug("Shutting down session " + session.getId() + ": Closing " + keys.size() + " open reports.");
for (final Object key : keys)
{
// remove also closes the cache-holder and thus the report (if the report is no longer in use).
cache.remove(key);
}
}
logger.debug("Shutting down session " + session.getId() + ": Closing cache manager.");
manager.shutdown();
}
}
private static class CacheHolder
{
private ReportCacheKey realKey;
private ReportOutputHandler outputHandler;
private boolean closed;
private boolean reportInUse;
private boolean reportInCache;
private CacheHolder(final ReportCacheKey realKey, final ReportOutputHandler outputHandler)
{
if (outputHandler == null)
{
throw new NullPointerException();
}
if (realKey == null)
{
throw new NullPointerException();
}
this.reportInCache = true;
this.realKey = realKey;
this.outputHandler = outputHandler;
}
public synchronized void markEvicted()
{
reportInCache = false;
}
public boolean isReportInCache()
{
return reportInCache;
}
public ReportCacheKey getRealKey()
{
return realKey;
}
public ReportOutputHandler getOutputHandler()
{
return outputHandler;
}
public synchronized void close()
{
if (reportInUse && reportInCache)
{
return;
}
if (closed == false)
{
outputHandler.close();
closed = true;
}
}
public synchronized void setReportInUse(final boolean reportInUse)
{
this.reportInUse = reportInUse;
}
}
private static class CacheEvictionHandler implements CacheEventListener
{
private CacheEvictionHandler()
{
}
public void notifyElementRemoved(final Ehcache ehcache, final Element element) throws CacheException
{
final Object o = element.getObjectValue();
if (o instanceof CacheHolder == false)
{
return;
}
final CacheHolder cacheHolder = (CacheHolder) o;
cacheHolder.close();
}
public void notifyElementPut(final Ehcache ehcache, final Element element) throws CacheException
{
}
public void notifyElementUpdated(final Ehcache ehcache, final Element element) throws CacheException
{
}
public void notifyElementExpired(final Ehcache ehcache, final Element element)
{
final Object o = element.getObjectValue();
if (o instanceof CacheHolder == false)
{
return;
}
final CacheHolder cacheHolder = (CacheHolder) o;
logger.debug("Shutting down report on element-expired event " + cacheHolder.getRealKey().getSessionId());
cacheHolder.close();
}
/**
* This method is called when a element is automatically removed from the cache. We then clear it here.
*
* @param ehcache
* @param element
*/
public void notifyElementEvicted(final Ehcache ehcache, final Element element)
{
final Object o = element.getObjectValue();
if (o instanceof CacheHolder == false)
{
return;
}
final CacheHolder cacheHolder = (CacheHolder) o;
cacheHolder.markEvicted();
logger.debug("Shutting down report on element-evicted event " + cacheHolder.getRealKey().getSessionId());
cacheHolder.close();
}
public void notifyRemoveAll(final Ehcache ehcache)
{
// could be that we are to late already here, the javadoc is not very clear on this one ..
//noinspection unchecked
final List keys = new ArrayList(ehcache.getKeys());
for (final Object key : keys)
{
final Element element = ehcache.get(key);
final Object o = element.getValue();
if (o instanceof CacheHolder)
{
final CacheHolder cacheHolder = (CacheHolder) o;
cacheHolder.markEvicted();
logger.debug("Shutting down report on remove-all event " + cacheHolder.getRealKey().getSessionId());
cacheHolder.close();
}
}
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
public void dispose()
{
}
}
private static class CachedReportOutputHandler implements ReportOutputHandler
{
private CacheHolder parent;
private CachedReportOutputHandler(final CacheHolder parent)
{
this.parent = parent;
this.parent.setReportInUse(true);
}
public int paginate(final MasterReport report, final int yieldRate)
throws ReportProcessingException, IOException, ContentIOException
{
return parent.getOutputHandler().paginate(report, yieldRate);
}
public boolean generate(final MasterReport report,
final int acceptedPage,
final OutputStream outputStream,
final int yieldRate)
throws ReportProcessingException, IOException, ContentIOException
{
return parent.getOutputHandler().generate(report, acceptedPage, outputStream, yieldRate);
}
public void close()
{
this.parent.setReportInUse(false);
if (this.parent.isReportInCache() == false)
{
this.parent.close();
}
}
}
public DefaultReportCache()
{
PentahoSystem.addLogoutListener(new LogoutHandler());
}
public ReportOutputHandler get(final ReportCacheKey key)
{
final IPentahoSession session = PentahoSessionHolder.getSession();
logger.debug("id: " + session.getId() + " - Cache.get(..) started");
synchronized (session)
{
final Object attribute = session.getAttribute(SESSION_ATTRIBUTE);
if (attribute instanceof CacheManager == false)
{
logger.debug("id: " + session.getId() + " - Cache.get(..): No cache manager");
return null;
}
final CacheManager manager = (CacheManager) attribute;
if (manager.cacheExists(CACHE_NAME) == false)
{
logger.debug("id: " + session.getId() + " - Cache.get(..): No cache registered");
return null;
}
final Cache cache = manager.getCache(CACHE_NAME);
final Element element = cache.get(key.getSessionId());
if (element == null)
{
logger.debug("id: " + session.getId() + " - Cache.get(..): No element in cache for key: " + key.getSessionId());
return null;
}
final Object o = element.getObjectValue();
if (o instanceof CacheHolder == false)
{
logger.debug("id: " + session.getId() + " - Cache.get(..): No valid element in cache for key: " + key.getSessionId());
return null;
}
final CacheHolder cacheHolder = (CacheHolder) o;
if (cacheHolder.getRealKey().equals(key) == false)
{
logger.debug("id: " + session.getId() + " - Cache.get(..): remove stale report after parameter changed: " + key.getSessionId());
cache.remove(key.getSessionId());
return null;
}
logger.debug("id: " + session.getId() + " - Cache.get(..): Returning cached instance for key: " + key.getSessionId());
return new CachedReportOutputHandler(cacheHolder);
}
}
public ReportOutputHandler put(final ReportCacheKey key, final ReportOutputHandler report)
{
if (report instanceof CachedReportOutputHandler)
{
throw new IllegalStateException();
}
final IPentahoSession session = PentahoSessionHolder.getSession();
logger.debug("id: " + session.getId() + " - Cache.put(..) started");
synchronized (session)
{
final Object attribute = session.getAttribute(SESSION_ATTRIBUTE);
final CacheManager manager;
if (attribute instanceof CacheManager == false)
{
logger.debug("id: " + session.getId() + " - Cache.put(..): No cache manager; creating one");
manager = new CacheManager();
session.setAttribute(SESSION_ATTRIBUTE, manager);
}
else
{
manager = (CacheManager) attribute;
}
if (manager.cacheExists(CACHE_NAME) == false)
{
logger.debug("id: " + session.getId() + " - Cache.put(..): No cache registered with manager; creating one");
manager.addCache(CACHE_NAME);
final Cache cache = manager.getCache(CACHE_NAME);
cache.getCacheEventNotificationService().registerListener(new CacheEvictionHandler());
}
final Cache cache = manager.getCache(CACHE_NAME);
final Element element = cache.get(key.getSessionId());
if (element != null)
{
final Object o = element.getObjectValue();
if (o instanceof CacheHolder)
{
final CacheHolder cacheHolder = (CacheHolder) o;
if (cacheHolder.getRealKey().equals(key) == false)
{
logger.debug("id: " + session.getId() + " - Cache.put(..): Removing stale object.");
cache.remove(key.getSessionId());
}
else
{
// otherwise: Keep the element in the cache and the next put will perform an "update" operation
// on it. This will not close the report object.
logger.debug("id: " + session.getId() + " - Cache.put(..): keeping existing object, no cache operation done.");
return new CachedReportOutputHandler(cacheHolder);
}
}
}
final CacheHolder cacheHolder = new CacheHolder(key, report);
cache.put(new Element(key.getSessionId(), cacheHolder));
logger.debug("id: " + session.getId() + " - Cache.put(..): storing new report for key " + key.getSessionId());
return new CachedReportOutputHandler(cacheHolder);
}
}
}
| src/org/pentaho/reporting/platform/plugin/cache/DefaultReportCache.java | package org.pentaho.reporting.platform.plugin.cache;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.event.CacheEventListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.platform.api.engine.ILogoutListener;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.engine.core.system.PentahoSessionHolder;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.ReportProcessingException;
import org.pentaho.reporting.libraries.repository.ContentIOException;
import org.pentaho.reporting.platform.plugin.output.ReportOutputHandler;
/**
* This cache stores the report-output-handler on a map inside the user's session.
*
* @author Thomas Morgner.
*/
public class DefaultReportCache implements ReportCache
{
private static String SESSION_ATTRIBUTE = DefaultReportCache.class.getName() + "-Cache";
private static final String CACHE_NAME = "report-output-handlers";
private static final Log logger = LogFactory.getLog(DefaultReportCache.class);
private static class LogoutHandler implements ILogoutListener
{
private LogoutHandler()
{
}
public void onLogout(final IPentahoSession session)
{
logger.debug("Shutting down session " + session.getId());
final Object attribute = session.getAttribute(SESSION_ATTRIBUTE);
if (attribute instanceof CacheManager == false)
{
logger.debug("Shutting down session " + session.getId() + ": No cache manager found");
return;
}
final CacheManager manager = (CacheManager) attribute;
if (manager.cacheExists(CACHE_NAME))
{
final Cache cache = manager.getCache(CACHE_NAME);
//noinspection unchecked
final List<Object> keys = new ArrayList<Object>(cache.getKeys());
logger.debug("Shutting down session " + session.getId() + ": Closing " + keys.size() + " open reports.");
for (final Object key : keys)
{
// remove also closes the cache-holder and thus the report (if the report is no longer in use).
cache.remove(key);
}
}
logger.debug("Shutting down session " + session.getId() + ": Closing cache manager.");
manager.shutdown();
}
}
private static class CacheHolder
{
private ReportCacheKey realKey;
private ReportOutputHandler outputHandler;
private boolean closed;
private boolean reportInUse;
private boolean reportInCache;
private CacheHolder(final ReportCacheKey realKey, final ReportOutputHandler outputHandler)
{
if (outputHandler == null)
{
throw new NullPointerException();
}
if (realKey == null)
{
throw new NullPointerException();
}
this.reportInCache = true;
this.realKey = realKey;
this.outputHandler = outputHandler;
}
public synchronized void markEvicted()
{
reportInCache = false;
}
public boolean isReportInCache()
{
return reportInCache;
}
public ReportCacheKey getRealKey()
{
return realKey;
}
public ReportOutputHandler getOutputHandler()
{
return outputHandler;
}
public synchronized void close()
{
if (reportInUse && reportInCache)
{
return;
}
if (closed == false)
{
outputHandler.close();
closed = true;
}
}
public synchronized void setReportInUse(final boolean reportInUse)
{
this.reportInUse = reportInUse;
}
}
private static class CacheEvictionHandler implements CacheEventListener
{
private CacheEvictionHandler()
{
}
public void notifyElementRemoved(final Ehcache ehcache, final Element element) throws CacheException
{
final Object o = element.getObjectValue();
if (o instanceof CacheHolder == false)
{
return;
}
final CacheHolder cacheHolder = (CacheHolder) o;
cacheHolder.close();
}
public void notifyElementPut(final Ehcache ehcache, final Element element) throws CacheException
{
}
public void notifyElementUpdated(final Ehcache ehcache, final Element element) throws CacheException
{
}
public void notifyElementExpired(final Ehcache ehcache, final Element element)
{
final Object o = element.getObjectValue();
if (o instanceof CacheHolder == false)
{
return;
}
final CacheHolder cacheHolder = (CacheHolder) o;
logger.debug("Shutting down report on element-expired event " + cacheHolder.getRealKey().getSessionId());
cacheHolder.close();
}
/**
* This method is called when a element is automatically removed from the cache. We then clear it here.
*
* @param ehcache
* @param element
*/
public void notifyElementEvicted(final Ehcache ehcache, final Element element)
{
final Object o = element.getObjectValue();
if (o instanceof CacheHolder == false)
{
return;
}
final CacheHolder cacheHolder = (CacheHolder) o;
cacheHolder.markEvicted();
logger.debug("Shutting down report on element-evicted event " + cacheHolder.getRealKey().getSessionId());
cacheHolder.close();
}
public void notifyRemoveAll(final Ehcache ehcache)
{
// could be that we are to late already here, the javadoc is not very clear on this one ..
//noinspection unchecked
final List keys = new ArrayList(ehcache.getKeys());
for (final Object key : keys)
{
final Element element = ehcache.get(key);
final Object o = element.getValue();
if (o instanceof CacheHolder)
{
final CacheHolder cacheHolder = (CacheHolder) o;
cacheHolder.markEvicted();
logger.debug("Shutting down report on remove-all event " + cacheHolder.getRealKey().getSessionId());
cacheHolder.close();
}
}
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
public void dispose()
{
}
}
private static class CachedReportOutputHandler implements ReportOutputHandler
{
private CacheHolder parent;
private CachedReportOutputHandler(final CacheHolder parent)
{
this.parent = parent;
this.parent.setReportInUse(true);
}
public int paginate(final MasterReport report, final int yieldRate)
throws ReportProcessingException, IOException, ContentIOException
{
return parent.getOutputHandler().paginate(report, yieldRate);
}
public boolean generate(final MasterReport report,
final int acceptedPage,
final OutputStream outputStream,
final int yieldRate)
throws ReportProcessingException, IOException, ContentIOException
{
return parent.getOutputHandler().generate(report, acceptedPage, outputStream, yieldRate);
}
public void close()
{
this.parent.setReportInUse(false);
if (this.parent.isReportInCache() == false)
{
this.parent.close();
}
}
}
public DefaultReportCache()
{
}
public ReportOutputHandler get(final ReportCacheKey key)
{
final IPentahoSession session = PentahoSessionHolder.getSession();
logger.debug("id: " + session.getId() + " - Cache.get(..) started");
synchronized (session)
{
final Object attribute = session.getAttribute(SESSION_ATTRIBUTE);
if (attribute instanceof CacheManager == false)
{
logger.debug("id: " + session.getId() + " - Cache.get(..): No cache manager");
return null;
}
final CacheManager manager = (CacheManager) attribute;
if (manager.cacheExists(CACHE_NAME) == false)
{
logger.debug("id: " + session.getId() + " - Cache.get(..): No cache registered");
return null;
}
final Cache cache = manager.getCache(CACHE_NAME);
final Element element = cache.get(key.getSessionId());
if (element == null)
{
logger.debug("id: " + session.getId() + " - Cache.get(..): No element in cache for key: " + key.getSessionId());
return null;
}
final Object o = element.getObjectValue();
if (o instanceof CacheHolder == false)
{
logger.debug("id: " + session.getId() + " - Cache.get(..): No valid element in cache for key: " + key.getSessionId());
return null;
}
final CacheHolder cacheHolder = (CacheHolder) o;
if (cacheHolder.getRealKey().equals(key) == false)
{
logger.debug("id: " + session.getId() + " - Cache.get(..): remove stale report after parameter changed: " + key.getSessionId());
cache.remove(key.getSessionId());
return null;
}
logger.debug("id: " + session.getId() + " - Cache.get(..): Returning cached instance for key: " + key.getSessionId());
return new CachedReportOutputHandler(cacheHolder);
}
}
public ReportOutputHandler put(final ReportCacheKey key, final ReportOutputHandler report)
{
if (report instanceof CachedReportOutputHandler)
{
throw new IllegalStateException();
}
final IPentahoSession session = PentahoSessionHolder.getSession();
logger.debug("id: " + session.getId() + " - Cache.put(..) started");
synchronized (session)
{
final Object attribute = session.getAttribute(SESSION_ATTRIBUTE);
final CacheManager manager;
if (attribute instanceof CacheManager == false)
{
logger.debug("id: " + session.getId() + " - Cache.put(..): No cache manager; creating one");
manager = new CacheManager();
session.setAttribute(SESSION_ATTRIBUTE, manager);
PentahoSystem.addLogoutListener(new LogoutHandler());
}
else
{
manager = (CacheManager) attribute;
}
if (manager.cacheExists(CACHE_NAME) == false)
{
logger.debug("id: " + session.getId() + " - Cache.put(..): No cache registered with manager; creating one");
manager.addCache(CACHE_NAME);
final Cache cache = manager.getCache(CACHE_NAME);
cache.getCacheEventNotificationService().registerListener(new CacheEvictionHandler());
}
final Cache cache = manager.getCache(CACHE_NAME);
final Element element = cache.get(key.getSessionId());
if (element != null)
{
final Object o = element.getObjectValue();
if (o instanceof CacheHolder)
{
final CacheHolder cacheHolder = (CacheHolder) o;
if (cacheHolder.getRealKey().equals(key) == false)
{
logger.debug("id: " + session.getId() + " - Cache.put(..): Removing stale object.");
cache.remove(key.getSessionId());
}
else
{
// otherwise: Keep the element in the cache and the next put will perform an "update" operation
// on it. This will not close the report object.
logger.debug("id: " + session.getId() + " - Cache.put(..): keeping existing object, no cache operation done.");
return new CachedReportOutputHandler(cacheHolder);
}
}
}
final CacheHolder cacheHolder = new CacheHolder(key, report);
cache.put(new Element(key.getSessionId(), cacheHolder));
logger.debug("id: " + session.getId() + " - Cache.put(..): storing new report for key " + key.getSessionId());
return new CachedReportOutputHandler(cacheHolder);
}
}
}
| [BISERVER-5566] only add logout listener once
| src/org/pentaho/reporting/platform/plugin/cache/DefaultReportCache.java | [BISERVER-5566] only add logout listener once | <ide><path>rc/org/pentaho/reporting/platform/plugin/cache/DefaultReportCache.java
<ide>
<ide> public DefaultReportCache()
<ide> {
<add> PentahoSystem.addLogoutListener(new LogoutHandler());
<ide> }
<ide>
<ide> public ReportOutputHandler get(final ReportCacheKey key)
<ide> logger.debug("id: " + session.getId() + " - Cache.put(..): No cache manager; creating one");
<ide> manager = new CacheManager();
<ide> session.setAttribute(SESSION_ATTRIBUTE, manager);
<del> PentahoSystem.addLogoutListener(new LogoutHandler());
<ide> }
<ide> else
<ide> { |
|
Java | apache-2.0 | 50a7e7c79448a73858333a94a376a150b1c81a95 | 0 | kunallimaye/optaplanner,eshen1991/optaplanner,oskopek/optaplanner,DieterDePaepe/optaplanner,bernardator/optaplanner,kunallimaye/optaplanner,codeaudit/optaplanner,glamperi/optaplanner,codeaudit/optaplanner,droolsjbpm/optaplanner,glamperi/optaplanner,tomasdavidorg/optaplanner,gsheldon/optaplanner,netinept/Court-Scheduler,gsheldon/optaplanner,tkobayas/optaplanner,elsam/drools-planner-old,baldimir/optaplanner,elsam/drools-planner-old,oskopek/optaplanner,droolsjbpm/optaplanner,tkobayas/optaplanner,baldimir/optaplanner,bernardator/optaplanner,baldimir/optaplanner,eshen1991/optaplanner,netinept/Court-Scheduler,gsheldon/optaplanner,netinept/Court-Scheduler,bernardator/optaplanner,droolsjbpm/optaplanner,eshen1991/optaplanner,tomasdavidorg/optaplanner,snurkabill/optaplanner,kunallimaye/optaplanner,snurkabill/optaplanner,codeaudit/optaplanner,baldimir/optaplanner,elsam/drools-planner-old,oskopek/optaplanner,DieterDePaepe/optaplanner,tomasdavidorg/optaplanner,gsheldon/optaplanner,droolsjbpm/optaplanner,tkobayas/optaplanner,glamperi/optaplanner,tkobayas/optaplanner,snurkabill/optaplanner,oskopek/optaplanner | /*
* Copyright 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.planner.core.heuristic.selector.move.generic.chained;
import java.util.Collection;
import org.apache.commons.lang.ObjectUtils;
import org.drools.planner.core.domain.variable.PlanningVariableDescriptor;
import org.drools.planner.core.heuristic.selector.move.generic.SwapMove;
import org.drools.planner.core.move.Move;
import org.drools.planner.core.score.director.ScoreDirector;
public class ChainedSwapMove extends SwapMove {
public ChainedSwapMove(Collection<PlanningVariableDescriptor> variableDescriptors,
Object leftEntity, Object rightEntity) {
super(variableDescriptors, leftEntity, rightEntity);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Move createUndoMove(ScoreDirector scoreDirector) {
return new ChainedSwapMove(variableDescriptors, rightEntity, leftEntity);
}
public void doMove(ScoreDirector scoreDirector) {
for (PlanningVariableDescriptor variableDescriptor : variableDescriptors) {
Object oldLeftValue = variableDescriptor.getValue(leftEntity);
Object oldRightValue = variableDescriptor.getValue(rightEntity);
if (!ObjectUtils.equals(oldLeftValue, oldRightValue)) {
if (!variableDescriptor.isChained()) {
scoreDirector.beforeVariableChanged(leftEntity, variableDescriptor.getVariableName());
variableDescriptor.setValue(leftEntity, oldRightValue);
scoreDirector.afterVariableChanged(leftEntity, variableDescriptor.getVariableName());
scoreDirector.beforeVariableChanged(rightEntity, variableDescriptor.getVariableName());
variableDescriptor.setValue(rightEntity, oldLeftValue);
scoreDirector.afterVariableChanged(rightEntity, variableDescriptor.getVariableName());
} else {
if (oldRightValue != leftEntity) {
doChainedMove(scoreDirector, variableDescriptor, leftEntity, oldRightValue);
}
if (oldLeftValue != rightEntity) {
doChainedMove(scoreDirector, variableDescriptor, rightEntity, oldLeftValue);
}
}
}
}
}
// TODO DRY with ChainedChangeMove
public void doChainedMove(ScoreDirector scoreDirector, PlanningVariableDescriptor variableDescriptor,
Object entity, Object toPlanningValue) {
Object oldPlanningValue = variableDescriptor.getValue(entity);
Object oldTrailingEntity = scoreDirector.getTrailingEntity(variableDescriptor, entity);
// If chaining == true then toPlanningValue == null guarantees an uninitialized entity
Object newTrailingEntity = toPlanningValue == null ? null
: scoreDirector.getTrailingEntity(variableDescriptor, toPlanningValue);
// Close the old chain
if (oldTrailingEntity != null) {
scoreDirector.beforeVariableChanged(oldTrailingEntity, variableDescriptor.getVariableName());
variableDescriptor.setValue(oldTrailingEntity, oldPlanningValue);
scoreDirector.afterVariableChanged(oldTrailingEntity, variableDescriptor.getVariableName());
}
// Change the entity
scoreDirector.beforeVariableChanged(entity, variableDescriptor.getVariableName());
variableDescriptor.setValue(entity, toPlanningValue);
scoreDirector.afterVariableChanged(entity, variableDescriptor.getVariableName());
// Reroute the new chain
if (newTrailingEntity != null) {
scoreDirector.beforeVariableChanged(newTrailingEntity, variableDescriptor.getVariableName());
variableDescriptor.setValue(newTrailingEntity, entity);
scoreDirector.afterVariableChanged(newTrailingEntity, variableDescriptor.getVariableName());
}
}
}
| drools-planner-core/src/main/java/org/drools/planner/core/heuristic/selector/move/generic/chained/ChainedSwapMove.java | /*
* Copyright 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.planner.core.heuristic.selector.move.generic.chained;
import java.util.Collection;
import org.apache.commons.lang.ObjectUtils;
import org.drools.planner.core.domain.variable.PlanningVariableDescriptor;
import org.drools.planner.core.heuristic.selector.move.generic.SwapMove;
import org.drools.planner.core.move.Move;
import org.drools.planner.core.score.director.ScoreDirector;
public class ChainedSwapMove extends SwapMove {
public ChainedSwapMove(Collection<PlanningVariableDescriptor> variableDescriptors,
Object leftEntity, Object rightEntity) {
super(variableDescriptors, leftEntity, rightEntity);
}
// ************************************************************************
// Worker methods
// ************************************************************************
@Override
public Move createUndoMove(ScoreDirector scoreDirector) {
return new ChainedSwapMove(variableDescriptors, rightEntity, leftEntity);
}
public void doMove(ScoreDirector scoreDirector) {
for (PlanningVariableDescriptor variableDescriptor : variableDescriptors) {
Object oldLeftValue = variableDescriptor.getValue(leftEntity);
Object oldRightValue = variableDescriptor.getValue(rightEntity);
if (!ObjectUtils.equals(oldLeftValue, oldRightValue)) {
if (!variableDescriptor.isChained()) {
scoreDirector.beforeVariableChanged(leftEntity, variableDescriptor.getVariableName());
variableDescriptor.setValue(leftEntity, oldRightValue);
scoreDirector.afterVariableChanged(leftEntity, variableDescriptor.getVariableName());
scoreDirector.beforeVariableChanged(rightEntity, variableDescriptor.getVariableName());
variableDescriptor.setValue(rightEntity, oldLeftValue);
scoreDirector.afterVariableChanged(rightEntity, variableDescriptor.getVariableName());
} else {
if (oldRightValue != leftEntity) {
doChainedMove(scoreDirector, variableDescriptor, leftEntity, oldRightValue);
}
if (oldLeftValue != rightEntity) {
doChainedMove(scoreDirector, variableDescriptor, rightEntity, oldLeftValue);
}
}
}
}
}
// TODO DRY with ChainedChangeMove
public void doChainedMove(ScoreDirector scoreDirector, PlanningVariableDescriptor variableDescriptor,
Object planningEntity, Object toPlanningValue ) {
Object oldPlanningValue = variableDescriptor.getValue(planningEntity);
Object oldTrailingEntity = scoreDirector.getTrailingEntity(variableDescriptor, planningEntity);
// If chaining == true then toPlanningValue == null guarantees an uninitialized entity
Object newTrailingEntity = toPlanningValue == null ? null
: scoreDirector.getTrailingEntity(variableDescriptor, toPlanningValue);
// Close the old chain
if (oldTrailingEntity != null) {
scoreDirector.beforeVariableChanged(oldTrailingEntity, variableDescriptor.getVariableName());
variableDescriptor.setValue(oldTrailingEntity, oldPlanningValue);
scoreDirector.afterVariableChanged(oldTrailingEntity, variableDescriptor.getVariableName());
}
// Change the entity
scoreDirector.beforeVariableChanged(planningEntity, variableDescriptor.getVariableName());
variableDescriptor.setValue(planningEntity, toPlanningValue);
scoreDirector.afterVariableChanged(planningEntity, variableDescriptor.getVariableName());
// Reroute the new chain
if (newTrailingEntity != null) {
scoreDirector.beforeVariableChanged(newTrailingEntity, variableDescriptor.getVariableName());
variableDescriptor.setValue(newTrailingEntity, planningEntity);
scoreDirector.afterVariableChanged(newTrailingEntity, variableDescriptor.getVariableName());
}
}
}
| simplify field names (remove "planning" prefix)
| drools-planner-core/src/main/java/org/drools/planner/core/heuristic/selector/move/generic/chained/ChainedSwapMove.java | simplify field names (remove "planning" prefix) | <ide><path>rools-planner-core/src/main/java/org/drools/planner/core/heuristic/selector/move/generic/chained/ChainedSwapMove.java
<ide>
<ide> // TODO DRY with ChainedChangeMove
<ide> public void doChainedMove(ScoreDirector scoreDirector, PlanningVariableDescriptor variableDescriptor,
<del> Object planningEntity, Object toPlanningValue ) {
<del> Object oldPlanningValue = variableDescriptor.getValue(planningEntity);
<del> Object oldTrailingEntity = scoreDirector.getTrailingEntity(variableDescriptor, planningEntity);
<add> Object entity, Object toPlanningValue) {
<add> Object oldPlanningValue = variableDescriptor.getValue(entity);
<add> Object oldTrailingEntity = scoreDirector.getTrailingEntity(variableDescriptor, entity);
<ide> // If chaining == true then toPlanningValue == null guarantees an uninitialized entity
<ide> Object newTrailingEntity = toPlanningValue == null ? null
<ide> : scoreDirector.getTrailingEntity(variableDescriptor, toPlanningValue);
<ide> }
<ide>
<ide> // Change the entity
<del> scoreDirector.beforeVariableChanged(planningEntity, variableDescriptor.getVariableName());
<del> variableDescriptor.setValue(planningEntity, toPlanningValue);
<del> scoreDirector.afterVariableChanged(planningEntity, variableDescriptor.getVariableName());
<add> scoreDirector.beforeVariableChanged(entity, variableDescriptor.getVariableName());
<add> variableDescriptor.setValue(entity, toPlanningValue);
<add> scoreDirector.afterVariableChanged(entity, variableDescriptor.getVariableName());
<ide>
<ide> // Reroute the new chain
<ide> if (newTrailingEntity != null) {
<ide> scoreDirector.beforeVariableChanged(newTrailingEntity, variableDescriptor.getVariableName());
<del> variableDescriptor.setValue(newTrailingEntity, planningEntity);
<add> variableDescriptor.setValue(newTrailingEntity, entity);
<ide> scoreDirector.afterVariableChanged(newTrailingEntity, variableDescriptor.getVariableName());
<ide> }
<ide> } |
|
Java | lgpl-2.1 | be6b77af464f1ae157cbe4a70a65d05dcbc80750 | 0 | mbenz89/soot,cfallin/soot,anddann/soot,mbenz89/soot,mbenz89/soot,xph906/SootNew,xph906/SootNew,plast-lab/soot,anddann/soot,plast-lab/soot,cfallin/soot,anddann/soot,cfallin/soot,xph906/SootNew,plast-lab/soot,cfallin/soot,mbenz89/soot,anddann/soot,xph906/SootNew | /* Soot - a J*va Optimization Framework
* Copyright (C) 1997-2000 Etienne Gagnon. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*
* Modified by the Sable Research Group and others 1997-1999.
* See the 'credits' file distributed with Soot for the complete list of
* contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot)
*/
package soot.jimple.toolkits.typing.integer;
import soot.ArrayType;
import soot.IntegerType;
import soot.Local;
import soot.NullType;
import soot.SootMethodRef;
import soot.Type;
import soot.Value;
import soot.jimple.AbstractStmtSwitch;
import soot.jimple.AddExpr;
import soot.jimple.AndExpr;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.BreakpointStmt;
import soot.jimple.CastExpr;
import soot.jimple.ClassConstant;
import soot.jimple.CmpExpr;
import soot.jimple.CmpgExpr;
import soot.jimple.CmplExpr;
import soot.jimple.ConditionExpr;
import soot.jimple.DivExpr;
import soot.jimple.DoubleConstant;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.EqExpr;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.FloatConstant;
import soot.jimple.GeExpr;
import soot.jimple.GotoStmt;
import soot.jimple.GtExpr;
import soot.jimple.IdentityStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceOfExpr;
import soot.jimple.IntConstant;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.JimpleBody;
import soot.jimple.LeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.LongConstant;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.LtExpr;
import soot.jimple.MulExpr;
import soot.jimple.NeExpr;
import soot.jimple.NegExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NopStmt;
import soot.jimple.NullConstant;
import soot.jimple.OrExpr;
import soot.jimple.RemExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.ShlExpr;
import soot.jimple.ShrExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.SubExpr;
import soot.jimple.TableSwitchStmt;
import soot.jimple.ThrowStmt;
import soot.jimple.UshrExpr;
import soot.jimple.XorExpr;
class ConstraintCollector extends AbstractStmtSwitch {
private TypeResolver resolver;
private boolean uses; // if true, include use contraints
private JimpleBody stmtBody;
public ConstraintCollector(TypeResolver resolver, boolean uses) {
this.resolver = resolver;
this.uses = uses;
}
public void collect(Stmt stmt, JimpleBody stmtBody) {
this.stmtBody = stmtBody;
stmt.apply(this);
}
private void handleInvokeExpr(InvokeExpr ie) {
if (!uses)
return;
SootMethodRef method = ie.getMethodRef();
int count = ie.getArgCount();
for (int i = 0; i < count; i++) {
if (ie.getArg(i) instanceof Local) {
Local local = (Local) ie.getArg(i);
if (local.getType() instanceof IntegerType) {
TypeVariable localType = resolver.typeVariable(local);
localType.addParent(resolver.typeVariable(method.parameterType(i)));
}
}
}
}
public void caseBreakpointStmt(BreakpointStmt stmt) {
// Do nothing
}
public void caseInvokeStmt(InvokeStmt stmt) {
handleInvokeExpr(stmt.getInvokeExpr());
}
public void caseAssignStmt(AssignStmt stmt) {
Value l = stmt.getLeftOp();
Value r = stmt.getRightOp();
TypeVariable left = null;
TypeVariable right = null;
// ******** LEFT ********
if (l instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) l;
Type baset = ((Local) ref.getBase()).getType();
if (baset instanceof ArrayType) {
ArrayType base = (ArrayType) baset;
Value index = ref.getIndex();
if (uses) {
if ((base.numDimensions == 1) && (base.baseType instanceof IntegerType)) {
left = resolver.typeVariable(base.baseType);
}
if (index instanceof Local) {
resolver.typeVariable((Local) index).addParent(resolver.INT);
}
}
}
} else if (l instanceof Local) {
if (((Local) l).getType() instanceof IntegerType) {
left = resolver.typeVariable((Local) l);
}
} else if (l instanceof InstanceFieldRef) {
if (uses) {
InstanceFieldRef ref = (InstanceFieldRef) l;
Type fieldType = ref.getFieldRef().type();
if (fieldType instanceof IntegerType) {
left = resolver.typeVariable(ref.getFieldRef().type());
}
}
} else if (l instanceof StaticFieldRef) {
if (uses) {
StaticFieldRef ref = (StaticFieldRef) l;
Type fieldType = ref.getFieldRef().type();
if (fieldType instanceof IntegerType) {
left = resolver.typeVariable(ref.getFieldRef().type());
}
}
} else {
throw new RuntimeException("Unhandled assignment left hand side type: " + l.getClass());
}
// ******** RIGHT ********
if (r instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) r;
Type baset = ((Local) ref.getBase()).getType();
if (!(baset instanceof NullType)) {
Value index = ref.getIndex();
// Be careful, dex can do some weird object/array casting
if (baset instanceof ArrayType) {
ArrayType base = (ArrayType) baset;
if ((base.numDimensions == 1) && (base.baseType instanceof IntegerType)) {
right = resolver.typeVariable(base.baseType);
}
} else if (baset instanceof IntegerType)
right = resolver.typeVariable(baset);
if (uses)
if (index instanceof Local)
resolver.typeVariable((Local) index).addParent(resolver.INT);
}
} else if (r instanceof DoubleConstant) {
} else if (r instanceof FloatConstant) {
} else if (r instanceof IntConstant) {
int value = ((IntConstant) r).value;
if (value < -32768) {
right = resolver.INT;
} else if (value < -128) {
right = resolver.SHORT;
} else if (value < 0) {
right = resolver.BYTE;
} else if (value < 2) {
right = resolver.R0_1;
} else if (value < 128) {
right = resolver.R0_127;
} else if (value < 32768) {
right = resolver.R0_32767;
} else if (value < 65536) {
right = resolver.CHAR;
} else {
right = resolver.INT;
}
} else if (r instanceof LongConstant) {
} else if (r instanceof NullConstant) {
} else if (r instanceof StringConstant) {
} else if (r instanceof ClassConstant) {
} else if (r instanceof BinopExpr) {
// ******** BINOP EXPR ********
BinopExpr be = (BinopExpr) r;
Value lv = be.getOp1();
Value rv = be.getOp2();
TypeVariable lop = null;
TypeVariable rop = null;
// ******** LEFT ********
if (lv instanceof Local) {
if (((Local) lv).getType() instanceof IntegerType) {
lop = resolver.typeVariable((Local) lv);
}
} else if (lv instanceof DoubleConstant) {
} else if (lv instanceof FloatConstant) {
} else if (lv instanceof IntConstant) {
int value = ((IntConstant) lv).value;
if (value < -32768) {
lop = resolver.INT;
} else if (value < -128) {
lop = resolver.SHORT;
} else if (value < 0) {
lop = resolver.BYTE;
} else if (value < 2) {
lop = resolver.R0_1;
} else if (value < 128) {
lop = resolver.R0_127;
} else if (value < 32768) {
lop = resolver.R0_32767;
} else if (value < 65536) {
lop = resolver.CHAR;
} else {
lop = resolver.INT;
}
} else if (lv instanceof LongConstant) {
} else if (lv instanceof NullConstant) {
} else if (lv instanceof StringConstant) {
} else if (lv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
if (((Local) rv).getType() instanceof IntegerType) {
rop = resolver.typeVariable((Local) rv);
}
} else if (rv instanceof DoubleConstant) {
} else if (rv instanceof FloatConstant) {
} else if (rv instanceof IntConstant) {
int value = ((IntConstant) rv).value;
if (value < -32768) {
rop = resolver.INT;
} else if (value < -128) {
rop = resolver.SHORT;
} else if (value < 0) {
rop = resolver.BYTE;
} else if (value < 2) {
rop = resolver.R0_1;
} else if (value < 128) {
rop = resolver.R0_127;
} else if (value < 32768) {
rop = resolver.R0_32767;
} else if (value < 65536) {
rop = resolver.CHAR;
} else {
rop = resolver.INT;
}
} else if (rv instanceof LongConstant) {
} else if (rv instanceof NullConstant) {
} else if (rv instanceof StringConstant) {
} else if (rv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
if ((be instanceof AddExpr) || (be instanceof SubExpr) || (be instanceof DivExpr)
|| (be instanceof RemExpr) || (be instanceof MulExpr)) {
if (lop != null && rop != null) {
if (uses) {
if (lop.type() == null) {
lop.addParent(resolver.INT);
}
if (rop.type() == null) {
rop.addParent(resolver.INT);
}
}
right = resolver.INT;
}
} else if ((be instanceof AndExpr) || (be instanceof OrExpr) || (be instanceof XorExpr)) {
if (lop != null && rop != null) {
TypeVariable common = resolver.typeVariable();
if (rop != null)
rop.addParent(common);
if (lop != null)
lop.addParent(common);
right = common;
}
} else if (be instanceof ShlExpr) {
if (uses) {
if (lop != null && lop.type() == null) {
lop.addParent(resolver.INT);
}
if (rop.type() == null) {
rop.addParent(resolver.INT);
}
}
right = (lop == null) ? null : resolver.INT;
} else if ((be instanceof ShrExpr) || (be instanceof UshrExpr)) {
if (uses) {
if (lop != null && lop.type() == null) {
lop.addParent(resolver.INT);
}
if (rop.type() == null) {
rop.addParent(resolver.INT);
}
}
right = lop;
} else if ((be instanceof CmpExpr) || (be instanceof CmpgExpr) || (be instanceof CmplExpr)) {
right = resolver.BYTE;
} else if ((be instanceof EqExpr) || (be instanceof GeExpr) || (be instanceof GtExpr)
|| (be instanceof LeExpr) || (be instanceof LtExpr) || (be instanceof NeExpr)) {
if (uses) {
TypeVariable common = resolver.typeVariable();
if (rop != null)
rop.addParent(common);
if (lop != null)
lop.addParent(common);
}
right = resolver.BOOLEAN;
} else {
throw new RuntimeException("Unhandled binary expression type: " + be.getClass());
}
} else if (r instanceof CastExpr) {
CastExpr ce = (CastExpr) r;
if (ce.getCastType() instanceof IntegerType) {
right = resolver.typeVariable(ce.getCastType());
}
} else if (r instanceof InstanceOfExpr) {
right = resolver.BOOLEAN;
} else if (r instanceof InvokeExpr) {
InvokeExpr ie = (InvokeExpr) r;
handleInvokeExpr(ie);
if (ie.getMethodRef().returnType() instanceof IntegerType) {
right = resolver.typeVariable(ie.getMethodRef().returnType());
}
} else if (r instanceof NewArrayExpr) {
NewArrayExpr nae = (NewArrayExpr) r;
if (uses) {
Value size = nae.getSize();
if (size instanceof Local) {
TypeVariable var = resolver.typeVariable((Local) size);
var.addParent(resolver.INT);
}
}
} else if (r instanceof NewExpr) {
} else if (r instanceof NewMultiArrayExpr) {
NewMultiArrayExpr nmae = (NewMultiArrayExpr) r;
if (uses) {
for (int i = 0; i < nmae.getSizeCount(); i++) {
Value size = nmae.getSize(i);
if (size instanceof Local) {
TypeVariable var = resolver.typeVariable((Local) size);
var.addParent(resolver.INT);
}
}
}
} else if (r instanceof LengthExpr) {
right = resolver.INT;
} else if (r instanceof NegExpr) {
NegExpr ne = (NegExpr) r;
if (ne.getOp() instanceof Local) {
Local local = (Local) ne.getOp();
if (local.getType() instanceof IntegerType) {
if (uses) {
resolver.typeVariable(local).addParent(resolver.INT);
}
TypeVariable v = resolver.typeVariable();
v.addChild(resolver.BYTE);
v.addChild(resolver.typeVariable(local));
right = v;
}
} else if (ne.getOp() instanceof DoubleConstant) {
} else if (ne.getOp() instanceof FloatConstant) {
} else if (ne.getOp() instanceof IntConstant) {
int value = ((IntConstant) ne.getOp()).value;
if (value < -32768) {
right = resolver.INT;
} else if (value < -128) {
right = resolver.SHORT;
} else if (value < 0) {
right = resolver.BYTE;
} else if (value < 2) {
right = resolver.BYTE;
} else if (value < 128) {
right = resolver.BYTE;
} else if (value < 32768) {
right = resolver.SHORT;
} else if (value < 65536) {
right = resolver.INT;
} else {
right = resolver.INT;
}
} else if (ne.getOp() instanceof LongConstant) {
} else {
throw new RuntimeException("Unhandled neg expression operand type: " + ne.getOp().getClass());
}
} else if (r instanceof Local) {
Local local = (Local) r;
if (local.getType() instanceof IntegerType) {
right = resolver.typeVariable(local);
}
} else if (r instanceof InstanceFieldRef) {
InstanceFieldRef ref = (InstanceFieldRef) r;
if (ref.getFieldRef().type() instanceof IntegerType) {
right = resolver.typeVariable(ref.getFieldRef().type());
}
} else if (r instanceof StaticFieldRef) {
StaticFieldRef ref = (StaticFieldRef) r;
if (ref.getFieldRef().type() instanceof IntegerType) {
right = resolver.typeVariable(ref.getFieldRef().type());
}
} else {
throw new RuntimeException("Unhandled assignment right hand side type: " + r.getClass());
}
if (left != null && right != null && (left.type() == null || right.type() == null)) {
right.addParent(left);
}
}
public void caseIdentityStmt(IdentityStmt stmt) {
Value l = stmt.getLeftOp();
Value r = stmt.getRightOp();
if (l instanceof Local) {
if (((Local) l).getType() instanceof IntegerType) {
TypeVariable left = resolver.typeVariable((Local) l);
TypeVariable right = resolver.typeVariable(r.getType());
right.addParent(left);
}
}
}
public void caseEnterMonitorStmt(EnterMonitorStmt stmt) {
}
public void caseExitMonitorStmt(ExitMonitorStmt stmt) {
}
public void caseGotoStmt(GotoStmt stmt) {
}
public void caseIfStmt(IfStmt stmt) {
if (uses) {
ConditionExpr cond = (ConditionExpr) stmt.getCondition();
BinopExpr expr = cond;
Value lv = expr.getOp1();
Value rv = expr.getOp2();
TypeVariable lop = null;
TypeVariable rop = null;
// ******** LEFT ********
if (lv instanceof Local) {
if (((Local) lv).getType() instanceof IntegerType) {
lop = resolver.typeVariable((Local) lv);
}
} else if (lv instanceof DoubleConstant) {
} else if (lv instanceof FloatConstant) {
} else if (lv instanceof IntConstant) {
int value = ((IntConstant) lv).value;
if (value < -32768) {
lop = resolver.INT;
} else if (value < -128) {
lop = resolver.SHORT;
} else if (value < 0) {
lop = resolver.BYTE;
} else if (value < 2) {
lop = resolver.R0_1;
} else if (value < 128) {
lop = resolver.R0_127;
} else if (value < 32768) {
lop = resolver.R0_32767;
} else if (value < 65536) {
lop = resolver.CHAR;
} else {
lop = resolver.INT;
}
} else if (lv instanceof LongConstant) {
} else if (lv instanceof NullConstant) {
} else if (lv instanceof StringConstant) {
} else if (lv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
if (((Local) rv).getType() instanceof IntegerType) {
rop = resolver.typeVariable((Local) rv);
}
} else if (rv instanceof DoubleConstant) {
} else if (rv instanceof FloatConstant) {
} else if (rv instanceof IntConstant) {
int value = ((IntConstant) rv).value;
if (value < -32768) {
rop = resolver.INT;
} else if (value < -128) {
rop = resolver.SHORT;
} else if (value < 0) {
rop = resolver.BYTE;
} else if (value < 2) {
rop = resolver.R0_1;
} else if (value < 128) {
rop = resolver.R0_127;
} else if (value < 32768) {
rop = resolver.R0_32767;
} else if (value < 65536) {
rop = resolver.CHAR;
} else {
rop = resolver.INT;
}
} else if (rv instanceof LongConstant) {
} else if (rv instanceof NullConstant) {
} else if (rv instanceof StringConstant) {
} else if (rv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
if (rop != null && lop != null) {
TypeVariable common = resolver.typeVariable();
if (rop != null)
rop.addParent(common);
if (lop != null)
lop.addParent(common);
}
}
}
public void caseLookupSwitchStmt(LookupSwitchStmt stmt) {
if (uses) {
Value key = stmt.getKey();
if (key instanceof Local) {
resolver.typeVariable((Local) key).addParent(resolver.INT);
}
}
}
public void caseNopStmt(NopStmt stmt) {
}
public void caseReturnStmt(ReturnStmt stmt) {
if (uses) {
if (stmt.getOp() instanceof Local) {
if (((Local) stmt.getOp()).getType() instanceof IntegerType) {
resolver.typeVariable((Local) stmt.getOp()).addParent(
resolver.typeVariable(stmtBody.getMethod().getReturnType()));
}
}
}
}
public void caseReturnVoidStmt(ReturnVoidStmt stmt) {
}
public void caseTableSwitchStmt(TableSwitchStmt stmt) {
if (uses) {
Value key = stmt.getKey();
if (key instanceof Local) {
resolver.typeVariable((Local) key).addParent(resolver.INT);
}
}
}
public void caseThrowStmt(ThrowStmt stmt) {
}
public void defaultCase(Stmt stmt) {
throw new RuntimeException("Unhandled statement type: " + stmt.getClass());
}
}
| src/soot/jimple/toolkits/typing/integer/ConstraintCollector.java | /* Soot - a J*va Optimization Framework
* Copyright (C) 1997-2000 Etienne Gagnon. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*
* Modified by the Sable Research Group and others 1997-1999.
* See the 'credits' file distributed with Soot for the complete list of
* contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot)
*/
package soot.jimple.toolkits.typing.integer;
import soot.ArrayType;
import soot.IntegerType;
import soot.Local;
import soot.NullType;
import soot.SootMethodRef;
import soot.Type;
import soot.Value;
import soot.jimple.AbstractStmtSwitch;
import soot.jimple.AddExpr;
import soot.jimple.AndExpr;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.BreakpointStmt;
import soot.jimple.CastExpr;
import soot.jimple.ClassConstant;
import soot.jimple.CmpExpr;
import soot.jimple.CmpgExpr;
import soot.jimple.CmplExpr;
import soot.jimple.ConditionExpr;
import soot.jimple.DivExpr;
import soot.jimple.DoubleConstant;
import soot.jimple.EnterMonitorStmt;
import soot.jimple.EqExpr;
import soot.jimple.ExitMonitorStmt;
import soot.jimple.FloatConstant;
import soot.jimple.GeExpr;
import soot.jimple.GotoStmt;
import soot.jimple.GtExpr;
import soot.jimple.IdentityStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceOfExpr;
import soot.jimple.IntConstant;
import soot.jimple.InterfaceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.JimpleBody;
import soot.jimple.LeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.LongConstant;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.LtExpr;
import soot.jimple.MulExpr;
import soot.jimple.NeExpr;
import soot.jimple.NegExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NopStmt;
import soot.jimple.NullConstant;
import soot.jimple.OrExpr;
import soot.jimple.RemExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.ShlExpr;
import soot.jimple.ShrExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.SubExpr;
import soot.jimple.TableSwitchStmt;
import soot.jimple.ThrowStmt;
import soot.jimple.UshrExpr;
import soot.jimple.VirtualInvokeExpr;
import soot.jimple.XorExpr;
class ConstraintCollector extends AbstractStmtSwitch {
private TypeResolver resolver;
private boolean uses; // if true, include use contraints
private JimpleBody stmtBody;
public ConstraintCollector(TypeResolver resolver, boolean uses) {
this.resolver = resolver;
this.uses = uses;
}
public void collect(Stmt stmt, JimpleBody stmtBody) {
this.stmtBody = stmtBody;
stmt.apply(this);
}
private void handleInvokeExpr(InvokeExpr ie) {
if (!uses)
return;
if (ie instanceof InterfaceInvokeExpr) {
InterfaceInvokeExpr invoke = (InterfaceInvokeExpr) ie;
SootMethodRef method = invoke.getMethodRef();
int count = invoke.getArgCount();
for (int i = 0; i < count; i++) {
if (invoke.getArg(i) instanceof Local) {
Local local = (Local) invoke.getArg(i);
if (local.getType() instanceof IntegerType) {
TypeVariable localType = resolver.typeVariable(local);
localType.addParent(resolver.typeVariable(method.parameterType(i)));
}
}
}
} else if (ie instanceof SpecialInvokeExpr) {
SpecialInvokeExpr invoke = (SpecialInvokeExpr) ie;
SootMethodRef method = invoke.getMethodRef();
int count = invoke.getArgCount();
for (int i = 0; i < count; i++) {
if (invoke.getArg(i) instanceof Local) {
Local local = (Local) invoke.getArg(i);
if (local.getType() instanceof IntegerType) {
TypeVariable localType = resolver.typeVariable(local);
localType.addParent(resolver.typeVariable(method.parameterType(i)));
}
}
}
} else if (ie instanceof VirtualInvokeExpr) {
VirtualInvokeExpr invoke = (VirtualInvokeExpr) ie;
SootMethodRef method = invoke.getMethodRef();
int count = invoke.getArgCount();
for (int i = 0; i < count; i++) {
if (invoke.getArg(i) instanceof Local) {
Local local = (Local) invoke.getArg(i);
if (local.getType() instanceof IntegerType) {
TypeVariable localType = resolver.typeVariable(local);
localType.addParent(resolver.typeVariable(method.parameterType(i)));
}
}
}
} else if (ie instanceof StaticInvokeExpr) {
StaticInvokeExpr invoke = (StaticInvokeExpr) ie;
SootMethodRef method = invoke.getMethodRef();
int count = invoke.getArgCount();
for (int i = 0; i < count; i++) {
if (invoke.getArg(i) instanceof Local) {
Local local = (Local) invoke.getArg(i);
if (local.getType() instanceof IntegerType) {
TypeVariable localType = resolver.typeVariable(local);
localType.addParent(resolver.typeVariable(method.parameterType(i)));
}
}
}
} else {
throw new RuntimeException("Unhandled invoke expression type: " + ie.getClass());
}
}
public void caseBreakpointStmt(BreakpointStmt stmt) {
// Do nothing
}
public void caseInvokeStmt(InvokeStmt stmt) {
handleInvokeExpr(stmt.getInvokeExpr());
}
public void caseAssignStmt(AssignStmt stmt) {
Value l = stmt.getLeftOp();
Value r = stmt.getRightOp();
TypeVariable left = null;
TypeVariable right = null;
// ******** LEFT ********
if (l instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) l;
Type baset = ((Local) ref.getBase()).getType();
if (baset instanceof ArrayType) {
ArrayType base = (ArrayType) baset;
Value index = ref.getIndex();
if (uses) {
if ((base.numDimensions == 1) && (base.baseType instanceof IntegerType)) {
left = resolver.typeVariable(base.baseType);
}
if (index instanceof Local) {
resolver.typeVariable((Local) index).addParent(resolver.INT);
}
}
}
} else if (l instanceof Local) {
if (((Local) l).getType() instanceof IntegerType) {
left = resolver.typeVariable((Local) l);
}
} else if (l instanceof InstanceFieldRef) {
if (uses) {
InstanceFieldRef ref = (InstanceFieldRef) l;
Type fieldType = ref.getFieldRef().type();
if (fieldType instanceof IntegerType) {
left = resolver.typeVariable(ref.getFieldRef().type());
}
}
} else if (l instanceof StaticFieldRef) {
if (uses) {
StaticFieldRef ref = (StaticFieldRef) l;
Type fieldType = ref.getFieldRef().type();
if (fieldType instanceof IntegerType) {
left = resolver.typeVariable(ref.getFieldRef().type());
}
}
} else {
throw new RuntimeException("Unhandled assignment left hand side type: " + l.getClass());
}
// ******** RIGHT ********
if (r instanceof ArrayRef) {
ArrayRef ref = (ArrayRef) r;
Type baset = ((Local) ref.getBase()).getType();
if (!(baset instanceof NullType)) {
Value index = ref.getIndex();
// Be careful, dex can do some weird object/array casting
if (baset instanceof ArrayType) {
ArrayType base = (ArrayType) baset;
if ((base.numDimensions == 1) && (base.baseType instanceof IntegerType)) {
right = resolver.typeVariable(base.baseType);
}
} else if (baset instanceof IntegerType)
right = resolver.typeVariable(baset);
if (uses)
if (index instanceof Local)
resolver.typeVariable((Local) index).addParent(resolver.INT);
}
} else if (r instanceof DoubleConstant) {
} else if (r instanceof FloatConstant) {
} else if (r instanceof IntConstant) {
int value = ((IntConstant) r).value;
if (value < -32768) {
right = resolver.INT;
} else if (value < -128) {
right = resolver.SHORT;
} else if (value < 0) {
right = resolver.BYTE;
} else if (value < 2) {
right = resolver.R0_1;
} else if (value < 128) {
right = resolver.R0_127;
} else if (value < 32768) {
right = resolver.R0_32767;
} else if (value < 65536) {
right = resolver.CHAR;
} else {
right = resolver.INT;
}
} else if (r instanceof LongConstant) {
} else if (r instanceof NullConstant) {
} else if (r instanceof StringConstant) {
} else if (r instanceof ClassConstant) {
} else if (r instanceof BinopExpr) {
// ******** BINOP EXPR ********
BinopExpr be = (BinopExpr) r;
Value lv = be.getOp1();
Value rv = be.getOp2();
TypeVariable lop = null;
TypeVariable rop = null;
// ******** LEFT ********
if (lv instanceof Local) {
if (((Local) lv).getType() instanceof IntegerType) {
lop = resolver.typeVariable((Local) lv);
}
} else if (lv instanceof DoubleConstant) {
} else if (lv instanceof FloatConstant) {
} else if (lv instanceof IntConstant) {
int value = ((IntConstant) lv).value;
if (value < -32768) {
lop = resolver.INT;
} else if (value < -128) {
lop = resolver.SHORT;
} else if (value < 0) {
lop = resolver.BYTE;
} else if (value < 2) {
lop = resolver.R0_1;
} else if (value < 128) {
lop = resolver.R0_127;
} else if (value < 32768) {
lop = resolver.R0_32767;
} else if (value < 65536) {
lop = resolver.CHAR;
} else {
lop = resolver.INT;
}
} else if (lv instanceof LongConstant) {
} else if (lv instanceof NullConstant) {
} else if (lv instanceof StringConstant) {
} else if (lv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
if (((Local) rv).getType() instanceof IntegerType) {
rop = resolver.typeVariable((Local) rv);
}
} else if (rv instanceof DoubleConstant) {
} else if (rv instanceof FloatConstant) {
} else if (rv instanceof IntConstant) {
int value = ((IntConstant) rv).value;
if (value < -32768) {
rop = resolver.INT;
} else if (value < -128) {
rop = resolver.SHORT;
} else if (value < 0) {
rop = resolver.BYTE;
} else if (value < 2) {
rop = resolver.R0_1;
} else if (value < 128) {
rop = resolver.R0_127;
} else if (value < 32768) {
rop = resolver.R0_32767;
} else if (value < 65536) {
rop = resolver.CHAR;
} else {
rop = resolver.INT;
}
} else if (rv instanceof LongConstant) {
} else if (rv instanceof NullConstant) {
} else if (rv instanceof StringConstant) {
} else if (rv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
if ((be instanceof AddExpr) || (be instanceof SubExpr) || (be instanceof DivExpr)
|| (be instanceof RemExpr) || (be instanceof MulExpr)) {
if (lop != null && rop != null) {
if (uses) {
if (lop.type() == null) {
lop.addParent(resolver.INT);
}
if (rop.type() == null) {
rop.addParent(resolver.INT);
}
}
right = resolver.INT;
}
} else if ((be instanceof AndExpr) || (be instanceof OrExpr) || (be instanceof XorExpr)) {
if (lop != null && rop != null) {
TypeVariable common = resolver.typeVariable();
if (rop != null)
rop.addParent(common);
if (lop != null)
lop.addParent(common);
right = common;
}
} else if (be instanceof ShlExpr) {
if (uses) {
if (lop != null && lop.type() == null) {
lop.addParent(resolver.INT);
}
if (rop.type() == null) {
rop.addParent(resolver.INT);
}
}
right = (lop == null) ? null : resolver.INT;
} else if ((be instanceof ShrExpr) || (be instanceof UshrExpr)) {
if (uses) {
if (lop != null && lop.type() == null) {
lop.addParent(resolver.INT);
}
if (rop.type() == null) {
rop.addParent(resolver.INT);
}
}
right = lop;
} else if ((be instanceof CmpExpr) || (be instanceof CmpgExpr) || (be instanceof CmplExpr)) {
right = resolver.BYTE;
} else if ((be instanceof EqExpr) || (be instanceof GeExpr) || (be instanceof GtExpr)
|| (be instanceof LeExpr) || (be instanceof LtExpr) || (be instanceof NeExpr)) {
if (uses) {
TypeVariable common = resolver.typeVariable();
if (rop != null)
rop.addParent(common);
if (lop != null)
lop.addParent(common);
}
right = resolver.BOOLEAN;
} else {
throw new RuntimeException("Unhandled binary expression type: " + be.getClass());
}
} else if (r instanceof CastExpr) {
CastExpr ce = (CastExpr) r;
if (ce.getCastType() instanceof IntegerType) {
right = resolver.typeVariable(ce.getCastType());
}
} else if (r instanceof InstanceOfExpr) {
right = resolver.BOOLEAN;
} else if (r instanceof InvokeExpr) {
InvokeExpr ie = (InvokeExpr) r;
handleInvokeExpr(ie);
if (ie.getMethodRef().returnType() instanceof IntegerType) {
right = resolver.typeVariable(ie.getMethodRef().returnType());
}
} else if (r instanceof NewArrayExpr) {
NewArrayExpr nae = (NewArrayExpr) r;
if (uses) {
Value size = nae.getSize();
if (size instanceof Local) {
TypeVariable var = resolver.typeVariable((Local) size);
var.addParent(resolver.INT);
}
}
} else if (r instanceof NewExpr) {
} else if (r instanceof NewMultiArrayExpr) {
NewMultiArrayExpr nmae = (NewMultiArrayExpr) r;
if (uses) {
for (int i = 0; i < nmae.getSizeCount(); i++) {
Value size = nmae.getSize(i);
if (size instanceof Local) {
TypeVariable var = resolver.typeVariable((Local) size);
var.addParent(resolver.INT);
}
}
}
} else if (r instanceof LengthExpr) {
right = resolver.INT;
} else if (r instanceof NegExpr) {
NegExpr ne = (NegExpr) r;
if (ne.getOp() instanceof Local) {
Local local = (Local) ne.getOp();
if (local.getType() instanceof IntegerType) {
if (uses) {
resolver.typeVariable(local).addParent(resolver.INT);
}
TypeVariable v = resolver.typeVariable();
v.addChild(resolver.BYTE);
v.addChild(resolver.typeVariable(local));
right = v;
}
} else if (ne.getOp() instanceof DoubleConstant) {
} else if (ne.getOp() instanceof FloatConstant) {
} else if (ne.getOp() instanceof IntConstant) {
int value = ((IntConstant) ne.getOp()).value;
if (value < -32768) {
right = resolver.INT;
} else if (value < -128) {
right = resolver.SHORT;
} else if (value < 0) {
right = resolver.BYTE;
} else if (value < 2) {
right = resolver.BYTE;
} else if (value < 128) {
right = resolver.BYTE;
} else if (value < 32768) {
right = resolver.SHORT;
} else if (value < 65536) {
right = resolver.INT;
} else {
right = resolver.INT;
}
} else if (ne.getOp() instanceof LongConstant) {
} else {
throw new RuntimeException("Unhandled neg expression operand type: " + ne.getOp().getClass());
}
} else if (r instanceof Local) {
Local local = (Local) r;
if (local.getType() instanceof IntegerType) {
right = resolver.typeVariable(local);
}
} else if (r instanceof InstanceFieldRef) {
InstanceFieldRef ref = (InstanceFieldRef) r;
if (ref.getFieldRef().type() instanceof IntegerType) {
right = resolver.typeVariable(ref.getFieldRef().type());
}
} else if (r instanceof StaticFieldRef) {
StaticFieldRef ref = (StaticFieldRef) r;
if (ref.getFieldRef().type() instanceof IntegerType) {
right = resolver.typeVariable(ref.getFieldRef().type());
}
} else {
throw new RuntimeException("Unhandled assignment right hand side type: " + r.getClass());
}
if (left != null && right != null && (left.type() == null || right.type() == null)) {
right.addParent(left);
}
}
public void caseIdentityStmt(IdentityStmt stmt) {
Value l = stmt.getLeftOp();
Value r = stmt.getRightOp();
if (l instanceof Local) {
if (((Local) l).getType() instanceof IntegerType) {
TypeVariable left = resolver.typeVariable((Local) l);
TypeVariable right = resolver.typeVariable(r.getType());
right.addParent(left);
}
}
}
public void caseEnterMonitorStmt(EnterMonitorStmt stmt) {
}
public void caseExitMonitorStmt(ExitMonitorStmt stmt) {
}
public void caseGotoStmt(GotoStmt stmt) {
}
public void caseIfStmt(IfStmt stmt) {
if (uses) {
ConditionExpr cond = (ConditionExpr) stmt.getCondition();
BinopExpr expr = cond;
Value lv = expr.getOp1();
Value rv = expr.getOp2();
TypeVariable lop = null;
TypeVariable rop = null;
// ******** LEFT ********
if (lv instanceof Local) {
if (((Local) lv).getType() instanceof IntegerType) {
lop = resolver.typeVariable((Local) lv);
}
} else if (lv instanceof DoubleConstant) {
} else if (lv instanceof FloatConstant) {
} else if (lv instanceof IntConstant) {
int value = ((IntConstant) lv).value;
if (value < -32768) {
lop = resolver.INT;
} else if (value < -128) {
lop = resolver.SHORT;
} else if (value < 0) {
lop = resolver.BYTE;
} else if (value < 2) {
lop = resolver.R0_1;
} else if (value < 128) {
lop = resolver.R0_127;
} else if (value < 32768) {
lop = resolver.R0_32767;
} else if (value < 65536) {
lop = resolver.CHAR;
} else {
lop = resolver.INT;
}
} else if (lv instanceof LongConstant) {
} else if (lv instanceof NullConstant) {
} else if (lv instanceof StringConstant) {
} else if (lv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression left operand type: " + lv.getClass());
}
// ******** RIGHT ********
if (rv instanceof Local) {
if (((Local) rv).getType() instanceof IntegerType) {
rop = resolver.typeVariable((Local) rv);
}
} else if (rv instanceof DoubleConstant) {
} else if (rv instanceof FloatConstant) {
} else if (rv instanceof IntConstant) {
int value = ((IntConstant) rv).value;
if (value < -32768) {
rop = resolver.INT;
} else if (value < -128) {
rop = resolver.SHORT;
} else if (value < 0) {
rop = resolver.BYTE;
} else if (value < 2) {
rop = resolver.R0_1;
} else if (value < 128) {
rop = resolver.R0_127;
} else if (value < 32768) {
rop = resolver.R0_32767;
} else if (value < 65536) {
rop = resolver.CHAR;
} else {
rop = resolver.INT;
}
} else if (rv instanceof LongConstant) {
} else if (rv instanceof NullConstant) {
} else if (rv instanceof StringConstant) {
} else if (rv instanceof ClassConstant) {
} else {
throw new RuntimeException("Unhandled binary expression right operand type: " + rv.getClass());
}
if (rop != null && lop != null) {
TypeVariable common = resolver.typeVariable();
if (rop != null)
rop.addParent(common);
if (lop != null)
lop.addParent(common);
}
}
}
public void caseLookupSwitchStmt(LookupSwitchStmt stmt) {
if (uses) {
Value key = stmt.getKey();
if (key instanceof Local) {
resolver.typeVariable((Local) key).addParent(resolver.INT);
}
}
}
public void caseNopStmt(NopStmt stmt) {
}
public void caseReturnStmt(ReturnStmt stmt) {
if (uses) {
if (stmt.getOp() instanceof Local) {
if (((Local) stmt.getOp()).getType() instanceof IntegerType) {
resolver.typeVariable((Local) stmt.getOp()).addParent(
resolver.typeVariable(stmtBody.getMethod().getReturnType()));
}
}
}
}
public void caseReturnVoidStmt(ReturnVoidStmt stmt) {
}
public void caseTableSwitchStmt(TableSwitchStmt stmt) {
if (uses) {
Value key = stmt.getKey();
if (key instanceof Local) {
resolver.typeVariable((Local) key).addParent(resolver.INT);
}
}
}
public void caseThrowStmt(ThrowStmt stmt) {
}
public void defaultCase(Stmt stmt) {
throw new RuntimeException("Unhandled statement type: " + stmt.getClass());
}
}
| simplified the constraint collector for integer types to also handle dynamic invoke expressions in response to #225
| src/soot/jimple/toolkits/typing/integer/ConstraintCollector.java | simplified the constraint collector for integer types to also handle dynamic invoke expressions in response to #225 | <ide><path>rc/soot/jimple/toolkits/typing/integer/ConstraintCollector.java
<ide> import soot.jimple.InstanceFieldRef;
<ide> import soot.jimple.InstanceOfExpr;
<ide> import soot.jimple.IntConstant;
<del>import soot.jimple.InterfaceInvokeExpr;
<ide> import soot.jimple.InvokeExpr;
<ide> import soot.jimple.InvokeStmt;
<ide> import soot.jimple.JimpleBody;
<ide> import soot.jimple.ReturnVoidStmt;
<ide> import soot.jimple.ShlExpr;
<ide> import soot.jimple.ShrExpr;
<del>import soot.jimple.SpecialInvokeExpr;
<ide> import soot.jimple.StaticFieldRef;
<del>import soot.jimple.StaticInvokeExpr;
<ide> import soot.jimple.Stmt;
<ide> import soot.jimple.StringConstant;
<ide> import soot.jimple.SubExpr;
<ide> import soot.jimple.TableSwitchStmt;
<ide> import soot.jimple.ThrowStmt;
<ide> import soot.jimple.UshrExpr;
<del>import soot.jimple.VirtualInvokeExpr;
<ide> import soot.jimple.XorExpr;
<ide>
<ide> class ConstraintCollector extends AbstractStmtSwitch {
<ide> if (!uses)
<ide> return;
<ide>
<del> if (ie instanceof InterfaceInvokeExpr) {
<del> InterfaceInvokeExpr invoke = (InterfaceInvokeExpr) ie;
<del> SootMethodRef method = invoke.getMethodRef();
<del> int count = invoke.getArgCount();
<del>
<del> for (int i = 0; i < count; i++) {
<del> if (invoke.getArg(i) instanceof Local) {
<del> Local local = (Local) invoke.getArg(i);
<del>
<del> if (local.getType() instanceof IntegerType) {
<del> TypeVariable localType = resolver.typeVariable(local);
<del>
<del> localType.addParent(resolver.typeVariable(method.parameterType(i)));
<del> }
<del> }
<del> }
<del> } else if (ie instanceof SpecialInvokeExpr) {
<del> SpecialInvokeExpr invoke = (SpecialInvokeExpr) ie;
<del> SootMethodRef method = invoke.getMethodRef();
<del> int count = invoke.getArgCount();
<del>
<del> for (int i = 0; i < count; i++) {
<del> if (invoke.getArg(i) instanceof Local) {
<del> Local local = (Local) invoke.getArg(i);
<del>
<del> if (local.getType() instanceof IntegerType) {
<del> TypeVariable localType = resolver.typeVariable(local);
<del>
<del> localType.addParent(resolver.typeVariable(method.parameterType(i)));
<del> }
<del> }
<del> }
<del> } else if (ie instanceof VirtualInvokeExpr) {
<del> VirtualInvokeExpr invoke = (VirtualInvokeExpr) ie;
<del> SootMethodRef method = invoke.getMethodRef();
<del> int count = invoke.getArgCount();
<del>
<del> for (int i = 0; i < count; i++) {
<del> if (invoke.getArg(i) instanceof Local) {
<del> Local local = (Local) invoke.getArg(i);
<del>
<del> if (local.getType() instanceof IntegerType) {
<del> TypeVariable localType = resolver.typeVariable(local);
<del>
<del> localType.addParent(resolver.typeVariable(method.parameterType(i)));
<del> }
<del> }
<del> }
<del> } else if (ie instanceof StaticInvokeExpr) {
<del> StaticInvokeExpr invoke = (StaticInvokeExpr) ie;
<del> SootMethodRef method = invoke.getMethodRef();
<del> int count = invoke.getArgCount();
<del>
<del> for (int i = 0; i < count; i++) {
<del> if (invoke.getArg(i) instanceof Local) {
<del> Local local = (Local) invoke.getArg(i);
<del>
<del> if (local.getType() instanceof IntegerType) {
<del> TypeVariable localType = resolver.typeVariable(local);
<del>
<del> localType.addParent(resolver.typeVariable(method.parameterType(i)));
<del> }
<del> }
<del> }
<del> } else {
<del> throw new RuntimeException("Unhandled invoke expression type: " + ie.getClass());
<add> SootMethodRef method = ie.getMethodRef();
<add> int count = ie.getArgCount();
<add>
<add> for (int i = 0; i < count; i++) {
<add> if (ie.getArg(i) instanceof Local) {
<add> Local local = (Local) ie.getArg(i);
<add> if (local.getType() instanceof IntegerType) {
<add> TypeVariable localType = resolver.typeVariable(local);
<add> localType.addParent(resolver.typeVariable(method.parameterType(i)));
<add> }
<add> }
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | a06c49e2f55e7844cee972adafa9f63d9795f11a | 0 | jordancheah/oryx,SwathiMystery/oryx,feynmanliang/oryx,ChuyuHsu/oryx,OryxProject/oryx,chen0031/oryx,srowen/oryx,nvoron23/oryx,OryxProject/oryx,nvoron23/oryx,SevenYoung/oryx,brummell/oryx,dsdinter/oryx,oncewang/oryx2,jordancheah/oryx,dsdinter/oryx,chen0031/oryx,ChuyuHsu/oryx,SevenYoung/oryx,bikash/oryx-1,brummell/oryx,srowen/oryx,santoshsahoo/oryx,SwathiMystery/oryx,oncewang/oryx2,feynmanliang/oryx,bikash/oryx-1,santoshsahoo/oryx | /*
* Copyright (c) 2014, Cloudera and Intel, Inc. All Rights Reserved.
*
* Cloudera, Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* This software 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.cloudera.oryx.ml;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import com.google.common.base.Preconditions;
import com.typesafe.config.Config;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.VoidFunction;
import org.apache.spark.rdd.RDD;
import org.dmg.pmml.PMML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.Tuple2;
import com.cloudera.oryx.common.collection.Pair;
import com.cloudera.oryx.common.pmml.PMMLUtils;
import com.cloudera.oryx.common.random.RandomManager;
import com.cloudera.oryx.lambda.BatchLayerUpdate;
import com.cloudera.oryx.lambda.TopicProducer;
import com.cloudera.oryx.ml.param.HyperParamValues;
import com.cloudera.oryx.ml.param.HyperParams;
/**
* A specialization of {@link BatchLayerUpdate} for machine learning-oriented
* update processes. This implementation contains the framework for test/train split
* for example, parameter optimization, and so on. Subclasses instead implement
* methods like {@link #buildModel(JavaSparkContext,JavaRDD,List,Path)} to create a PMML model and
* {@link #evaluate(JavaSparkContext,PMML,Path,JavaRDD)} to evaluate a model from
* held-out test data.
*/
public abstract class MLUpdate<M> implements BatchLayerUpdate<Object,M,String> {
private static final Logger log = LoggerFactory.getLogger(MLUpdate.class);
public static final String MODEL_FILE_NAME = "model.pmml.gz";
private final double testFraction;
private final int candidates;
private final int evalParallelism;
protected MLUpdate(Config config) {
this.testFraction = config.getDouble("oryx.ml.eval.test-fraction");
this.candidates = config.getInt("oryx.ml.eval.candidates");
this.evalParallelism = config.getInt("oryx.ml.eval.parallelism");
Preconditions.checkArgument(testFraction >= 0.0 && testFraction <= 1.0);
Preconditions.checkArgument(candidates > 0);
Preconditions.checkArgument(evalParallelism > 0);
}
protected final double getTestFraction() {
return testFraction;
}
/**
* @return a list of hyperparameter value ranges to try, one {@link HyperParamValues} per
* hyperparameter. Different combinations of the values derived from the list will be
* passed back into {@link #buildModel(JavaSparkContext,JavaRDD,List,Path)}
*/
public List<HyperParamValues<?>> getHyperParameterValues() {
return Collections.emptyList();
}
/**
* @param sparkContext active Spark Context
* @param trainData training data on which to build a model
* @param hyperParameters ordered list of hyper parameter values to use in building model
* @param candidatePath directory where additional model files can be written
* @return a {@link PMML} representation of a model trained on the given data
*/
public abstract PMML buildModel(JavaSparkContext sparkContext,
JavaRDD<M> trainData,
List<?> hyperParameters,
Path candidatePath);
/**
* Optionally, publish additional model-related information to the update topic,
* after the model has been written. This is needed only in specific cases, like the
* ALS algorithm, where the model serialization in PMML can't contain all of the info.
*
* @param sparkContext active Spark Context
* @param pmml model for which extra data should be written
* @param newData data that has arrived in current interval
* @param pastData all previously-known data (may be {@code null})
* @param modelParentPath directory containing model files, if applicable
* @param modelUpdateTopic message topic to write to
*/
public void publishAdditionalModelData(JavaSparkContext sparkContext,
PMML pmml,
JavaRDD<M> newData,
JavaRDD<M> pastData,
Path modelParentPath,
TopicProducer<String, String> modelUpdateTopic) {
// Do nothing by default
}
/**
* @param sparkContext active Spark Context
* @param model model to evaluate
* @param modelParentPath directory containing model files, if applicable
* @param testData data on which to test the model performance
* @return an evaluation of the model on the test data. Higher should mean "better"
*/
public abstract double evaluate(JavaSparkContext sparkContext,
PMML model,
Path modelParentPath,
JavaRDD<M> testData);
@Override
public void runUpdate(JavaSparkContext sparkContext,
long timestamp,
JavaPairRDD<Object,M> newKeyMessageData,
JavaPairRDD<Object,M> pastKeyMessageData,
String modelDirString,
TopicProducer<String,String> modelUpdateTopic)
throws IOException, InterruptedException {
Preconditions.checkNotNull(newKeyMessageData);
JavaRDD<M> newData = newKeyMessageData.values();
JavaRDD<M> pastData = pastKeyMessageData == null ? null : pastKeyMessageData.values();
VoidFunction<Iterator<M>> noOpFn = new VoidFunction<Iterator<M>>() {
@Override
public void call(Iterator<M> it) {
// do nothing
}
};
if (newData != null) {
newData.cache();
// This forces caching of the RDD. This shouldn't be necessary but we see some freezes
// when many workers try to materialize the RDDs at once. Hence the workaround.
newData.foreachPartition(noOpFn);
}
if (pastData != null) {
pastData.cache();
pastData.foreachPartition(noOpFn);
}
List<HyperParamValues<?>> hyperParamValues = getHyperParameterValues();
int valuesPerHyperParam = chooseValuesPerHyperParam(hyperParamValues.size());
List<List<?>> hyperParameterCombos =
HyperParams.chooseHyperParameterCombos(hyperParamValues,
candidates,
valuesPerHyperParam);
FileSystem fs = FileSystem.get(sparkContext.hadoopConfiguration());
Path modelDir = new Path(modelDirString);
Path tempModelPath = new Path(modelDir, ".temporary");
Path candidatesPath = new Path(tempModelPath, Long.toString(System.currentTimeMillis()));
fs.mkdirs(candidatesPath);
Path bestCandidatePath = findBestCandidatePath(
sparkContext, newData, pastData, hyperParameterCombos, candidatesPath);
Path finalPath = new Path(modelDir, Long.toString(System.currentTimeMillis()));
if (bestCandidatePath == null) {
log.info("Unable to build any model");
} else {
// Move best model into place
fs.rename(bestCandidatePath, finalPath);
}
// Then delete everything else
fs.delete(candidatesPath, true);
// Push PMML model onto update topic, if it exists
Path bestModelPath = new Path(finalPath, MODEL_FILE_NAME);
if (fs.exists(bestModelPath)) {
PMML bestModel;
try (InputStream in = new GZIPInputStream(fs.open(bestModelPath), 1 << 16)) {
bestModel = PMMLUtils.read(in);
}
modelUpdateTopic.send("MODEL", PMMLUtils.toString(bestModel));
publishAdditionalModelData(
sparkContext, bestModel, newData, pastData, finalPath, modelUpdateTopic);
}
if (newData != null) {
newData.unpersist();
}
if (pastData != null) {
pastData.unpersist();
}
}
/**
* @return smallest value such that pow(value, numParams) is at least the number of candidates
* requested to build. Returns 0 if numParams is less than 1.
*/
private int chooseValuesPerHyperParam(int numParams) {
if (numParams < 1) {
return 0;
}
int valuesPerHyperParam = 0;
int total;
do {
valuesPerHyperParam++;
total = 1;
for (int i = 0; i < numParams; i++) {
total *= valuesPerHyperParam;
}
} while (total < candidates);
return valuesPerHyperParam;
}
private Path findBestCandidatePath(JavaSparkContext sparkContext,
JavaRDD<M> newData,
JavaRDD<M> pastData,
List<List<?>> hyperParameterCombos,
Path candidatesPath) throws InterruptedException, IOException {
Map<Path,Double> pathToEval = new HashMap<>(candidates);
if (evalParallelism > 1) {
Collection<Future<Tuple2<Path,Double>>> futures = new ArrayList<>(candidates);
ExecutorService executor = Executors.newFixedThreadPool(evalParallelism);
try {
for (int i = 0; i < candidates; i++) {
futures.add(executor.submit(new BuildAndEvalWorker(
i, hyperParameterCombos, sparkContext, newData, pastData, candidatesPath)));
}
} finally {
executor.shutdown();
}
for (Future<Tuple2<Path,Double>> future : futures) {
Tuple2<Path,Double> pathEval;
try {
pathEval = future.get();
} catch (ExecutionException e) {
throw new IllegalStateException(e.getCause());
}
pathToEval.put(pathEval._1(), pathEval._2());
}
} else {
// Execute serially
for (int i = 0; i < candidates; i++) {
Tuple2<Path,Double> pathEval = new BuildAndEvalWorker(
i, hyperParameterCombos, sparkContext, newData, pastData, candidatesPath).call();
pathToEval.put(pathEval._1(), pathEval._2());
}
}
FileSystem fs = FileSystem.get(sparkContext.hadoopConfiguration());
Path bestCandidatePath = null;
double bestEval = Double.NEGATIVE_INFINITY;
for (Map.Entry<Path,Double> pathEval : pathToEval.entrySet()) {
Path path = pathEval.getKey();
Double eval = pathEval.getValue();
if ((bestCandidatePath == null || (eval != null && eval > bestEval)) &&
fs.exists(path)) {
log.info("Best eval / path is now {} / {}", eval ,path);
if (eval != null) {
bestEval = eval;
}
bestCandidatePath = path;
}
}
return bestCandidatePath;
}
final class BuildAndEvalWorker implements Callable<Tuple2<Path,Double>> {
private final int i;
private final List<List<?>> hyperParameterCombos;
private final JavaSparkContext sparkContext;
private final JavaRDD<M> newData;
private final JavaRDD<M> pastData;
private final Path candidatesPath;
BuildAndEvalWorker(int i,
List<List<?>> hyperParameterCombos,
JavaSparkContext sparkContext,
JavaRDD<M> newData,
JavaRDD<M> pastData,
Path candidatesPath) {
this.i = i;
this.hyperParameterCombos = hyperParameterCombos;
this.sparkContext = sparkContext;
this.newData = newData;
this.pastData = pastData;
this.candidatesPath = candidatesPath;
}
@Override
public Tuple2<Path,Double> call() throws IOException {
// % = cycle through combinations if needed
List<?> hyperParameters = hyperParameterCombos.get(i % hyperParameterCombos.size());
Path candidatePath = new Path(candidatesPath, Integer.toString(i));
log.info("Building candidate {} with params {}", i, hyperParameters);
Pair<JavaRDD<M>,JavaRDD<M>> trainTestData = splitTrainTest(newData, pastData);
JavaRDD<M> allTrainData = trainTestData.getFirst();
JavaRDD<M> testData = trainTestData.getSecond();
Double eval = null;
if (empty(allTrainData)) {
log.info("No train data to build a model");
} else {
PMML model = buildModel(sparkContext, allTrainData, hyperParameters, candidatePath);
if (model == null) {
log.info("Unable to build a model");
} else {
Path modelPath = new Path(candidatePath, MODEL_FILE_NAME);
log.info("Writing model to {}", modelPath);
FileSystem fs = FileSystem.get(sparkContext.hadoopConfiguration());
fs.mkdirs(candidatePath);
try (OutputStream out = new GZIPOutputStream(fs.create(modelPath), 1 << 16)) {
PMMLUtils.write(model, out);
}
if (empty(testData)) {
log.info("No test data available to evaluate model");
} else {
log.info("Evaluating model");
double thisEval = evaluate(sparkContext, model, candidatePath, testData);
eval = Double.isNaN(thisEval) ? null : thisEval;
}
}
}
log.info("Model eval for params {}: {} ({})", hyperParameters, eval, candidatePath);
return new Tuple2<>(candidatePath, eval);
}
}
private static boolean empty(JavaRDD<?> rdd) {
// Check is faster than count() == 0. Later, replace with RDD.isEmpty
return rdd == null || rdd.take(1).isEmpty();
}
private Pair<JavaRDD<M>,JavaRDD<M>> splitTrainTest(JavaRDD<M> newData, JavaRDD<M> pastData) {
Preconditions.checkNotNull(newData);
if (testFraction <= 0.0) {
return new Pair<>(pastData == null ? newData : newData.union(pastData), null);
}
if (testFraction >= 1.0) {
return new Pair<>(pastData, newData);
}
if (empty(newData)) {
return new Pair<>(pastData, null);
}
Pair<JavaRDD<M>,JavaRDD<M>> newTrainTest = splitNewDataToTrainTest(newData);
JavaRDD<M> newTrainData = newTrainTest.getFirst();
return new Pair<>(pastData == null ? newTrainData : newTrainData.union(pastData),
newTrainTest.getSecond());
}
/**
* Default implementation which randomly splits new data into train/test sets.
* This handles the case where {@link #getTestFraction()} is not 0 or 1.
*
* @param newData data that has arrived in the current input batch
* @return a {@link Pair} of train, test {@link RDD}s.
*/
protected Pair<JavaRDD<M>,JavaRDD<M>> splitNewDataToTrainTest(JavaRDD<M> newData) {
RDD<M>[] testTrainRDDs = newData.rdd().randomSplit(
new double[]{1.0 - testFraction, testFraction},
RandomManager.getRandom().nextLong());
return new Pair<>(newData.wrapRDD(testTrainRDDs[0]),
newData.wrapRDD(testTrainRDDs[1]));
}
}
| oryx-ml/src/main/java/com/cloudera/oryx/ml/MLUpdate.java | /*
* Copyright (c) 2014, Cloudera and Intel, Inc. All Rights Reserved.
*
* Cloudera, Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* This software 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.cloudera.oryx.ml;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import com.google.common.base.Preconditions;
import com.typesafe.config.Config;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.rdd.RDD;
import org.dmg.pmml.PMML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.Tuple2;
import com.cloudera.oryx.common.collection.Pair;
import com.cloudera.oryx.common.pmml.PMMLUtils;
import com.cloudera.oryx.common.random.RandomManager;
import com.cloudera.oryx.lambda.BatchLayerUpdate;
import com.cloudera.oryx.lambda.TopicProducer;
import com.cloudera.oryx.ml.param.HyperParamValues;
import com.cloudera.oryx.ml.param.HyperParams;
/**
* A specialization of {@link BatchLayerUpdate} for machine learning-oriented
* update processes. This implementation contains the framework for test/train split
* for example, parameter optimization, and so on. Subclasses instead implement
* methods like {@link #buildModel(JavaSparkContext,JavaRDD,List,Path)} to create a PMML model and
* {@link #evaluate(JavaSparkContext,PMML,Path,JavaRDD)} to evaluate a model from
* held-out test data.
*/
public abstract class MLUpdate<M> implements BatchLayerUpdate<Object,M,String> {
private static final Logger log = LoggerFactory.getLogger(MLUpdate.class);
public static final String MODEL_FILE_NAME = "model.pmml.gz";
private final double testFraction;
private final int candidates;
private final int evalParallelism;
protected MLUpdate(Config config) {
this.testFraction = config.getDouble("oryx.ml.eval.test-fraction");
this.candidates = config.getInt("oryx.ml.eval.candidates");
this.evalParallelism = config.getInt("oryx.ml.eval.parallelism");
Preconditions.checkArgument(testFraction >= 0.0 && testFraction <= 1.0);
Preconditions.checkArgument(candidates > 0);
Preconditions.checkArgument(evalParallelism > 0);
}
protected final double getTestFraction() {
return testFraction;
}
/**
* @return a list of hyperparameter value ranges to try, one {@link HyperParamValues} per
* hyperparameter. Different combinations of the values derived from the list will be
* passed back into {@link #buildModel(JavaSparkContext,JavaRDD,List,Path)}
*/
public List<HyperParamValues<?>> getHyperParameterValues() {
return Collections.emptyList();
}
/**
* @param sparkContext active Spark Context
* @param trainData training data on which to build a model
* @param hyperParameters ordered list of hyper parameter values to use in building model
* @param candidatePath directory where additional model files can be written
* @return a {@link PMML} representation of a model trained on the given data
*/
public abstract PMML buildModel(JavaSparkContext sparkContext,
JavaRDD<M> trainData,
List<?> hyperParameters,
Path candidatePath);
/**
* Optionally, publish additional model-related information to the update topic,
* after the model has been written. This is needed only in specific cases, like the
* ALS algorithm, where the model serialization in PMML can't contain all of the info.
*
* @param sparkContext active Spark Context
* @param pmml model for which extra data should be written
* @param newData data that has arrived in current interval
* @param pastData all previously-known data (may be {@code null})
* @param modelParentPath directory containing model files, if applicable
* @param modelUpdateTopic message topic to write to
*/
public void publishAdditionalModelData(JavaSparkContext sparkContext,
PMML pmml,
JavaRDD<M> newData,
JavaRDD<M> pastData,
Path modelParentPath,
TopicProducer<String, String> modelUpdateTopic) {
// Do nothing by default
}
/**
* @param sparkContext active Spark Context
* @param model model to evaluate
* @param modelParentPath directory containing model files, if applicable
* @param testData data on which to test the model performance
* @return an evaluation of the model on the test data. Higher should mean "better"
*/
public abstract double evaluate(JavaSparkContext sparkContext,
PMML model,
Path modelParentPath,
JavaRDD<M> testData);
@Override
public void runUpdate(JavaSparkContext sparkContext,
long timestamp,
JavaPairRDD<Object,M> newKeyMessageData,
JavaPairRDD<Object,M> pastKeyMessageData,
String modelDirString,
TopicProducer<String,String> modelUpdateTopic)
throws IOException, InterruptedException {
Preconditions.checkNotNull(newKeyMessageData);
JavaRDD<M> newData = newKeyMessageData.values();
JavaRDD<M> pastData = pastKeyMessageData == null ? null : pastKeyMessageData.values();
if (newData != null) {
newData.cache();
// This forces caching of the RDD. This shouldn't be necessary but we see some freezes
// when many workers try to materialize the RDDs at once. Hence the workaround.
newData.count();
}
if (pastData != null) {
pastData.cache();
pastData.count();
}
List<HyperParamValues<?>> hyperParamValues = getHyperParameterValues();
int valuesPerHyperParam = chooseValuesPerHyperParam(hyperParamValues.size());
List<List<?>> hyperParameterCombos =
HyperParams.chooseHyperParameterCombos(hyperParamValues,
candidates,
valuesPerHyperParam);
FileSystem fs = FileSystem.get(sparkContext.hadoopConfiguration());
Path modelDir = new Path(modelDirString);
Path tempModelPath = new Path(modelDir, ".temporary");
Path candidatesPath = new Path(tempModelPath, Long.toString(System.currentTimeMillis()));
fs.mkdirs(candidatesPath);
Path bestCandidatePath = findBestCandidatePath(
sparkContext, newData, pastData, hyperParameterCombos, candidatesPath);
Path finalPath = new Path(modelDir, Long.toString(System.currentTimeMillis()));
if (bestCandidatePath == null) {
log.info("Unable to build any model");
} else {
// Move best model into place
fs.rename(bestCandidatePath, finalPath);
}
// Then delete everything else
fs.delete(candidatesPath, true);
// Push PMML model onto update topic, if it exists
Path bestModelPath = new Path(finalPath, MODEL_FILE_NAME);
if (fs.exists(bestModelPath)) {
PMML bestModel;
try (InputStream in = new GZIPInputStream(fs.open(bestModelPath), 1 << 16)) {
bestModel = PMMLUtils.read(in);
}
modelUpdateTopic.send("MODEL", PMMLUtils.toString(bestModel));
publishAdditionalModelData(
sparkContext, bestModel, newData, pastData, finalPath, modelUpdateTopic);
}
if (newData != null) {
newData.unpersist();
}
if (pastData != null) {
pastData.unpersist();
}
}
/**
* @return smallest value such that pow(value, numParams) is at least the number of candidates
* requested to build. Returns 0 if numParams is less than 1.
*/
private int chooseValuesPerHyperParam(int numParams) {
if (numParams < 1) {
return 0;
}
int valuesPerHyperParam = 0;
int total;
do {
valuesPerHyperParam++;
total = 1;
for (int i = 0; i < numParams; i++) {
total *= valuesPerHyperParam;
}
} while (total < candidates);
return valuesPerHyperParam;
}
private Path findBestCandidatePath(JavaSparkContext sparkContext,
JavaRDD<M> newData,
JavaRDD<M> pastData,
List<List<?>> hyperParameterCombos,
Path candidatesPath) throws InterruptedException, IOException {
Map<Path,Double> pathToEval = new HashMap<>(candidates);
if (evalParallelism > 1) {
Collection<Future<Tuple2<Path,Double>>> futures = new ArrayList<>(candidates);
ExecutorService executor = Executors.newFixedThreadPool(evalParallelism);
try {
for (int i = 0; i < candidates; i++) {
futures.add(executor.submit(new BuildAndEvalWorker(
i, hyperParameterCombos, sparkContext, newData, pastData, candidatesPath)));
}
} finally {
executor.shutdown();
}
for (Future<Tuple2<Path,Double>> future : futures) {
Tuple2<Path,Double> pathEval;
try {
pathEval = future.get();
} catch (ExecutionException e) {
throw new IllegalStateException(e.getCause());
}
pathToEval.put(pathEval._1(), pathEval._2());
}
} else {
// Execute serially
for (int i = 0; i < candidates; i++) {
Tuple2<Path,Double> pathEval = new BuildAndEvalWorker(
i, hyperParameterCombos, sparkContext, newData, pastData, candidatesPath).call();
pathToEval.put(pathEval._1(), pathEval._2());
}
}
FileSystem fs = FileSystem.get(sparkContext.hadoopConfiguration());
Path bestCandidatePath = null;
double bestEval = Double.NEGATIVE_INFINITY;
for (Map.Entry<Path,Double> pathEval : pathToEval.entrySet()) {
Path path = pathEval.getKey();
Double eval = pathEval.getValue();
if ((bestCandidatePath == null || (eval != null && eval > bestEval)) &&
fs.exists(path)) {
log.info("Best eval / path is now {} / {}", eval ,path);
if (eval != null) {
bestEval = eval;
}
bestCandidatePath = path;
}
}
return bestCandidatePath;
}
final class BuildAndEvalWorker implements Callable<Tuple2<Path,Double>> {
private final int i;
private final List<List<?>> hyperParameterCombos;
private final JavaSparkContext sparkContext;
private final JavaRDD<M> newData;
private final JavaRDD<M> pastData;
private final Path candidatesPath;
BuildAndEvalWorker(int i,
List<List<?>> hyperParameterCombos,
JavaSparkContext sparkContext,
JavaRDD<M> newData,
JavaRDD<M> pastData,
Path candidatesPath) {
this.i = i;
this.hyperParameterCombos = hyperParameterCombos;
this.sparkContext = sparkContext;
this.newData = newData;
this.pastData = pastData;
this.candidatesPath = candidatesPath;
}
@Override
public Tuple2<Path,Double> call() throws IOException {
// % = cycle through combinations if needed
List<?> hyperParameters = hyperParameterCombos.get(i % hyperParameterCombos.size());
Path candidatePath = new Path(candidatesPath, Integer.toString(i));
log.info("Building candidate {} with params {}", i, hyperParameters);
Pair<JavaRDD<M>,JavaRDD<M>> trainTestData = splitTrainTest(newData, pastData);
JavaRDD<M> allTrainData = trainTestData.getFirst();
JavaRDD<M> testData = trainTestData.getSecond();
Double eval = null;
if (empty(allTrainData)) {
log.info("No train data to build a model");
} else {
PMML model = buildModel(sparkContext, allTrainData, hyperParameters, candidatePath);
if (model == null) {
log.info("Unable to build a model");
} else {
Path modelPath = new Path(candidatePath, MODEL_FILE_NAME);
log.info("Writing model to {}", modelPath);
FileSystem fs = FileSystem.get(sparkContext.hadoopConfiguration());
fs.mkdirs(candidatePath);
try (OutputStream out = new GZIPOutputStream(fs.create(modelPath), 1 << 16)) {
PMMLUtils.write(model, out);
}
if (empty(testData)) {
log.info("No test data available to evaluate model");
} else {
log.info("Evaluating model");
double thisEval = evaluate(sparkContext, model, candidatePath, testData);
eval = Double.isNaN(thisEval) ? null : thisEval;
}
}
}
log.info("Model eval for params {}: {} ({})", hyperParameters, eval, candidatePath);
return new Tuple2<>(candidatePath, eval);
}
}
private static boolean empty(JavaRDD<?> rdd) {
// Check is faster than count() == 0. Later, replace with RDD.isEmpty
return rdd == null || rdd.take(1).isEmpty();
}
private Pair<JavaRDD<M>,JavaRDD<M>> splitTrainTest(JavaRDD<M> newData, JavaRDD<M> pastData) {
Preconditions.checkNotNull(newData);
if (testFraction <= 0.0) {
return new Pair<>(pastData == null ? newData : newData.union(pastData), null);
}
if (testFraction >= 1.0) {
return new Pair<>(pastData, newData);
}
if (empty(newData)) {
return new Pair<>(pastData, null);
}
Pair<JavaRDD<M>,JavaRDD<M>> newTrainTest = splitNewDataToTrainTest(newData);
JavaRDD<M> newTrainData = newTrainTest.getFirst();
return new Pair<>(pastData == null ? newTrainData : newTrainData.union(pastData),
newTrainTest.getSecond());
}
/**
* Default implementation which randomly splits new data into train/test sets.
* This handles the case where {@link #getTestFraction()} is not 0 or 1.
*
* @param newData data that has arrived in the current input batch
* @return a {@link Pair} of train, test {@link RDD}s.
*/
protected Pair<JavaRDD<M>,JavaRDD<M>> splitNewDataToTrainTest(JavaRDD<M> newData) {
RDD<M>[] testTrainRDDs = newData.rdd().randomSplit(
new double[]{1.0 - testFraction, testFraction},
RandomManager.getRandom().nextLong());
return new Pair<>(newData.wrapRDD(testTrainRDDs[0]),
newData.wrapRDD(testTrainRDDs[1]));
}
}
| Slightly faster trick to materialize and cache RDD
| oryx-ml/src/main/java/com/cloudera/oryx/ml/MLUpdate.java | Slightly faster trick to materialize and cache RDD | <ide><path>ryx-ml/src/main/java/com/cloudera/oryx/ml/MLUpdate.java
<ide> import java.util.Collection;
<ide> import java.util.Collections;
<ide> import java.util.HashMap;
<add>import java.util.Iterator;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.concurrent.Callable;
<ide> import org.apache.spark.api.java.JavaPairRDD;
<ide> import org.apache.spark.api.java.JavaRDD;
<ide> import org.apache.spark.api.java.JavaSparkContext;
<add>import org.apache.spark.api.java.function.VoidFunction;
<ide> import org.apache.spark.rdd.RDD;
<ide> import org.dmg.pmml.PMML;
<ide> import org.slf4j.Logger;
<ide> JavaRDD<M> newData = newKeyMessageData.values();
<ide> JavaRDD<M> pastData = pastKeyMessageData == null ? null : pastKeyMessageData.values();
<ide>
<add> VoidFunction<Iterator<M>> noOpFn = new VoidFunction<Iterator<M>>() {
<add> @Override
<add> public void call(Iterator<M> it) {
<add> // do nothing
<add> }
<add> };
<add>
<ide> if (newData != null) {
<ide> newData.cache();
<ide> // This forces caching of the RDD. This shouldn't be necessary but we see some freezes
<ide> // when many workers try to materialize the RDDs at once. Hence the workaround.
<del> newData.count();
<add> newData.foreachPartition(noOpFn);
<ide> }
<ide> if (pastData != null) {
<ide> pastData.cache();
<del> pastData.count();
<add> pastData.foreachPartition(noOpFn);
<ide> }
<ide>
<ide> List<HyperParamValues<?>> hyperParamValues = getHyperParameterValues(); |
|
Java | apache-2.0 | 106529a2362f629aa1ebb6954f1519cc0572ef7b | 0 | diorcety/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,izonder/intellij-community,semonte/intellij-community,supersven/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,jagguli/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,caot/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,petteyg/intellij-community,robovm/robovm-studio,blademainer/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,fitermay/intellij-community,ibinti/intellij-community,izonder/intellij-community,retomerz/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,holmes/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,kool79/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,dslomov/intellij-community,apixandru/intellij-community,holmes/intellij-community,dslomov/intellij-community,da1z/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,kdwink/intellij-community,da1z/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,da1z/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,hurricup/intellij-community,holmes/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,robovm/robovm-studio,fnouama/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,FHannes/intellij-community,diorcety/intellij-community,holmes/intellij-community,asedunov/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,fitermay/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,da1z/intellij-community,FHannes/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,kdwink/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,apixandru/intellij-community,holmes/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,samthor/intellij-community,da1z/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,da1z/intellij-community,supersven/intellij-community,holmes/intellij-community,youdonghai/intellij-community,samthor/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,allotria/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,asedunov/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,holmes/intellij-community,kool79/intellij-community,nicolargo/intellij-community,signed/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,retomerz/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,petteyg/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,signed/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,allotria/intellij-community,semonte/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,caot/intellij-community,ryano144/intellij-community,allotria/intellij-community,ryano144/intellij-community,semonte/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,kool79/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,holmes/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,caot/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,da1z/intellij-community,robovm/robovm-studio,FHannes/intellij-community,robovm/robovm-studio,retomerz/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,fitermay/intellij-community,dslomov/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,samthor/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,samthor/intellij-community,dslomov/intellij-community,clumsy/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,caot/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,robovm/robovm-studio,ibinti/intellij-community,slisson/intellij-community,izonder/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,FHannes/intellij-community,apixandru/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,samthor/intellij-community,ibinti/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,semonte/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,signed/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,diorcety/intellij-community,kdwink/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,signed/intellij-community,dslomov/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,caot/intellij-community,robovm/robovm-studio,adedayo/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,amith01994/intellij-community,signed/intellij-community,dslomov/intellij-community,ryano144/intellij-community,vladmm/intellij-community,hurricup/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,da1z/intellij-community,petteyg/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,supersven/intellij-community,adedayo/intellij-community,retomerz/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,kdwink/intellij-community,salguarnieri/intellij-community,caot/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,xfournet/intellij-community,vladmm/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,fitermay/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,supersven/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,izonder/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,semonte/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,amith01994/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,jagguli/intellij-community,kdwink/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,supersven/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,caot/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,apixandru/intellij-community,slisson/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,FHannes/intellij-community,xfournet/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,caot/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,slisson/intellij-community,holmes/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,robovm/robovm-studio,izonder/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,kool79/intellij-community,clumsy/intellij-community,signed/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,caot/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,signed/intellij-community,kool79/intellij-community,wreckJ/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,slisson/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,supersven/intellij-community,adedayo/intellij-community,blademainer/intellij-community,ryano144/intellij-community,kdwink/intellij-community,da1z/intellij-community,asedunov/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,fitermay/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,izonder/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,izonder/intellij-community,kdwink/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,holmes/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,slisson/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,slisson/intellij-community,supersven/intellij-community,signed/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,ibinti/intellij-community,signed/intellij-community,hurricup/intellij-community,asedunov/intellij-community,jagguli/intellij-community,fnouama/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,petteyg/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community | /*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.impl;
import com.intellij.execution.*;
import com.intellij.execution.configuration.ConfigurationFactoryEx;
import com.intellij.execution.configurations.*;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.options.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.popup.*;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.*;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.labels.ActionLink;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.IconUtil;
import com.intellij.util.PlatformIcons;
import com.intellij.util.config.StorageAccessors;
import com.intellij.util.containers.*;
import com.intellij.util.containers.HashMap;
import com.intellij.util.ui.EditableModel;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.GridBag;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import gnu.trove.THashSet;
import net.miginfocom.swing.MigLayout;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.*;
import java.util.HashSet;
import java.util.List;
import static com.intellij.execution.impl.RunConfigurable.NodeKind.*;
import static com.intellij.ui.RowsDnDSupport.RefinedDropSupport.Position.*;
class RunConfigurable extends BaseConfigurable {
private static final Icon ADD_ICON = IconUtil.getAddIcon();
private static final Icon REMOVE_ICON = IconUtil.getRemoveIcon();
private static final Icon SHARED_ICON = IconLoader.getTransparentIcon(AllIcons.Nodes.Symlink, .6f);
private static final Icon NON_SHARED_ICON = EmptyIcon.ICON_16;
@NonNls private static final String DIVIDER_PROPORTION = "dividerProportion";
@NonNls private static final Object DEFAULTS = new Object() {
@Override
public String toString() {
return "Defaults";
}
};
private volatile boolean isDisposed = false;
private final Project myProject;
private RunDialogBase myRunDialog;
@NonNls final DefaultMutableTreeNode myRoot = new DefaultMutableTreeNode("Root");
final MyTreeModel myTreeModel = new MyTreeModel(myRoot);
final Tree myTree = new Tree(myTreeModel);
private final JPanel myRightPanel = new JPanel(new BorderLayout());
private final Splitter mySplitter = new Splitter(false);
private JPanel myWholePanel;
private final StorageAccessors myProperties = StorageAccessors.createGlobal("RunConfigurable");
private Configurable mySelectedConfigurable = null;
private static final Logger LOG = Logger.getInstance("#com.intellij.execution.impl.RunConfigurable");
private final JTextField myRecentsLimit = new JTextField("5", 2);
private final JCheckBox myConfirmation = new JCheckBox(ExecutionBundle.message("rerun.confirmation.checkbox"), true);
private final List<Pair<UnnamedConfigurable, JComponent>> myAdditionalSettings = new ArrayList<Pair<UnnamedConfigurable, JComponent>>();
private Map<ConfigurationFactory, Configurable> myStoredComponents = new HashMap<ConfigurationFactory, Configurable>();
private ToolbarDecorator myToolbarDecorator;
private boolean isFolderCreating;
private RunConfigurable.MyToolbarAddAction myAddAction = new MyToolbarAddAction();
public RunConfigurable(final Project project) {
this(project, null);
}
public RunConfigurable(final Project project, @Nullable final RunDialogBase runDialog) {
myProject = project;
myRunDialog = runDialog;
}
@Override
public String getDisplayName() {
return ExecutionBundle.message("run.configurable.display.name");
}
private void initTree() {
myTree.setRootVisible(false);
myTree.setShowsRootHandles(true);
UIUtil.setLineStyleAngled(myTree);
TreeUtil.installActions(myTree);
new TreeSpeedSearch(myTree, new Convertor<TreePath, String>() {
@Override
public String convert(TreePath o) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)o.getLastPathComponent();
final Object userObject = node.getUserObject();
if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
return ((RunnerAndConfigurationSettingsImpl)userObject).getName();
}
else if (userObject instanceof SingleConfigurationConfigurable) {
return ((SingleConfigurationConfigurable)userObject).getNameText();
}
else {
if (userObject instanceof ConfigurationType) {
return ((ConfigurationType)userObject).getDisplayName();
}
else if (userObject instanceof String) {
return (String)userObject;
}
}
return o.toString();
}
});
myTree.setCellRenderer(new ColoredTreeCellRenderer() {
@Override
public void customizeCellRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
if (value instanceof DefaultMutableTreeNode) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
final Object userObject = node.getUserObject();
Boolean shared = null;
if (userObject instanceof ConfigurationType) {
final ConfigurationType configurationType = (ConfigurationType)userObject;
append(configurationType.getDisplayName(), parent.isRoot() ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES);
setIcon(configurationType.getIcon());
}
else if (userObject == DEFAULTS) {
append("Defaults", SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
setIcon(AllIcons.General.Settings);
}
else if (userObject instanceof String) {//Folders
append((String)userObject, SimpleTextAttributes.REGULAR_ATTRIBUTES);
setIcon(AllIcons.Nodes.Folder);
}
else if (userObject instanceof ConfigurationFactory) {
append(((ConfigurationFactory)userObject).getName());
setIcon(((ConfigurationFactory)userObject).getIcon());
}
else {
final RunManagerImpl runManager = getRunManager();
RunnerAndConfigurationSettings configuration = null;
String name = null;
if (userObject instanceof SingleConfigurationConfigurable) {
final SingleConfigurationConfigurable<?> settings = (SingleConfigurationConfigurable)userObject;
RunnerAndConfigurationSettings configurationSettings;
configurationSettings = settings.getSettings();
configuration = configurationSettings;
name = settings.getNameText();
shared = settings.isStoreProjectConfiguration();
setIcon(ProgramRunnerUtil.getConfigurationIcon(configurationSettings, !settings.isValid()));
}
else if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
RunnerAndConfigurationSettings settings = (RunnerAndConfigurationSettings)userObject;
shared = runManager.isConfigurationShared(settings);
setIcon(RunManagerEx.getInstanceEx(myProject).getConfigurationIcon(settings));
configuration = settings;
name = configuration.getName();
}
if (configuration != null) {
append(name, configuration.isTemporary()
? SimpleTextAttributes.GRAY_ATTRIBUTES
: SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
}
if (shared != null) {
Icon icon = getIcon();
LayeredIcon layeredIcon = new LayeredIcon(2);
layeredIcon.setIcon(icon, 0, 0, 0);
layeredIcon.setIcon(shared ? SHARED_ICON : NON_SHARED_ICON, 1, 8, 0);
setIcon(layeredIcon);
setIconTextGap(0);
} else {
setIconTextGap(2);
}
}
}
});
final RunManagerEx manager = getRunManager();
final ConfigurationType[] factories = manager.getConfigurationFactories();
for (ConfigurationType type : factories) {
final List<RunnerAndConfigurationSettings> configurations = manager.getConfigurationSettingsList(type);
if (!configurations.isEmpty()) {
final DefaultMutableTreeNode typeNode = new DefaultMutableTreeNode(type);
myRoot.add(typeNode);
Map<String, DefaultMutableTreeNode> folderMapping = new HashMap<String, DefaultMutableTreeNode>();
int folderCounter = 0;
for (RunnerAndConfigurationSettings configuration : configurations) {
String folder = configuration.getFolderName();
if (folder != null) {
DefaultMutableTreeNode node = folderMapping.get(folder);
if (node == null) {
node = new DefaultMutableTreeNode(folder);
typeNode.insert(node, folderCounter);
folderCounter++;
folderMapping.put(folder, node);
}
node.add(new DefaultMutableTreeNode(configuration));
} else {
typeNode.add(new DefaultMutableTreeNode(configuration));
}
}
}
}
// add defaults
final DefaultMutableTreeNode defaults = new DefaultMutableTreeNode(DEFAULTS);
final ConfigurationType[] configurationTypes = RunManagerImpl.getInstanceImpl(myProject).getConfigurationFactories();
for (final ConfigurationType type : configurationTypes) {
if (!(type instanceof UnknownConfigurationType)) {
ConfigurationFactory[] configurationFactories = type.getConfigurationFactories();
DefaultMutableTreeNode typeNode = new DefaultMutableTreeNode(type);
defaults.add(typeNode);
if (configurationFactories.length != 1) {
for (ConfigurationFactory factory : configurationFactories) {
typeNode.add(new DefaultMutableTreeNode(factory));
}
}
}
}
if (defaults.getChildCount() > 0) myRoot.add(defaults);
myTree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
final TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
final Object userObject = getSafeUserObject(node);
if (userObject instanceof SingleConfigurationConfigurable) {
updateRightPanel((SingleConfigurationConfigurable<RunConfiguration>)userObject);
}
else if (userObject instanceof String) {
showFolderField(getSelectedConfigurationType(), node, (String)userObject);
}
else {
if (userObject instanceof ConfigurationType || userObject == DEFAULTS) {
final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
if (parent.isRoot()) {
drawPressAddButtonMessage(userObject == DEFAULTS ? null : (ConfigurationType)userObject);
}
else {
final ConfigurationType type = (ConfigurationType)userObject;
ConfigurationFactory[] factories = type.getConfigurationFactories();
if (factories.length == 1) {
final ConfigurationFactory factory = factories[0];
showTemplateConfigurable(factory);
}
else {
drawPressAddButtonMessage((ConfigurationType)userObject);
}
}
}
else if (userObject instanceof ConfigurationFactory) {
showTemplateConfigurable((ConfigurationFactory)userObject);
}
}
}
updateDialog();
}
});
myTree.registerKeyboardAction(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clickDefaultButton();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isDisposed) return;
myTree.requestFocusInWindow();
final RunnerAndConfigurationSettings settings = manager.getSelectedConfiguration();
if (settings != null) {
final Enumeration enumeration = myRoot.breadthFirstEnumeration();
while (enumeration.hasMoreElements()) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)enumeration.nextElement();
final Object userObject = node.getUserObject();
if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
final RunnerAndConfigurationSettings runnerAndConfigurationSettings = (RunnerAndConfigurationSettings)userObject;
final ConfigurationType configurationType = settings.getType();
if (configurationType != null &&
Comparing.strEqual(runnerAndConfigurationSettings.getConfiguration().getType().getId(), configurationType.getId()) &&
Comparing.strEqual(runnerAndConfigurationSettings.getConfiguration().getName(), settings.getName())) {
TreeUtil.selectInTree(node, true, myTree);
return;
}
}
}
}
else {
mySelectedConfigurable = null;
}
//TreeUtil.selectInTree(defaults, true, myTree);
drawPressAddButtonMessage(null);
}
});
sortTopLevelBranches();
((DefaultTreeModel)myTree.getModel()).reload();
}
private void showTemplateConfigurable(ConfigurationFactory factory) {
Configurable configurable = myStoredComponents.get(factory);
if (configurable == null){
configurable = new TemplateConfigurable(RunManagerImpl.getInstanceImpl(myProject).getConfigurationTemplate(factory));
myStoredComponents.put(factory, configurable);
configurable.reset();
}
updateRightPanel(configurable);
}
private void showFolderField(final ConfigurationType type, final DefaultMutableTreeNode node, final String folderName) {
myRightPanel.removeAll();
JPanel p = new JPanel(new MigLayout("ins " + myToolbarDecorator.getActionsPanel().getHeight() + " 5 0 0, flowx"));
final JTextField textField = new JTextField(folderName);
textField.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
node.setUserObject(textField.getText());
myTreeModel.reload(node);
}
});
p.add(new JLabel("Folder name:"), "gapright 5");
p.add(textField, "pushx, growx, wrap");
p.add(new JLabel(ExecutionBundle.message("run.configuration.rename.folder.disclaimer")), "gaptop 5, spanx 2");
myRightPanel.add(p);
myRightPanel.revalidate();
myRightPanel.repaint();
if (isFolderCreating) {
textField.selectAll();
textField.requestFocus();
}
}
private Object getSafeUserObject(DefaultMutableTreeNode node) {
Object userObject = node.getUserObject();
if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
final SingleConfigurationConfigurable<RunConfiguration> configurationConfigurable =
SingleConfigurationConfigurable.editSettings((RunnerAndConfigurationSettings)userObject, null);
installUpdateListeners(configurationConfigurable);
node.setUserObject(configurationConfigurable);
return configurationConfigurable;
}
return userObject;
}
public void setRunDialog(final RunDialogBase runDialog) {
myRunDialog = runDialog;
}
private void updateRightPanel(final Configurable configurable) {
myRightPanel.removeAll();
mySelectedConfigurable = configurable;
final JBScrollPane scrollPane = new JBScrollPane(configurable.createComponent());
scrollPane.setBorder(null);
myRightPanel.add(scrollPane, BorderLayout.CENTER);
if (configurable instanceof SingleConfigurationConfigurable) {
myRightPanel.add(((SingleConfigurationConfigurable)configurable).getValidationComponent(), BorderLayout.SOUTH);
}
setupDialogBounds();
}
private void sortTopLevelBranches() {
List<TreePath> expandedPaths = TreeUtil.collectExpandedPaths(myTree);
TreeUtil.sort(myRoot, new Comparator() {
@Override
public int compare(final Object o1, final Object o2) {
final Object userObject1 = ((DefaultMutableTreeNode)o1).getUserObject();
final Object userObject2 = ((DefaultMutableTreeNode)o2).getUserObject();
if (userObject1 instanceof ConfigurationType && userObject2 instanceof ConfigurationType) {
return ((ConfigurationType)userObject1).getDisplayName().compareTo(((ConfigurationType)userObject2).getDisplayName());
}
else if (userObject1 == DEFAULTS && userObject2 instanceof ConfigurationType) {
return 1;
}
else if (userObject2 == DEFAULTS && userObject1 instanceof ConfigurationType) {
return -1;
}
return 0;
}
});
TreeUtil.restoreExpandedPaths(myTree, expandedPaths);
}
private void update() {
updateDialog();
final TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath != null) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
myTreeModel.reload(node);
}
}
private void installUpdateListeners(final SingleConfigurationConfigurable<RunConfiguration> info) {
final boolean[] changed = new boolean[]{false};
info.getEditor().addSettingsEditorListener(new SettingsEditorListener<RunnerAndConfigurationSettings>() {
@Override
public void stateChanged(final SettingsEditor<RunnerAndConfigurationSettings> editor) {
update();
final RunConfiguration configuration = info.getConfiguration();
if (configuration instanceof LocatableConfiguration) {
final LocatableConfiguration runtimeConfiguration = (LocatableConfiguration)configuration;
if (runtimeConfiguration.isGeneratedName() && !changed[0]) {
try {
final LocatableConfiguration snapshot = (LocatableConfiguration)editor.getSnapshot().getConfiguration();
final String generatedName = snapshot.suggestedName();
if (generatedName != null && generatedName.length() > 0) {
info.setNameText(generatedName);
changed[0] = false;
}
}
catch (ConfigurationException ignore) {
}
}
}
setupDialogBounds();
}
});
info.addNameListener(new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
changed[0] = true;
update();
}
});
info.addSharedListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
changed[0] = true;
update();
}
});
}
private void drawPressAddButtonMessage(final ConfigurationType configurationType) {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
panel.setBorder(new EmptyBorder(30, 0, 0, 0));
panel.add(new JLabel("Press the"));
ActionLink addIcon = new ActionLink("", ADD_ICON, myAddAction);
addIcon.setBorder(new EmptyBorder(0, 0, 0, 5));
panel.add(addIcon);
final String configurationTypeDescription = configurationType != null
? configurationType.getConfigurationTypeDescription()
: ExecutionBundle.message("run.configuration.default.type.description");
panel.add(new JLabel(ExecutionBundle.message("empty.run.configuration.panel.text.label3", configurationTypeDescription)));
JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(panel, true);
myRightPanel.removeAll();
myRightPanel.add(scrollPane, BorderLayout.CENTER);
if (configurationType == null) {
JPanel settingsPanel = new JPanel(new GridBagLayout());
GridBag grid = new GridBag().setDefaultAnchor(GridBagConstraints.NORTHWEST);
for (Pair<UnnamedConfigurable, JComponent> each : myAdditionalSettings) {
settingsPanel.add(each.second, grid.nextLine().next());
}
settingsPanel.add(createSettingsPanel(), grid.nextLine().next());
JPanel wrapper = new JPanel(new BorderLayout());
wrapper.add(settingsPanel, BorderLayout.WEST);
wrapper.add(Box.createGlue(), BorderLayout.CENTER);
myRightPanel.add(wrapper, BorderLayout.SOUTH);
}
myRightPanel.revalidate();
myRightPanel.repaint();
}
private JPanel createLeftPanel() {
initTree();
MyRemoveAction removeAction = new MyRemoveAction();
MyMoveAction moveUpAction = new MyMoveAction(ExecutionBundle.message("move.up.action.name"), null, IconUtil.getMoveUpIcon(), -1);
MyMoveAction moveDownAction = new MyMoveAction(ExecutionBundle.message("move.down.action.name"), null, IconUtil.getMoveDownIcon(), 1);
myToolbarDecorator = ToolbarDecorator.createDecorator(myTree).setAsUsualTopToolbar()
.setAddAction(myAddAction).setAddActionName(ExecutionBundle.message("add.new.run.configuration.acrtion.name"))
.setRemoveAction(removeAction).setRemoveActionUpdater(removeAction)
.setRemoveActionName(ExecutionBundle.message("remove.run.configuration.action.name"))
.setMoveUpAction(moveUpAction).setMoveUpActionName(ExecutionBundle.message("move.up.action.name")).setMoveUpActionUpdater(moveUpAction)
.setMoveDownAction(moveDownAction).setMoveDownActionName(ExecutionBundle.message("move.down.action.name")).setMoveDownActionUpdater(moveDownAction)
.addExtraAction(AnActionButton.fromAction(new MyCopyAction()))
.addExtraAction(AnActionButton.fromAction(new MySaveAction()))
.addExtraAction(AnActionButton.fromAction(new MyEditDefaultsAction()))
.addExtraAction(AnActionButton.fromAction(new MyCreateFolderAction()))
.setButtonComparator(ExecutionBundle.message("add.new.run.configuration.acrtion.name"),
ExecutionBundle.message("remove.run.configuration.action.name"),
ExecutionBundle.message("copy.configuration.action.name"),
ExecutionBundle.message("action.name.save.configuration"),
ExecutionBundle.message("run.configuration.edit.default.configuration.settings.text"),
ExecutionBundle.message("move.up.action.name"),
ExecutionBundle.message("move.down.action.name"),
ExecutionBundle.message("run.configuration.create.folder.text")
).setForcedDnD();
return myToolbarDecorator.createPanel();
}
private JPanel createSettingsPanel() {
JPanel bottomPanel = new JPanel(new GridBagLayout());
GridBag g = new GridBag();
bottomPanel.add(myConfirmation, g.nextLine().coverLine());
bottomPanel.add(new JLabel("Temporary configurations limit:"), g.nextLine().next());
bottomPanel.add(myRecentsLimit, g.next().anchor(GridBagConstraints.WEST));
myRecentsLimit.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
setModified(true);
}
});
myConfirmation.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
setModified(true);
}
});
return bottomPanel;
}
@Nullable
private ConfigurationType getSelectedConfigurationType() {
final DefaultMutableTreeNode configurationTypeNode = getSelectedConfigurationTypeNode();
return configurationTypeNode != null ? (ConfigurationType)configurationTypeNode.getUserObject() : null;
}
@Override
public JComponent createComponent() {
for (RunConfigurationsSettings each : Extensions.getExtensions(RunConfigurationsSettings.EXTENSION_POINT)) {
UnnamedConfigurable configurable = each.createConfigurable();
myAdditionalSettings.add(Pair.create(configurable, configurable.createComponent()));
}
myWholePanel = new JPanel(new BorderLayout());
mySplitter.setFirstComponent(createLeftPanel());
mySplitter.setSecondComponent(myRightPanel);
myWholePanel.add(mySplitter, BorderLayout.CENTER);
updateDialog();
Dimension d = myWholePanel.getPreferredSize();
d.width = Math.max(d.width, 800);
d.height = Math.max(d.height, 600);
myWholePanel.setPreferredSize(d);
mySplitter.setProportion(myProperties.getFloat(DIVIDER_PROPORTION, 0.3f));
return myWholePanel;
}
@Override
public void reset() {
final RunManagerEx manager = getRunManager();
final RunManagerConfig config = manager.getConfig();
myRecentsLimit.setText(Integer.toString(config.getRecentsLimit()));
myConfirmation.setSelected(config.isRestartRequiresConfirmation());
for (Pair<UnnamedConfigurable, JComponent> each : myAdditionalSettings) {
each.first.reset();
}
setModified(false);
}
public Configurable getSelectedConfigurable() {
return mySelectedConfigurable;
}
@Override
public void apply() throws ConfigurationException {
updateActiveConfigurationFromSelected();
final RunManagerImpl manager = getRunManager();
final ConfigurationType[] types = manager.getConfigurationFactories();
List<ConfigurationType> configurationTypes = new ArrayList<ConfigurationType>();
for (int i = 0; i < myRoot.getChildCount(); i++) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)myRoot.getChildAt(i);
Object userObject = node.getUserObject();
if (userObject instanceof ConfigurationType) {
configurationTypes.add((ConfigurationType)userObject);
}
}
for (ConfigurationType type : types) {
if (!configurationTypes.contains(type))
configurationTypes.add(type);
}
for (ConfigurationType configurationType : configurationTypes) {
applyByType(configurationType);
}
try {
int i = Math.max(RunManagerConfig.MIN_RECENT_LIMIT, Integer.parseInt(myRecentsLimit.getText()));
int oldLimit = manager.getConfig().getRecentsLimit();
if (oldLimit != i) {
manager.getConfig().setRecentsLimit(i);
manager.checkRecentsLimit();
}
}
catch (NumberFormatException e) {
// ignore
}
manager.getConfig().setRestartRequiresConfirmation(myConfirmation.isSelected());
for (Configurable configurable : myStoredComponents.values()) {
if (configurable.isModified()){
configurable.apply();
}
}
for (Pair<UnnamedConfigurable, JComponent> each : myAdditionalSettings) {
each.first.apply();
}
manager.saveOrder();
setModified(false);
myTree.repaint();
}
protected void updateActiveConfigurationFromSelected() {
if (mySelectedConfigurable != null && mySelectedConfigurable instanceof SingleConfigurationConfigurable) {
RunnerAndConfigurationSettings settings =
(RunnerAndConfigurationSettings)((SingleConfigurationConfigurable)mySelectedConfigurable).getSettings();
getRunManager().setSelectedConfiguration(settings);
}
}
private void applyByType(@NotNull ConfigurationType type) throws ConfigurationException {
RunnerAndConfigurationSettings selectedSettings = getSelectedSettings();
int indexToMove = -1;
DefaultMutableTreeNode typeNode = getConfigurationTypeNode(type);
final RunManagerImpl manager = getRunManager();
final ArrayList<RunConfigurationBean> stableConfigurations = new ArrayList<RunConfigurationBean>();
if (typeNode != null) {
final Set<String> names = new HashSet<String>();
List<DefaultMutableTreeNode> configurationNodes = new ArrayList<DefaultMutableTreeNode>();
collectNodesRecursively(typeNode, configurationNodes, CONFIGURATION, TEMPORARY_CONFIGURATION);
for (DefaultMutableTreeNode node : configurationNodes) {
final Object userObject = node.getUserObject();
RunConfigurationBean configurationBean = null;
RunnerAndConfigurationSettings settings = null;
if (userObject instanceof SingleConfigurationConfigurable) {
final SingleConfigurationConfigurable configurable = (SingleConfigurationConfigurable)userObject;
settings = (RunnerAndConfigurationSettings)configurable.getSettings();
if (settings.isTemporary()) {
applyConfiguration(typeNode, configurable);
}
configurationBean = new RunConfigurationBean(configurable);
}
else if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
settings = (RunnerAndConfigurationSettings)userObject;
configurationBean = new RunConfigurationBean(settings,
manager.isConfigurationShared(settings),
manager.getBeforeRunTasks(settings.getConfiguration()));
}
if (configurationBean != null) {
final SingleConfigurationConfigurable configurable = configurationBean.getConfigurable();
final String nameText = configurable != null ? configurable.getNameText() : configurationBean.getSettings().getName();
if (!names.add(nameText)) {
TreeUtil.selectNode(myTree, node);
throw new ConfigurationException(type.getDisplayName() + " with name \'" + nameText + "\' already exists");
}
stableConfigurations.add(configurationBean);
if (settings == selectedSettings) {
indexToMove = stableConfigurations.size()-1;
}
}
}
List<DefaultMutableTreeNode> folderNodes = new ArrayList<DefaultMutableTreeNode>();
collectNodesRecursively(typeNode, folderNodes, FOLDER);
names.clear();
for (DefaultMutableTreeNode node : folderNodes) {
String folderName = (String)node.getUserObject();
if (folderName.isEmpty()) {
TreeUtil.selectNode(myTree, node);
throw new ConfigurationException("Folder name shouldn't be empty");
}
if (!names.add(folderName)) {
TreeUtil.selectNode(myTree, node);
throw new ConfigurationException("Folders name \'" + folderName + "\' is duplicated");
}
}
}
// try to apply all
for (RunConfigurationBean bean : stableConfigurations) {
final SingleConfigurationConfigurable configurable = bean.getConfigurable();
if (configurable != null) {
applyConfiguration(typeNode, configurable);
}
}
// if apply succeeded, update the list of configurations in RunManager
Set<RunnerAndConfigurationSettings> toDeleteSettings = new THashSet<RunnerAndConfigurationSettings>();
for (RunConfiguration each : manager.getConfigurationsList(type)) {
ContainerUtil.addIfNotNull(toDeleteSettings, manager.getSettings(each));
}
//Just saved as 'stable' configuration shouldn't stay between temporary ones (here we order model to save)
int shift = 0;
if (selectedSettings != null && selectedSettings.getType() == type) {
shift = adjustOrder();
}
if (shift != 0 && indexToMove != -1) {
stableConfigurations.add(indexToMove-shift, stableConfigurations.remove(indexToMove));
}
for (RunConfigurationBean each : stableConfigurations) {
toDeleteSettings.remove(each.getSettings());
manager.addConfiguration(each.getSettings(), each.isShared(), each.getStepsBeforeLaunch(), false);
}
for (RunnerAndConfigurationSettings each : toDeleteSettings) {
manager.removeConfiguration(each);
}
}
static void collectNodesRecursively(DefaultMutableTreeNode parentNode, List<DefaultMutableTreeNode> nodes, NodeKind... allowed) {
for (int i = 0; i < parentNode.getChildCount(); i++) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode)parentNode.getChildAt(i);
if (ArrayUtilRt.find(allowed, getKind(child)) != -1) {
nodes.add(child);
}
collectNodesRecursively(child, nodes, allowed);
}
}
@Nullable
private DefaultMutableTreeNode getConfigurationTypeNode(@NotNull final ConfigurationType type) {
for (int i = 0; i < myRoot.getChildCount(); i++) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)myRoot.getChildAt(i);
if (node.getUserObject() == type) return node;
}
return null;
}
private void applyConfiguration(DefaultMutableTreeNode typeNode, SingleConfigurationConfigurable<?> configurable) throws ConfigurationException {
try {
if (configurable != null) {
configurable.apply();
RunManagerImpl.getInstanceImpl(myProject).fireRunConfigurationChanged(configurable.getSettings());
}
}
catch (ConfigurationException e) {
for (int i = 0; i < typeNode.getChildCount(); i++) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)typeNode.getChildAt(i);
if (Comparing.equal(configurable, node.getUserObject())) {
TreeUtil.selectNode(myTree, node);
break;
}
}
throw e;
}
}
@Override
public boolean isModified() {
if (super.isModified()) return true;
final RunManagerImpl runManager = getRunManager();
final List<RunConfiguration> allConfigurations = runManager.getAllConfigurationsList();
final List<RunConfiguration> currentConfigurations = new ArrayList<RunConfiguration>();
for (int i = 0; i < myRoot.getChildCount(); i++) {
DefaultMutableTreeNode typeNode = (DefaultMutableTreeNode)myRoot.getChildAt(i);
final Object object = typeNode.getUserObject();
if (object instanceof ConfigurationType) {
final List<RunnerAndConfigurationSettings> configurationSettings = runManager.getConfigurationSettingsList(
(ConfigurationType)object);
List<DefaultMutableTreeNode> configurationNodes = new ArrayList<DefaultMutableTreeNode>();
collectNodesRecursively(typeNode, configurationNodes, CONFIGURATION, TEMPORARY_CONFIGURATION);
if (configurationSettings.size() != configurationNodes.size()) return true;
for (int j = 0; j < configurationNodes.size(); j++) {
DefaultMutableTreeNode configurationNode = configurationNodes.get(j);
final Object userObject = configurationNode.getUserObject();
if (userObject instanceof SingleConfigurationConfigurable) {
SingleConfigurationConfigurable configurable = (SingleConfigurationConfigurable)userObject;
if (!Comparing.strEqual(configurationSettings.get(j).getConfiguration().getName(), configurable.getConfiguration().getName())) {
return true;
}
if (configurable.isModified()) return true;
currentConfigurations.add(configurable.getConfiguration());
}
else if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
currentConfigurations.add(((RunnerAndConfigurationSettings)userObject).getConfiguration());
}
}
}
}
if (allConfigurations.size() != currentConfigurations.size() || !allConfigurations.containsAll(currentConfigurations)) return true;
for (Configurable configurable : myStoredComponents.values()) {
if (configurable.isModified()) return true;
}
for (Pair<UnnamedConfigurable, JComponent> each : myAdditionalSettings) {
if (each.first.isModified()) return true;
}
return false;
}
@Override
public void disposeUIResources() {
isDisposed = true;
for (Configurable configurable : myStoredComponents.values()) {
configurable.disposeUIResources();
}
myStoredComponents.clear();
for (Pair<UnnamedConfigurable, JComponent> each : myAdditionalSettings) {
each.first.disposeUIResources();
}
TreeUtil.traverseDepth(myRoot, new TreeUtil.Traverse() {
@Override
public boolean accept(Object node) {
if (node instanceof DefaultMutableTreeNode) {
final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node;
final Object userObject = treeNode.getUserObject();
if (userObject instanceof SingleConfigurationConfigurable) {
((SingleConfigurationConfigurable)userObject).disposeUIResources();
}
}
return true;
}
});
myRightPanel.removeAll();
myProperties.setFloat(DIVIDER_PROPORTION, mySplitter.getProportion());
mySplitter.dispose();
}
private void updateDialog() {
final Executor executor = myRunDialog != null ? myRunDialog.getExecutor() : null;
if (executor == null) return;
final StringBuilder buffer = new StringBuilder();
buffer.append(executor.getId());
final SingleConfigurationConfigurable<RunConfiguration> configuration = getSelectedConfiguration();
if (configuration != null) {
buffer.append(" - ");
buffer.append(configuration.getNameText());
}
myRunDialog.setOKActionEnabled(canRunConfiguration(configuration, executor));
myRunDialog.setTitle(buffer.toString());
}
private void setupDialogBounds() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
UIUtil.setupEnclosingDialogBounds(myWholePanel);
}
});
}
@Nullable
private SingleConfigurationConfigurable<RunConfiguration> getSelectedConfiguration() {
final TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath != null) {
final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
final Object userObject = treeNode.getUserObject();
if (userObject instanceof SingleConfigurationConfigurable) {
return (SingleConfigurationConfigurable<RunConfiguration>)userObject;
}
}
return null;
}
private static boolean canRunConfiguration(@Nullable SingleConfigurationConfigurable<RunConfiguration> configuration, final @NotNull Executor executor) {
try {
return configuration != null && RunManagerImpl.canRunConfiguration(configuration.getSnapshot(), executor);
}
catch (ConfigurationException e) {
return false;
}
}
RunManagerImpl getRunManager() {
return RunManagerImpl.getInstanceImpl(myProject);
}
@Override
public String getHelpTopic() {
final ConfigurationType type = getSelectedConfigurationType();
if (type != null) {
return "reference.dialogs.rundebug." + type.getId();
}
return "reference.dialogs.rundebug";
}
private void clickDefaultButton() {
if (myRunDialog != null) myRunDialog.clickDefaultButton();
}
@Nullable
private DefaultMutableTreeNode getSelectedConfigurationTypeNode() {
TreePath selectionPath = myTree.getSelectionPath();
DefaultMutableTreeNode node = selectionPath != null ? (DefaultMutableTreeNode)selectionPath.getLastPathComponent() : null;
while(node != null) {
Object userObject = node.getUserObject();
if (userObject instanceof ConfigurationType) {
return node;
}
node = (DefaultMutableTreeNode)node.getParent();
}
return null;
}
@NotNull
private DefaultMutableTreeNode getNode(int row) {
return (DefaultMutableTreeNode)myTree.getPathForRow(row).getLastPathComponent();
}
@Nullable
Trinity<Integer, Integer, RowsDnDSupport.RefinedDropSupport.Position> getAvailableDropPosition(int direction) {
int[] rows = myTree.getSelectionRows();
if (rows == null || rows.length != 1) {
return null;
}
int oldIndex = rows[0];
int newIndex = oldIndex + direction;
if (!getKind((DefaultMutableTreeNode)myTree.getPathForRow(oldIndex).getLastPathComponent()).supportsDnD())
return null;
while (newIndex > 0 && newIndex < myTree.getRowCount()) {
TreePath targetPath = myTree.getPathForRow(newIndex);
boolean allowInto = getKind((DefaultMutableTreeNode)targetPath.getLastPathComponent()) == FOLDER && !myTree.isExpanded(targetPath);
RowsDnDSupport.RefinedDropSupport.Position position = allowInto && myTreeModel.isDropInto(myTree, oldIndex, newIndex) ?
INTO :
direction > 0 ? BELOW : ABOVE;
DefaultMutableTreeNode oldNode = getNode(oldIndex);
DefaultMutableTreeNode newNode = getNode(newIndex);
if (oldNode.getParent() != newNode.getParent() && getKind(newNode) != FOLDER) {
RowsDnDSupport.RefinedDropSupport.Position copy = position;
if (position == BELOW) {
copy = ABOVE;
}
else if (position == ABOVE) {
copy = BELOW;
}
if (myTreeModel.canDrop(oldIndex, newIndex, copy)) {
return Trinity.create(oldIndex, newIndex, copy);
}
}
if (myTreeModel.canDrop(oldIndex, newIndex, position)) {
return Trinity.create(oldIndex, newIndex, position);
}
if (position == BELOW && newIndex < myTree.getRowCount() - 1 && myTreeModel.canDrop(oldIndex, newIndex + 1, ABOVE)) {
return Trinity.create(oldIndex, newIndex + 1, ABOVE);
}
if (position == ABOVE && newIndex > 1 && myTreeModel.canDrop(oldIndex, newIndex - 1, BELOW)) {
return Trinity.create(oldIndex, newIndex - 1, BELOW);
}
if (position == BELOW && myTreeModel.canDrop(oldIndex, newIndex, ABOVE)) {
return Trinity.create(oldIndex, newIndex, ABOVE);
}
if (position == ABOVE && myTreeModel.canDrop(oldIndex, newIndex, BELOW)) {
return Trinity.create(oldIndex, newIndex, BELOW);
}
newIndex += direction;
}
return null;
}
@NotNull
private static String createUniqueName(DefaultMutableTreeNode typeNode, @Nullable String baseName, NodeKind...kinds) {
String str = (baseName == null) ? ExecutionBundle.message("run.configuration.unnamed.name.prefix") : baseName;
List<DefaultMutableTreeNode> configurationNodes = new ArrayList<DefaultMutableTreeNode>();
collectNodesRecursively(typeNode, configurationNodes, kinds);
final ArrayList<String> currentNames = new ArrayList<String>();
for (DefaultMutableTreeNode node : configurationNodes) {
final Object userObject = node.getUserObject();
if (userObject instanceof SingleConfigurationConfigurable) {
currentNames.add(((SingleConfigurationConfigurable)userObject).getNameText());
}
else if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
currentNames.add(((RunnerAndConfigurationSettings)userObject).getName());
}
else if (userObject instanceof String) {
currentNames.add((String)userObject);
}
}
return RunManager.suggestUniqueName(str, currentNames);
}
private SingleConfigurationConfigurable<RunConfiguration> createNewConfiguration(final RunnerAndConfigurationSettings settings, final DefaultMutableTreeNode node) {
final SingleConfigurationConfigurable<RunConfiguration> configurationConfigurable =
SingleConfigurationConfigurable.editSettings(settings, null);
installUpdateListeners(configurationConfigurable);
DefaultMutableTreeNode nodeToAdd = new DefaultMutableTreeNode(configurationConfigurable);
myTreeModel.insertNodeInto(nodeToAdd, node, node.getChildCount());
TreeUtil.selectNode(myTree, nodeToAdd);
return configurationConfigurable;
}
private void createNewConfiguration(final ConfigurationFactory factory) {
DefaultMutableTreeNode node = null;
DefaultMutableTreeNode selectedNode = null;
TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath != null) {
selectedNode = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
}
DefaultMutableTreeNode typeNode = getConfigurationTypeNode(factory.getType());
if (typeNode == null) {
typeNode = new DefaultMutableTreeNode(factory.getType());
myRoot.add(typeNode);
sortTopLevelBranches();
((DefaultTreeModel)myTree.getModel()).reload();
}
node = typeNode;
if (selectedNode != null && typeNode.isNodeDescendant(selectedNode)) {
node = selectedNode;
if (getKind(node).isConfiguration()) {
node = (DefaultMutableTreeNode)node.getParent();
}
}
final RunnerAndConfigurationSettings settings = getRunManager().createConfiguration(createUniqueName(typeNode, null, CONFIGURATION, TEMPORARY_CONFIGURATION), factory);
if (factory instanceof ConfigurationFactoryEx) {
((ConfigurationFactoryEx)factory).onNewConfigurationCreated(settings.getConfiguration());
}
createNewConfiguration(settings, node);
}
private class MyToolbarAddAction extends AnAction implements AnActionButtonRunnable {
public MyToolbarAddAction() {
super(ExecutionBundle.message("add.new.run.configuration.acrtion.name"),
ExecutionBundle.message("add.new.run.configuration.acrtion.name"), ADD_ICON);
registerCustomShortcutSet(CommonShortcuts.INSERT, myTree);
}
@Override
public void actionPerformed(AnActionEvent e) {
showAddPopup(true);
}
@Override
public void run(AnActionButton button) {
showAddPopup(true);
}
private void showAddPopup(final boolean showApplicableTypesOnly) {
ConfigurationType[] allTypes = getRunManager().getConfigurationFactories(false);
final List<ConfigurationType> configurationTypes = getTypesToShow(showApplicableTypesOnly, allTypes);
Collections.sort(configurationTypes, new Comparator<ConfigurationType>() {
@Override
public int compare(final ConfigurationType type1, final ConfigurationType type2) {
return type1.getDisplayName().compareToIgnoreCase(type2.getDisplayName());
}
});
final int hiddenCount = allTypes.length - configurationTypes.size();
if (hiddenCount > 0) {
configurationTypes.add(null);
}
final ListPopup popup = JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<ConfigurationType>(
ExecutionBundle.message("add.new.run.configuration.acrtion.name"), configurationTypes) {
@Override
@NotNull
public String getTextFor(final ConfigurationType type) {
return type != null ? type.getDisplayName() : hiddenCount + " items more (irrelevant)...";
}
@Override
public boolean isSpeedSearchEnabled() {
return true;
}
@Override
public boolean canBeHidden(ConfigurationType value) {
return true;
}
@Override
public Icon getIconFor(final ConfigurationType type) {
return type != null ? type.getIcon() : EmptyIcon.ICON_16;
}
@Override
public PopupStep onChosen(final ConfigurationType type, final boolean finalChoice) {
if (hasSubstep(type)) {
return getSupStep(type);
}
if (type == null) {
return doFinalStep(new Runnable() {
@Override
public void run() {
showAddPopup(false);
}
});
}
final ConfigurationFactory[] factories = type.getConfigurationFactories();
if (factories.length > 0) {
createNewConfiguration(factories[0]);
}
return FINAL_CHOICE;
}
@Override
public int getDefaultOptionIndex() {
ConfigurationType type = getSelectedConfigurationType();
return type != null ? configurationTypes.indexOf(type) : super.getDefaultOptionIndex();
}
private ListPopupStep getSupStep(final ConfigurationType type) {
final ConfigurationFactory[] factories = type.getConfigurationFactories();
Arrays.sort(factories, new Comparator<ConfigurationFactory>() {
@Override
public int compare(final ConfigurationFactory factory1, final ConfigurationFactory factory2) {
return factory1.getName().compareToIgnoreCase(factory2.getName());
}
});
return new BaseListPopupStep<ConfigurationFactory>(
ExecutionBundle.message("add.new.run.configuration.action.name", type.getDisplayName()), factories) {
@Override
@NotNull
public String getTextFor(final ConfigurationFactory value) {
return value.getName();
}
@Override
public Icon getIconFor(final ConfigurationFactory factory) {
return factory.getIcon();
}
@Override
public PopupStep onChosen(final ConfigurationFactory factory, final boolean finalChoice) {
createNewConfiguration(factory);
return FINAL_CHOICE;
}
};
}
@Override
public boolean hasSubstep(final ConfigurationType type) {
return type != null && type.getConfigurationFactories().length > 1;
}
});
//new TreeSpeedSearch(myTree);
popup.showUnderneathOf(myToolbarDecorator.getActionsPanel());
}
private List<ConfigurationType> getTypesToShow(boolean showApplicableTypesOnly, ConfigurationType[] allTypes) {
if (showApplicableTypesOnly) {
List<ConfigurationType> applicableTypes = new ArrayList<ConfigurationType>();
for (ConfigurationType type : allTypes) {
if (isApplicable(type)) {
applicableTypes.add(type);
}
}
if (applicableTypes.size() < allTypes.length - 3) {
return applicableTypes;
}
}
return new ArrayList<ConfigurationType>(Arrays.asList(allTypes));
}
private boolean isApplicable(ConfigurationType type) {
for (ConfigurationFactory factory : type.getConfigurationFactories()) {
if (factory.isApplicable(myProject)) {
return true;
}
}
return false;
}
}
private class MyRemoveAction extends AnAction implements AnActionButtonRunnable, AnActionButtonUpdater{
public MyRemoveAction() {
super(ExecutionBundle.message("remove.run.configuration.action.name"),
ExecutionBundle.message("remove.run.configuration.action.name"), REMOVE_ICON);
registerCustomShortcutSet(CommonShortcuts.DELETE, myTree);
}
@Override
public void actionPerformed(AnActionEvent e) {
doRemove();
}
@Override
public void run(AnActionButton button) {
doRemove();
}
private void doRemove() {
TreePath[] selections = myTree.getSelectionPaths();
myTree.clearSelection();
int nodeIndexToSelect = -1;
DefaultMutableTreeNode parentToSelect = null;
Set<DefaultMutableTreeNode> changedParents = new HashSet<DefaultMutableTreeNode>();
boolean wasRootChanged = false;
for (TreePath each : selections) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)each.getLastPathComponent();
DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
NodeKind kind = getKind(node);
if (!kind.isConfiguration() && kind != FOLDER)
continue;
if (node.getUserObject() instanceof SingleConfigurationConfigurable) {
((SingleConfigurationConfigurable)node.getUserObject()).disposeUIResources();
}
nodeIndexToSelect = parent.getIndex(node);
parentToSelect = parent;
myTreeModel.removeNodeFromParent(node);
changedParents.add(parent);
if (kind == FOLDER) {
List<DefaultMutableTreeNode> children = new ArrayList<DefaultMutableTreeNode>();
for (int i = 0; i < node.getChildCount(); i++) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(i);
Object userObject = getSafeUserObject(child);
if (userObject instanceof SingleConfigurationConfigurable) {
((SingleConfigurationConfigurable)userObject).setFolderName(null);
}
children.add(0, child);
}
int confIndex = 0;
for (int i = 0; i < parent.getChildCount(); i++) {
if (getKind((DefaultMutableTreeNode)parent.getChildAt(i)).isConfiguration()) {
confIndex = i;
break;
}
}
for (DefaultMutableTreeNode child : children) {
if (getKind(child) == CONFIGURATION)
myTreeModel.insertNodeInto(child, parent, confIndex);
}
confIndex = parent.getChildCount();
for (int i = 0; i < parent.getChildCount(); i++) {
if (getKind((DefaultMutableTreeNode)parent.getChildAt(i)) == TEMPORARY_CONFIGURATION) {
confIndex = i;
break;
}
}
for (DefaultMutableTreeNode child : children) {
if (getKind(child) == TEMPORARY_CONFIGURATION)
myTreeModel.insertNodeInto(child, parent, confIndex);
}
}
if (parent.getChildCount() == 0 && parent.getUserObject() instanceof ConfigurationType) {
changedParents.remove(parent);
wasRootChanged = true;
nodeIndexToSelect = myRoot.getIndex(parent);
nodeIndexToSelect = Math.max(0, nodeIndexToSelect - 1);
parentToSelect = myRoot;
parent.removeFromParent();
}
}
if (wasRootChanged) {
((DefaultTreeModel)myTree.getModel()).reload();
} else {
for (DefaultMutableTreeNode each : changedParents) {
myTreeModel.reload(each);
myTree.expandPath(new TreePath(each));
}
}
mySelectedConfigurable = null;
if (myRoot.getChildCount() == 0) {
drawPressAddButtonMessage(null);
}
else {
if (parentToSelect.getChildCount() > 0) {
TreeNode nodeToSelect = nodeIndexToSelect < parentToSelect.getChildCount()
? parentToSelect.getChildAt(nodeIndexToSelect)
: parentToSelect.getChildAt(nodeIndexToSelect - 1);
TreeUtil.selectInTree((DefaultMutableTreeNode)nodeToSelect, true, myTree);
}
}
}
@Override
public void update(AnActionEvent e) {
boolean enabled = isEnabled(e);
e.getPresentation().setEnabled(enabled);
}
@Override
public boolean isEnabled(AnActionEvent e) {
boolean enabled = false;
TreePath[] selections = myTree.getSelectionPaths();
if (selections != null) {
for (TreePath each : selections) {
NodeKind kind = getKind((DefaultMutableTreeNode)each.getLastPathComponent());
if (kind.isConfiguration() || kind == FOLDER) {
enabled = true;
break;
}
}
}
return enabled;
}
}
private class MyCopyAction extends AnAction {
public MyCopyAction() {
super(ExecutionBundle.message("copy.configuration.action.name"),
ExecutionBundle.message("copy.configuration.action.name"),
PlatformIcons.COPY_ICON);
final AnAction action = ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_DUPLICATE);
registerCustomShortcutSet(action.getShortcutSet(), myTree);
}
@Override
public void actionPerformed(AnActionEvent e) {
final SingleConfigurationConfigurable<RunConfiguration> configuration = getSelectedConfiguration();
LOG.assertTrue(configuration != null);
try {
final DefaultMutableTreeNode typeNode = getSelectedConfigurationTypeNode();
final RunnerAndConfigurationSettings settings = configuration.getSnapshot();
final String copyName = createUniqueName(typeNode, configuration.getNameText(), CONFIGURATION, TEMPORARY_CONFIGURATION);
settings.setName(copyName);
final ConfigurationFactory factory = settings.getFactory();
if (factory instanceof ConfigurationFactoryEx) {
((ConfigurationFactoryEx)factory).onConfigurationCopied(settings.getConfiguration());
}
final SingleConfigurationConfigurable<RunConfiguration> configurable = createNewConfiguration(settings, typeNode);
IdeFocusManager.getInstance(myProject).requestFocus(configurable.getNameTextField(), true);
configurable.getNameTextField().setSelectionStart(0);
configurable.getNameTextField().setSelectionEnd(copyName.length());
}
catch (ConfigurationException e1) {
Messages.showErrorDialog(myToolbarDecorator.getActionsPanel(), e1.getMessage(), e1.getTitle());
}
}
@Override
public void update(AnActionEvent e) {
final SingleConfigurationConfigurable<RunConfiguration> configuration = getSelectedConfiguration();
e.getPresentation().setEnabled(configuration != null && !(configuration.getConfiguration() instanceof UnknownRunConfiguration));
}
}
private class MySaveAction extends AnAction {
public MySaveAction() {
super(ExecutionBundle.message("action.name.save.configuration"), null, AllIcons.Actions.Menu_saveall);
}
@Override
public void actionPerformed(final AnActionEvent e) {
final SingleConfigurationConfigurable<RunConfiguration> configurationConfigurable = getSelectedConfiguration();
LOG.assertTrue(configurationConfigurable != null);
try {
configurationConfigurable.apply();
}
catch (ConfigurationException e1) {
//do nothing
}
final RunnerAndConfigurationSettings originalConfiguration = configurationConfigurable.getSettings();
if (originalConfiguration.isTemporary()) {
getRunManager().makeStable(originalConfiguration);
adjustOrder();
}
myTree.repaint();
}
@Override
public void update(final AnActionEvent e) {
final SingleConfigurationConfigurable<RunConfiguration> configuration = getSelectedConfiguration();
final Presentation presentation = e.getPresentation();
final boolean enabled;
if (configuration == null) {
enabled = false;
} else {
RunnerAndConfigurationSettings settings = configuration.getSettings();
enabled = settings != null && settings.isTemporary();
}
presentation.setEnabled(enabled);
presentation.setVisible(enabled);
}
}
/**
* Just saved as 'stable' configuration shouldn't stay between temporary ones (here we order nodes in JTree only)
* @return shift (positive) for move configuration "up" to other stable configurations. Zero means "there is nothing to change"
*/
private int adjustOrder() {
TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath == null)
return 0;
final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
RunnerAndConfigurationSettings selectedSettings = getSettings(treeNode);
if (selectedSettings == null || selectedSettings.isTemporary())
return 0;
MutableTreeNode parent = (MutableTreeNode)treeNode.getParent();
int initialPosition = parent.getIndex(treeNode);
int position = initialPosition;
DefaultMutableTreeNode node = treeNode.getPreviousSibling();
while (node != null) {
RunnerAndConfigurationSettings settings = getSettings(node);
if (settings != null && settings.isTemporary()) {
position--;
} else {
break;
}
node = node.getPreviousSibling();
}
for (int i = 0; i < initialPosition - position; i++) {
TreeUtil.moveSelectedRow(myTree, -1);
}
return initialPosition - position;
}
private class MyMoveAction extends AnAction implements AnActionButtonRunnable, AnActionButtonUpdater {
private final int myDirection;
protected MyMoveAction(String text, String description, Icon icon, int direction) {
super(text, description, icon);
myDirection = direction;
}
@Override
public void actionPerformed(final AnActionEvent e) {
doMove();
}
private void doMove() {
Trinity<Integer, Integer, RowsDnDSupport.RefinedDropSupport.Position> dropPosition = getAvailableDropPosition(myDirection);
if (dropPosition != null) {
myTreeModel.drop(dropPosition.first, dropPosition.second, dropPosition.third);
}
}
@Override
public void run(AnActionButton button) {
doMove();
}
@Override
public void update(final AnActionEvent e) {
e.getPresentation().setEnabled(isEnabled(e));
}
@Override
public boolean isEnabled(AnActionEvent e) {
return getAvailableDropPosition(myDirection) != null;
}
}
private class MyEditDefaultsAction extends AnAction {
public MyEditDefaultsAction() {
super(ExecutionBundle.message("run.configuration.edit.default.configuration.settings.text"),
ExecutionBundle.message("run.configuration.edit.default.configuration.settings.description"), AllIcons.General.Settings);
}
@Override
public void actionPerformed(final AnActionEvent e) {
TreeNode defaults = TreeUtil.findNodeWithObject(DEFAULTS, myTree.getModel(), myRoot);
if (defaults != null) {
final ConfigurationType configurationType = getSelectedConfigurationType();
if (configurationType != null) {
defaults = TreeUtil.findNodeWithObject(configurationType, myTree.getModel(), defaults);
}
final DefaultMutableTreeNode defaultsNode = (DefaultMutableTreeNode)defaults;
if (defaultsNode == null) {
return;
}
final TreePath path = TreeUtil.getPath(myRoot, defaultsNode);
myTree.expandPath(path);
TreeUtil.selectInTree(defaultsNode, true, myTree);
myTree.scrollPathToVisible(path);
}
}
@Override
public void update(AnActionEvent e) {
boolean isEnabled = TreeUtil.findNodeWithObject(DEFAULTS, myTree.getModel(), myRoot) != null;
TreePath path = myTree.getSelectionPath();
if (path != null) {
Object o = path.getLastPathComponent();
if (o instanceof DefaultMutableTreeNode && ((DefaultMutableTreeNode)o).getUserObject().equals(DEFAULTS)) {
isEnabled = false;
}
o = path.getParentPath().getLastPathComponent();
if (o instanceof DefaultMutableTreeNode && ((DefaultMutableTreeNode)o).getUserObject().equals(DEFAULTS)) {
isEnabled = false;
}
}
e.getPresentation().setEnabled(isEnabled);
}
}
private class MyCreateFolderAction extends AnAction {
private MyCreateFolderAction() {
super(ExecutionBundle.message("run.configuration.create.folder.text"),
ExecutionBundle.message("run.configuration.create.folder.description"), AllIcons.Nodes.Folder);
}
@Override
public void actionPerformed(AnActionEvent e) {
final ConfigurationType type = getSelectedConfigurationType();
if (type == null) {
return;
}
final DefaultMutableTreeNode[] selectedNodes = getSelectedNodes();
DefaultMutableTreeNode typeNode = getConfigurationTypeNode(type);
if (typeNode == null) {
return;
}
String folderName = createUniqueName(typeNode, "New Folder", FOLDER);
List<DefaultMutableTreeNode> folders = new ArrayList<DefaultMutableTreeNode>();
collectNodesRecursively(getConfigurationTypeNode(type), folders, FOLDER);
final DefaultMutableTreeNode folderNode = new DefaultMutableTreeNode(folderName);
myTreeModel.insertNodeInto(folderNode, typeNode, folders.size());
isFolderCreating = true;
try {
for (DefaultMutableTreeNode node : selectedNodes) {
int folderRow = myTree.getRowForPath(new TreePath(folderNode.getPath()));
int rowForPath = myTree.getRowForPath(new TreePath(node.getPath()));
if (getKind(node).isConfiguration() && myTreeModel.canDrop(rowForPath, folderRow, INTO)) {
myTreeModel.drop(rowForPath, folderRow, INTO);
}
}
myTree.setSelectionPath(new TreePath(folderNode.getPath()));
}
finally {
isFolderCreating = false;
}
}
@Override
public void update(AnActionEvent e) {
boolean isEnabled = false;
boolean toMove = false;
DefaultMutableTreeNode[] selectedNodes = getSelectedNodes();
ConfigurationType selectedType = null;
for (DefaultMutableTreeNode node : selectedNodes) {
ConfigurationType type = getType(node);
if (selectedType == null) {
selectedType = type;
} else {
if (!Comparing.equal(type, selectedType)) {
isEnabled = false;
break;
}
}
NodeKind kind = getKind(node);
if (kind.isConfiguration() || (kind == CONFIGURATION_TYPE && node.getParent() == myRoot) || kind == FOLDER) {
isEnabled = true;
}
if (kind.isConfiguration()) {
toMove = true;
}
}
e.getPresentation().setText(ExecutionBundle.message("run.configuration.create.folder.description" + (toMove ? ".move" : "")));
e.getPresentation().setEnabled(isEnabled);
}
}
@Nullable
private static ConfigurationType getType(DefaultMutableTreeNode node) {
while (node != null) {
if (node.getUserObject() instanceof ConfigurationType) {
return (ConfigurationType)node.getUserObject();
}
node = (DefaultMutableTreeNode)node.getParent();
}
return null;
}
@NotNull
private DefaultMutableTreeNode[] getSelectedNodes() {
return myTree.getSelectedNodes(DefaultMutableTreeNode.class, null);
}
@Nullable
private DefaultMutableTreeNode getSelectedNode() {
DefaultMutableTreeNode[] nodes = myTree.getSelectedNodes(DefaultMutableTreeNode.class, null);
return nodes.length > 1 ? nodes[0] : null;
}
@Nullable
private RunnerAndConfigurationSettings getSelectedSettings() {
TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath == null)
return null;
return getSettings((DefaultMutableTreeNode)selectionPath.getLastPathComponent());
}
@Nullable
private static RunnerAndConfigurationSettings getSettings(DefaultMutableTreeNode treeNode) {
if (treeNode == null)
return null;
RunnerAndConfigurationSettings settings = null;
if (treeNode.getUserObject() instanceof SingleConfigurationConfigurable) {
settings = (RunnerAndConfigurationSettings)((SingleConfigurationConfigurable)treeNode.getUserObject()).getSettings();
}
if (treeNode.getUserObject() instanceof RunnerAndConfigurationSettings) {
settings = (RunnerAndConfigurationSettings)treeNode.getUserObject();
}
return settings;
}
private static class RunConfigurationBean {
private final RunnerAndConfigurationSettings mySettings;
private final boolean myShared;
private final List<BeforeRunTask> myStepsBeforeLaunch;
private final SingleConfigurationConfigurable myConfigurable;
public RunConfigurationBean(final RunnerAndConfigurationSettings settings,
final boolean shared,
final List<BeforeRunTask> stepsBeforeLaunch) {
mySettings = settings;
myShared = shared;
myStepsBeforeLaunch = Collections.unmodifiableList(stepsBeforeLaunch);
myConfigurable = null;
}
public RunConfigurationBean(final SingleConfigurationConfigurable configurable) {
myConfigurable = configurable;
mySettings = (RunnerAndConfigurationSettings)myConfigurable.getSettings();
final ConfigurationSettingsEditorWrapper editorWrapper = (ConfigurationSettingsEditorWrapper)myConfigurable.getEditor();
myShared = configurable.isStoreProjectConfiguration();
myStepsBeforeLaunch = editorWrapper.getStepsBeforeLaunch();
}
public RunnerAndConfigurationSettings getSettings() {
return mySettings;
}
public boolean isShared() {
return myShared;
}
public List<BeforeRunTask> getStepsBeforeLaunch() {
return myStepsBeforeLaunch;
}
public SingleConfigurationConfigurable getConfigurable() {
return myConfigurable;
}
@Override
public String toString() {
return String.valueOf(mySettings);
}
}
public interface RunDialogBase {
void setOKActionEnabled(boolean isEnabled);
@Nullable
Executor getExecutor();
void setTitle(String title);
void clickDefaultButton();
}
enum NodeKind {
CONFIGURATION_TYPE, FOLDER, CONFIGURATION, TEMPORARY_CONFIGURATION, UNKNOWN;
boolean supportsDnD() {
return this == FOLDER || this == CONFIGURATION || this == TEMPORARY_CONFIGURATION;
}
boolean isConfiguration() {
return this == CONFIGURATION | this == TEMPORARY_CONFIGURATION;
}
}
@NotNull
static NodeKind getKind(@Nullable DefaultMutableTreeNode node) {
if (node == null)
return UNKNOWN;
Object userObject = node.getUserObject();
if (userObject instanceof SingleConfigurationConfigurable || userObject instanceof RunnerAndConfigurationSettings) {
RunnerAndConfigurationSettings settings = getSettings(node);
if (settings == null) {
return UNKNOWN;
}
return settings.isTemporary() ? TEMPORARY_CONFIGURATION : CONFIGURATION;
}
if (userObject instanceof String) {
return FOLDER;
}
if (userObject instanceof ConfigurationType) {
return CONFIGURATION_TYPE;
}
return UNKNOWN;
}
class MyTreeModel extends DefaultTreeModel implements EditableModel, RowsDnDSupport.RefinedDropSupport {
private MyTreeModel(TreeNode root) {
super(root);
}
@Override
public void addRow() {
}
@Override
public void removeRow(int index) {
}
@Override
public void exchangeRows(int oldIndex, int newIndex) {
//Do nothing, use drop() instead
}
@Override
public boolean canExchangeRows(int oldIndex, int newIndex) {
return false;//Legacy, use canDrop() instead
}
@Override
public boolean canDrop(int oldIndex, int newIndex, @NotNull Position position) {
if (myTree.getRowCount() <= oldIndex || myTree.getRowCount() <= newIndex || oldIndex < 0 || newIndex < 0) {
return false;
}
DefaultMutableTreeNode oldNode = (DefaultMutableTreeNode)myTree.getPathForRow(oldIndex).getLastPathComponent();
DefaultMutableTreeNode newNode = (DefaultMutableTreeNode)myTree.getPathForRow(newIndex).getLastPathComponent();
DefaultMutableTreeNode oldParent = (DefaultMutableTreeNode)oldNode.getParent();
DefaultMutableTreeNode newParent = (DefaultMutableTreeNode)newNode.getParent();
NodeKind oldKind = getKind(oldNode);
NodeKind newKind = getKind(newNode);
ConfigurationType oldType = getType(oldNode);
ConfigurationType newType = getType(newNode);
if (oldParent == newParent) {
if (oldNode.getPreviousSibling() == newNode && position == BELOW) {
return false;
}
if (oldNode.getNextSibling() == newNode && position == ABOVE) {
return false;
}
}
if (oldType == null)
return false;
if (oldType != newType) {
DefaultMutableTreeNode typeNode = getConfigurationTypeNode(oldType);
if (getKind(oldParent) == FOLDER && typeNode != null && typeNode.getNextSibling() == newNode && position == ABOVE) {
return true;
}
if (getKind(oldParent) == CONFIGURATION_TYPE &&
oldKind == FOLDER &&
typeNode != null &&
typeNode.getNextSibling() == newNode &&
position == ABOVE &&
oldParent.getLastChild() != oldNode &&
getKind((DefaultMutableTreeNode)oldParent.getLastChild()) == FOLDER) {
return true;
}
return false;
}
if (newParent == oldNode || oldParent == newNode)
return false;
if (oldKind == FOLDER && newKind != FOLDER) {
if (newKind.isConfiguration() &&
position == ABOVE &&
getKind(newParent) == CONFIGURATION_TYPE &&
newIndex > 1 &&
getKind((DefaultMutableTreeNode)myTree.getPathForRow(newIndex - 1).getParentPath().getLastPathComponent()) == FOLDER) {
return true;
}
return false;
}
if (!oldKind.supportsDnD() || !newKind.supportsDnD()) {
return false;
}
if (oldKind.isConfiguration() && newKind == FOLDER && position == ABOVE)
return false;
if (oldKind == TEMPORARY_CONFIGURATION && newKind == CONFIGURATION && position == ABOVE)
return false;
if (oldKind == CONFIGURATION && newKind == TEMPORARY_CONFIGURATION && position == BELOW)
return false;
if (oldKind == CONFIGURATION && newKind == TEMPORARY_CONFIGURATION && position == ABOVE) {
return newNode.getPreviousSibling() == null ||
getKind(newNode.getPreviousSibling()) == CONFIGURATION ||
getKind(newNode.getPreviousSibling()) == FOLDER;
}
if (oldKind == TEMPORARY_CONFIGURATION && newKind == CONFIGURATION && position == BELOW)
return newNode.getNextSibling() == null || getKind(newNode.getNextSibling()) == TEMPORARY_CONFIGURATION;
if (oldParent == newParent) { //Same parent
if (oldKind.isConfiguration() && newKind.isConfiguration()) {
return oldKind == newKind;//both are temporary or saved
} else if (oldKind == FOLDER) {
return !myTree.isExpanded(newIndex) || position == ABOVE;
}
}
return true;
}
@Override
public boolean isDropInto(JComponent component, int oldIndex, int newIndex) {
TreePath oldPath = myTree.getPathForRow(oldIndex);
TreePath newPath = myTree.getPathForRow(newIndex);
if (oldPath == null || newPath == null) {
return false;
}
DefaultMutableTreeNode oldNode = (DefaultMutableTreeNode)oldPath.getLastPathComponent();
DefaultMutableTreeNode newNode = (DefaultMutableTreeNode)newPath.getLastPathComponent();
return getKind(oldNode).isConfiguration() && getKind(newNode) == FOLDER;
}
@Override
public void drop(int oldIndex, int newIndex, @NotNull Position position) {
DefaultMutableTreeNode oldNode = (DefaultMutableTreeNode)myTree.getPathForRow(oldIndex).getLastPathComponent();
DefaultMutableTreeNode newNode = (DefaultMutableTreeNode)myTree.getPathForRow(newIndex).getLastPathComponent();
DefaultMutableTreeNode newParent = (DefaultMutableTreeNode)newNode.getParent();
NodeKind oldKind = getKind(oldNode);
boolean wasExpanded = myTree.isExpanded(new TreePath(oldNode.getPath()));
if (isDropInto(myTree, oldIndex, newIndex)) { //Drop in folder
removeNodeFromParent(oldNode);
int index = newNode.getChildCount();
if (oldKind.isConfiguration()) {
int middleIndex = newNode.getChildCount();
for (int i = 0; i < newNode.getChildCount(); i++) {
if (getKind((DefaultMutableTreeNode)newNode.getChildAt(i)) == TEMPORARY_CONFIGURATION) {
middleIndex = i;//index of first temporary configuration in target folder
break;
}
}
if (position != INTO) {
if (oldIndex < newIndex) {
index = oldKind == CONFIGURATION ? 0 : middleIndex;
}
else {
index = oldKind == CONFIGURATION ? middleIndex : newNode.getChildCount();
}
} else {
index = oldKind == TEMPORARY_CONFIGURATION ? newNode.getChildCount() : middleIndex;
}
}
insertNodeInto(oldNode, newNode, index);
myTree.expandPath(new TreePath(newNode.getPath()));
}
else {
ConfigurationType type = getType(oldNode);
assert type != null;
removeNodeFromParent(oldNode);
int index;
if (type != getType(newNode)) {
DefaultMutableTreeNode typeNode = getConfigurationTypeNode(type);
assert typeNode != null;
newParent = typeNode;
index = newParent.getChildCount();
} else {
index = newParent.getIndex(newNode);
if (position == BELOW)
index++;
}
insertNodeInto(oldNode, newParent, index);
}
TreePath treePath = new TreePath(oldNode.getPath());
myTree.setSelectionPath(treePath);
if (wasExpanded) {
myTree.expandPath(treePath);
}
}
@Override
public void insertNodeInto(MutableTreeNode newChild, MutableTreeNode parent, int index) {
super.insertNodeInto(newChild, parent, index);
if (!getKind((DefaultMutableTreeNode)newChild).isConfiguration()) {
return;
}
Object userObject = getSafeUserObject((DefaultMutableTreeNode)newChild);
String newFolderName = getKind((DefaultMutableTreeNode)parent) == FOLDER
? (String)((DefaultMutableTreeNode)parent).getUserObject()
: null;
if (userObject instanceof SingleConfigurationConfigurable) {
((SingleConfigurationConfigurable)userObject).setFolderName(newFolderName);
}
}
@Override
public void reload(TreeNode node) {
super.reload(node);
Object userObject = ((DefaultMutableTreeNode)node).getUserObject();
if (userObject instanceof String) {
String folderName = (String)userObject;
for (int i = 0; i < node.getChildCount(); i++) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(i);
Object safeUserObject = getSafeUserObject(child);
if (safeUserObject instanceof SingleConfigurationConfigurable) {
((SingleConfigurationConfigurable)safeUserObject).setFolderName(folderName);
}
}
}
}
@Nullable
private RunnerAndConfigurationSettings getSettings(@NotNull DefaultMutableTreeNode treeNode) {
Object userObject = treeNode.getUserObject();
if (userObject instanceof SingleConfigurationConfigurable) {
SingleConfigurationConfigurable configurable = (SingleConfigurationConfigurable)userObject;
return (RunnerAndConfigurationSettings)configurable.getSettings();
} else if (userObject instanceof RunnerAndConfigurationSettings) {
return (RunnerAndConfigurationSettings)userObject;
}
return null;
}
@Nullable
private ConfigurationType getType(@Nullable DefaultMutableTreeNode treeNode) {
if (treeNode == null)
return null;
Object userObject = treeNode.getUserObject();
if (userObject instanceof SingleConfigurationConfigurable) {
SingleConfigurationConfigurable configurable = (SingleConfigurationConfigurable)userObject;
return configurable.getConfiguration().getType();
} else if (userObject instanceof RunnerAndConfigurationSettings) {
return ((RunnerAndConfigurationSettings)userObject).getType();
} else if (userObject instanceof ConfigurationType) {
return (ConfigurationType)userObject;
}
if (treeNode.getParent() instanceof DefaultMutableTreeNode) {
return getType((DefaultMutableTreeNode)treeNode.getParent());
}
return null;
}
}
}
| platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java | /*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.impl;
import com.intellij.execution.*;
import com.intellij.execution.configuration.ConfigurationFactoryEx;
import com.intellij.execution.configurations.*;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.options.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.popup.*;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.*;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.labels.ActionLink;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.IconUtil;
import com.intellij.util.PlatformIcons;
import com.intellij.util.config.StorageAccessors;
import com.intellij.util.containers.*;
import com.intellij.util.containers.HashMap;
import com.intellij.util.ui.EditableModel;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.GridBag;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import gnu.trove.THashSet;
import net.miginfocom.swing.MigLayout;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.*;
import java.util.HashSet;
import java.util.List;
import static com.intellij.execution.impl.RunConfigurable.NodeKind.*;
import static com.intellij.ui.RowsDnDSupport.RefinedDropSupport.Position.*;
class RunConfigurable extends BaseConfigurable {
private static final Icon ADD_ICON = IconUtil.getAddIcon();
private static final Icon REMOVE_ICON = IconUtil.getRemoveIcon();
private static final Icon SHARED_ICON = IconLoader.getTransparentIcon(AllIcons.Nodes.Symlink, .6f);
private static final Icon NON_SHARED_ICON = EmptyIcon.ICON_16;
@NonNls private static final String DIVIDER_PROPORTION = "dividerProportion";
@NonNls private static final Object DEFAULTS = new Object() {
@Override
public String toString() {
return "Defaults";
}
};
private volatile boolean isDisposed = false;
private final Project myProject;
private RunDialogBase myRunDialog;
@NonNls final DefaultMutableTreeNode myRoot = new DefaultMutableTreeNode("Root");
final MyTreeModel myTreeModel = new MyTreeModel(myRoot);
final Tree myTree = new Tree(myTreeModel);
private final JPanel myRightPanel = new JPanel(new BorderLayout());
private final Splitter mySplitter = new Splitter(false);
private JPanel myWholePanel;
private final StorageAccessors myProperties = StorageAccessors.createGlobal("RunConfigurable");
private Configurable mySelectedConfigurable = null;
private static final Logger LOG = Logger.getInstance("#com.intellij.execution.impl.RunConfigurable");
private final JTextField myRecentsLimit = new JTextField("5", 2);
private final JCheckBox myConfirmation = new JCheckBox(ExecutionBundle.message("rerun.confirmation.checkbox"), true);
private final List<Pair<UnnamedConfigurable, JComponent>> myAdditionalSettings = new ArrayList<Pair<UnnamedConfigurable, JComponent>>();
private Map<ConfigurationFactory, Configurable> myStoredComponents = new HashMap<ConfigurationFactory, Configurable>();
private ToolbarDecorator myToolbarDecorator;
private boolean isFolderCreating;
private RunConfigurable.MyToolbarAddAction myAddAction = new MyToolbarAddAction();
public RunConfigurable(final Project project) {
this(project, null);
}
public RunConfigurable(final Project project, @Nullable final RunDialogBase runDialog) {
myProject = project;
myRunDialog = runDialog;
}
@Override
public String getDisplayName() {
return ExecutionBundle.message("run.configurable.display.name");
}
private void initTree() {
myTree.setRootVisible(false);
myTree.setShowsRootHandles(true);
UIUtil.setLineStyleAngled(myTree);
TreeUtil.installActions(myTree);
new TreeSpeedSearch(myTree, new Convertor<TreePath, String>() {
@Override
public String convert(TreePath o) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)o.getLastPathComponent();
final Object userObject = node.getUserObject();
if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
return ((RunnerAndConfigurationSettingsImpl)userObject).getName();
}
else if (userObject instanceof SingleConfigurationConfigurable) {
return ((SingleConfigurationConfigurable)userObject).getNameText();
}
else {
if (userObject instanceof ConfigurationType) {
return ((ConfigurationType)userObject).getDisplayName();
}
else if (userObject instanceof String) {
return (String)userObject;
}
}
return o.toString();
}
});
myTree.setCellRenderer(new ColoredTreeCellRenderer() {
@Override
public void customizeCellRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
if (value instanceof DefaultMutableTreeNode) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
final Object userObject = node.getUserObject();
Boolean shared = null;
if (userObject instanceof ConfigurationType) {
final ConfigurationType configurationType = (ConfigurationType)userObject;
append(configurationType.getDisplayName(), parent.isRoot() ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES);
setIcon(configurationType.getIcon());
}
else if (userObject == DEFAULTS) {
append("Defaults", SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
setIcon(AllIcons.General.Settings);
}
else if (userObject instanceof String) {//Folders
append((String)userObject, SimpleTextAttributes.REGULAR_ATTRIBUTES);
setIcon(AllIcons.Nodes.Folder);
}
else if (userObject instanceof ConfigurationFactory) {
append(((ConfigurationFactory)userObject).getName());
setIcon(((ConfigurationFactory)userObject).getIcon());
}
else {
final RunManagerImpl runManager = getRunManager();
RunnerAndConfigurationSettings configuration = null;
String name = null;
if (userObject instanceof SingleConfigurationConfigurable) {
final SingleConfigurationConfigurable<?> settings = (SingleConfigurationConfigurable)userObject;
RunnerAndConfigurationSettings configurationSettings;
configurationSettings = settings.getSettings();
configuration = configurationSettings;
name = settings.getNameText();
shared = settings.isStoreProjectConfiguration();
setIcon(ProgramRunnerUtil.getConfigurationIcon(configurationSettings, !settings.isValid()));
}
else if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
RunnerAndConfigurationSettings settings = (RunnerAndConfigurationSettings)userObject;
shared = runManager.isConfigurationShared(settings);
setIcon(RunManagerEx.getInstanceEx(myProject).getConfigurationIcon(settings));
configuration = settings;
name = configuration.getName();
}
if (configuration != null) {
append(name, configuration.isTemporary()
? SimpleTextAttributes.GRAY_ATTRIBUTES
: SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
}
if (shared != null) {
Icon icon = getIcon();
LayeredIcon layeredIcon = new LayeredIcon(2);
layeredIcon.setIcon(icon, 0, 0, 0);
layeredIcon.setIcon(shared ? SHARED_ICON : NON_SHARED_ICON, 1, 8, 0);
setIcon(layeredIcon);
setIconTextGap(0);
} else {
setIconTextGap(2);
}
}
}
});
final RunManagerEx manager = getRunManager();
final ConfigurationType[] factories = manager.getConfigurationFactories();
for (ConfigurationType type : factories) {
final List<RunnerAndConfigurationSettings> configurations = manager.getConfigurationSettingsList(type);
if (!configurations.isEmpty()) {
final DefaultMutableTreeNode typeNode = new DefaultMutableTreeNode(type);
myRoot.add(typeNode);
Map<String, DefaultMutableTreeNode> folderMapping = new HashMap<String, DefaultMutableTreeNode>();
int folderCounter = 0;
for (RunnerAndConfigurationSettings configuration : configurations) {
String folder = configuration.getFolderName();
if (folder != null) {
DefaultMutableTreeNode node = folderMapping.get(folder);
if (node == null) {
node = new DefaultMutableTreeNode(folder);
typeNode.insert(node, folderCounter);
folderCounter++;
folderMapping.put(folder, node);
}
node.add(new DefaultMutableTreeNode(configuration));
} else {
typeNode.add(new DefaultMutableTreeNode(configuration));
}
}
}
}
// add defaults
final DefaultMutableTreeNode defaults = new DefaultMutableTreeNode(DEFAULTS);
final ConfigurationType[] configurationTypes = RunManagerImpl.getInstanceImpl(myProject).getConfigurationFactories();
for (final ConfigurationType type : configurationTypes) {
if (!(type instanceof UnknownConfigurationType)) {
ConfigurationFactory[] configurationFactories = type.getConfigurationFactories();
DefaultMutableTreeNode typeNode = new DefaultMutableTreeNode(type);
defaults.add(typeNode);
if (configurationFactories.length != 1) {
for (ConfigurationFactory factory : configurationFactories) {
typeNode.add(new DefaultMutableTreeNode(factory));
}
}
}
}
if (defaults.getChildCount() > 0) myRoot.add(defaults);
myTree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
final TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath != null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
final Object userObject = getSafeUserObject(node);
if (userObject instanceof SingleConfigurationConfigurable) {
updateRightPanel((SingleConfigurationConfigurable<RunConfiguration>)userObject);
}
else if (userObject instanceof String) {
showFolderField(getSelectedConfigurationType(), node, (String)userObject);
}
else {
if (userObject instanceof ConfigurationType || userObject == DEFAULTS) {
final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
if (parent.isRoot()) {
drawPressAddButtonMessage(userObject == DEFAULTS ? null : (ConfigurationType)userObject);
}
else {
final ConfigurationType type = (ConfigurationType)userObject;
ConfigurationFactory[] factories = type.getConfigurationFactories();
if (factories.length == 1) {
final ConfigurationFactory factory = factories[0];
showTemplateConfigurable(factory);
}
else {
drawPressAddButtonMessage((ConfigurationType)userObject);
}
}
}
else if (userObject instanceof ConfigurationFactory) {
showTemplateConfigurable((ConfigurationFactory)userObject);
}
}
}
updateDialog();
}
});
myTree.registerKeyboardAction(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clickDefaultButton();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (isDisposed) return;
myTree.requestFocusInWindow();
final RunnerAndConfigurationSettings settings = manager.getSelectedConfiguration();
if (settings != null) {
final Enumeration enumeration = myRoot.breadthFirstEnumeration();
while (enumeration.hasMoreElements()) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)enumeration.nextElement();
final Object userObject = node.getUserObject();
if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
final RunnerAndConfigurationSettings runnerAndConfigurationSettings = (RunnerAndConfigurationSettings)userObject;
final ConfigurationType configurationType = settings.getType();
if (configurationType != null &&
Comparing.strEqual(runnerAndConfigurationSettings.getConfiguration().getType().getId(), configurationType.getId()) &&
Comparing.strEqual(runnerAndConfigurationSettings.getConfiguration().getName(), settings.getName())) {
TreeUtil.selectInTree(node, true, myTree);
return;
}
}
}
}
else {
mySelectedConfigurable = null;
}
//TreeUtil.selectInTree(defaults, true, myTree);
drawPressAddButtonMessage(null);
}
});
sortTopLevelBranches();
((DefaultTreeModel)myTree.getModel()).reload();
}
private void showTemplateConfigurable(ConfigurationFactory factory) {
Configurable configurable = myStoredComponents.get(factory);
if (configurable == null){
configurable = new TemplateConfigurable(RunManagerImpl.getInstanceImpl(myProject).getConfigurationTemplate(factory));
myStoredComponents.put(factory, configurable);
configurable.reset();
}
updateRightPanel(configurable);
}
private void showFolderField(final ConfigurationType type, final DefaultMutableTreeNode node, final String folderName) {
myRightPanel.removeAll();
JPanel p = new JPanel(new MigLayout("ins " + myToolbarDecorator.getActionsPanel().getHeight() + " 5 0 0, flowx"));
final JTextField textField = new JTextField(folderName);
textField.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
node.setUserObject(textField.getText());
myTreeModel.reload(node);
}
});
p.add(new JLabel("Folder name:"), "gapright 5");
p.add(textField, "pushx, growx, wrap");
p.add(new JLabel(ExecutionBundle.message("run.configuration.rename.folder.disclaimer")), "gaptop 5, spanx 2");
myRightPanel.add(p);
myRightPanel.revalidate();
myRightPanel.repaint();
if (isFolderCreating) {
textField.selectAll();
textField.requestFocus();
}
}
private Object getSafeUserObject(DefaultMutableTreeNode node) {
Object userObject = node.getUserObject();
if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
final SingleConfigurationConfigurable<RunConfiguration> configurationConfigurable =
SingleConfigurationConfigurable.editSettings((RunnerAndConfigurationSettings)userObject, null);
installUpdateListeners(configurationConfigurable);
node.setUserObject(configurationConfigurable);
return configurationConfigurable;
}
return userObject;
}
public void setRunDialog(final RunDialogBase runDialog) {
myRunDialog = runDialog;
}
private void updateRightPanel(final Configurable configurable) {
myRightPanel.removeAll();
mySelectedConfigurable = configurable;
final JBScrollPane scrollPane = new JBScrollPane(configurable.createComponent());
scrollPane.setBorder(null);
myRightPanel.add(scrollPane, BorderLayout.CENTER);
if (configurable instanceof SingleConfigurationConfigurable) {
myRightPanel.add(((SingleConfigurationConfigurable)configurable).getValidationComponent(), BorderLayout.SOUTH);
}
setupDialogBounds();
}
private void sortTopLevelBranches() {
List<TreePath> expandedPaths = TreeUtil.collectExpandedPaths(myTree);
TreeUtil.sort(myRoot, new Comparator() {
@Override
public int compare(final Object o1, final Object o2) {
final Object userObject1 = ((DefaultMutableTreeNode)o1).getUserObject();
final Object userObject2 = ((DefaultMutableTreeNode)o2).getUserObject();
if (userObject1 instanceof ConfigurationType && userObject2 instanceof ConfigurationType) {
return ((ConfigurationType)userObject1).getDisplayName().compareTo(((ConfigurationType)userObject2).getDisplayName());
}
else if (userObject1 == DEFAULTS && userObject2 instanceof ConfigurationType) {
return 1;
}
return 0;
}
});
TreeUtil.restoreExpandedPaths(myTree, expandedPaths);
}
private void update() {
updateDialog();
final TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath != null) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
myTreeModel.reload(node);
}
}
private void installUpdateListeners(final SingleConfigurationConfigurable<RunConfiguration> info) {
final boolean[] changed = new boolean[]{false};
info.getEditor().addSettingsEditorListener(new SettingsEditorListener<RunnerAndConfigurationSettings>() {
@Override
public void stateChanged(final SettingsEditor<RunnerAndConfigurationSettings> editor) {
update();
final RunConfiguration configuration = info.getConfiguration();
if (configuration instanceof LocatableConfiguration) {
final LocatableConfiguration runtimeConfiguration = (LocatableConfiguration)configuration;
if (runtimeConfiguration.isGeneratedName() && !changed[0]) {
try {
final LocatableConfiguration snapshot = (LocatableConfiguration)editor.getSnapshot().getConfiguration();
final String generatedName = snapshot.suggestedName();
if (generatedName != null && generatedName.length() > 0) {
info.setNameText(generatedName);
changed[0] = false;
}
}
catch (ConfigurationException ignore) {
}
}
}
setupDialogBounds();
}
});
info.addNameListener(new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
changed[0] = true;
update();
}
});
info.addSharedListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
changed[0] = true;
update();
}
});
}
private void drawPressAddButtonMessage(final ConfigurationType configurationType) {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
panel.setBorder(new EmptyBorder(30, 0, 0, 0));
panel.add(new JLabel("Press the"));
ActionLink addIcon = new ActionLink("", ADD_ICON, myAddAction);
addIcon.setBorder(new EmptyBorder(0, 0, 0, 5));
panel.add(addIcon);
final String configurationTypeDescription = configurationType != null
? configurationType.getConfigurationTypeDescription()
: ExecutionBundle.message("run.configuration.default.type.description");
panel.add(new JLabel(ExecutionBundle.message("empty.run.configuration.panel.text.label3", configurationTypeDescription)));
JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(panel, true);
myRightPanel.removeAll();
myRightPanel.add(scrollPane, BorderLayout.CENTER);
if (configurationType == null) {
JPanel settingsPanel = new JPanel(new GridBagLayout());
GridBag grid = new GridBag().setDefaultAnchor(GridBagConstraints.NORTHWEST);
for (Pair<UnnamedConfigurable, JComponent> each : myAdditionalSettings) {
settingsPanel.add(each.second, grid.nextLine().next());
}
settingsPanel.add(createSettingsPanel(), grid.nextLine().next());
JPanel wrapper = new JPanel(new BorderLayout());
wrapper.add(settingsPanel, BorderLayout.WEST);
wrapper.add(Box.createGlue(), BorderLayout.CENTER);
myRightPanel.add(wrapper, BorderLayout.SOUTH);
}
myRightPanel.revalidate();
myRightPanel.repaint();
}
private JPanel createLeftPanel() {
initTree();
MyRemoveAction removeAction = new MyRemoveAction();
MyMoveAction moveUpAction = new MyMoveAction(ExecutionBundle.message("move.up.action.name"), null, IconUtil.getMoveUpIcon(), -1);
MyMoveAction moveDownAction = new MyMoveAction(ExecutionBundle.message("move.down.action.name"), null, IconUtil.getMoveDownIcon(), 1);
myToolbarDecorator = ToolbarDecorator.createDecorator(myTree).setAsUsualTopToolbar()
.setAddAction(myAddAction).setAddActionName(ExecutionBundle.message("add.new.run.configuration.acrtion.name"))
.setRemoveAction(removeAction).setRemoveActionUpdater(removeAction)
.setRemoveActionName(ExecutionBundle.message("remove.run.configuration.action.name"))
.setMoveUpAction(moveUpAction).setMoveUpActionName(ExecutionBundle.message("move.up.action.name")).setMoveUpActionUpdater(moveUpAction)
.setMoveDownAction(moveDownAction).setMoveDownActionName(ExecutionBundle.message("move.down.action.name")).setMoveDownActionUpdater(moveDownAction)
.addExtraAction(AnActionButton.fromAction(new MyCopyAction()))
.addExtraAction(AnActionButton.fromAction(new MySaveAction()))
.addExtraAction(AnActionButton.fromAction(new MyEditDefaultsAction()))
.addExtraAction(AnActionButton.fromAction(new MyCreateFolderAction()))
.setButtonComparator(ExecutionBundle.message("add.new.run.configuration.acrtion.name"),
ExecutionBundle.message("remove.run.configuration.action.name"),
ExecutionBundle.message("copy.configuration.action.name"),
ExecutionBundle.message("action.name.save.configuration"),
ExecutionBundle.message("run.configuration.edit.default.configuration.settings.text"),
ExecutionBundle.message("move.up.action.name"),
ExecutionBundle.message("move.down.action.name"),
ExecutionBundle.message("run.configuration.create.folder.text")
).setForcedDnD();
return myToolbarDecorator.createPanel();
}
private JPanel createSettingsPanel() {
JPanel bottomPanel = new JPanel(new GridBagLayout());
GridBag g = new GridBag();
bottomPanel.add(myConfirmation, g.nextLine().coverLine());
bottomPanel.add(new JLabel("Temporary configurations limit:"), g.nextLine().next());
bottomPanel.add(myRecentsLimit, g.next().anchor(GridBagConstraints.WEST));
myRecentsLimit.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
setModified(true);
}
});
myConfirmation.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
setModified(true);
}
});
return bottomPanel;
}
@Nullable
private ConfigurationType getSelectedConfigurationType() {
final DefaultMutableTreeNode configurationTypeNode = getSelectedConfigurationTypeNode();
return configurationTypeNode != null ? (ConfigurationType)configurationTypeNode.getUserObject() : null;
}
@Override
public JComponent createComponent() {
for (RunConfigurationsSettings each : Extensions.getExtensions(RunConfigurationsSettings.EXTENSION_POINT)) {
UnnamedConfigurable configurable = each.createConfigurable();
myAdditionalSettings.add(Pair.create(configurable, configurable.createComponent()));
}
myWholePanel = new JPanel(new BorderLayout());
mySplitter.setFirstComponent(createLeftPanel());
mySplitter.setSecondComponent(myRightPanel);
myWholePanel.add(mySplitter, BorderLayout.CENTER);
updateDialog();
Dimension d = myWholePanel.getPreferredSize();
d.width = Math.max(d.width, 800);
d.height = Math.max(d.height, 600);
myWholePanel.setPreferredSize(d);
mySplitter.setProportion(myProperties.getFloat(DIVIDER_PROPORTION, 0.3f));
return myWholePanel;
}
@Override
public void reset() {
final RunManagerEx manager = getRunManager();
final RunManagerConfig config = manager.getConfig();
myRecentsLimit.setText(Integer.toString(config.getRecentsLimit()));
myConfirmation.setSelected(config.isRestartRequiresConfirmation());
for (Pair<UnnamedConfigurable, JComponent> each : myAdditionalSettings) {
each.first.reset();
}
setModified(false);
}
public Configurable getSelectedConfigurable() {
return mySelectedConfigurable;
}
@Override
public void apply() throws ConfigurationException {
updateActiveConfigurationFromSelected();
final RunManagerImpl manager = getRunManager();
final ConfigurationType[] types = manager.getConfigurationFactories();
List<ConfigurationType> configurationTypes = new ArrayList<ConfigurationType>();
for (int i = 0; i < myRoot.getChildCount(); i++) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)myRoot.getChildAt(i);
Object userObject = node.getUserObject();
if (userObject instanceof ConfigurationType) {
configurationTypes.add((ConfigurationType)userObject);
}
}
for (ConfigurationType type : types) {
if (!configurationTypes.contains(type))
configurationTypes.add(type);
}
for (ConfigurationType configurationType : configurationTypes) {
applyByType(configurationType);
}
try {
int i = Math.max(RunManagerConfig.MIN_RECENT_LIMIT, Integer.parseInt(myRecentsLimit.getText()));
int oldLimit = manager.getConfig().getRecentsLimit();
if (oldLimit != i) {
manager.getConfig().setRecentsLimit(i);
manager.checkRecentsLimit();
}
}
catch (NumberFormatException e) {
// ignore
}
manager.getConfig().setRestartRequiresConfirmation(myConfirmation.isSelected());
for (Configurable configurable : myStoredComponents.values()) {
if (configurable.isModified()){
configurable.apply();
}
}
for (Pair<UnnamedConfigurable, JComponent> each : myAdditionalSettings) {
each.first.apply();
}
manager.saveOrder();
setModified(false);
myTree.repaint();
}
protected void updateActiveConfigurationFromSelected() {
if (mySelectedConfigurable != null && mySelectedConfigurable instanceof SingleConfigurationConfigurable) {
RunnerAndConfigurationSettings settings =
(RunnerAndConfigurationSettings)((SingleConfigurationConfigurable)mySelectedConfigurable).getSettings();
getRunManager().setSelectedConfiguration(settings);
}
}
private void applyByType(@NotNull ConfigurationType type) throws ConfigurationException {
RunnerAndConfigurationSettings selectedSettings = getSelectedSettings();
int indexToMove = -1;
DefaultMutableTreeNode typeNode = getConfigurationTypeNode(type);
final RunManagerImpl manager = getRunManager();
final ArrayList<RunConfigurationBean> stableConfigurations = new ArrayList<RunConfigurationBean>();
if (typeNode != null) {
final Set<String> names = new HashSet<String>();
List<DefaultMutableTreeNode> configurationNodes = new ArrayList<DefaultMutableTreeNode>();
collectNodesRecursively(typeNode, configurationNodes, CONFIGURATION, TEMPORARY_CONFIGURATION);
for (DefaultMutableTreeNode node : configurationNodes) {
final Object userObject = node.getUserObject();
RunConfigurationBean configurationBean = null;
RunnerAndConfigurationSettings settings = null;
if (userObject instanceof SingleConfigurationConfigurable) {
final SingleConfigurationConfigurable configurable = (SingleConfigurationConfigurable)userObject;
settings = (RunnerAndConfigurationSettings)configurable.getSettings();
if (settings.isTemporary()) {
applyConfiguration(typeNode, configurable);
}
configurationBean = new RunConfigurationBean(configurable);
}
else if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
settings = (RunnerAndConfigurationSettings)userObject;
configurationBean = new RunConfigurationBean(settings,
manager.isConfigurationShared(settings),
manager.getBeforeRunTasks(settings.getConfiguration()));
}
if (configurationBean != null) {
final SingleConfigurationConfigurable configurable = configurationBean.getConfigurable();
final String nameText = configurable != null ? configurable.getNameText() : configurationBean.getSettings().getName();
if (!names.add(nameText)) {
TreeUtil.selectNode(myTree, node);
throw new ConfigurationException(type.getDisplayName() + " with name \'" + nameText + "\' already exists");
}
stableConfigurations.add(configurationBean);
if (settings == selectedSettings) {
indexToMove = stableConfigurations.size()-1;
}
}
}
List<DefaultMutableTreeNode> folderNodes = new ArrayList<DefaultMutableTreeNode>();
collectNodesRecursively(typeNode, folderNodes, FOLDER);
names.clear();
for (DefaultMutableTreeNode node : folderNodes) {
String folderName = (String)node.getUserObject();
if (folderName.isEmpty()) {
TreeUtil.selectNode(myTree, node);
throw new ConfigurationException("Folder name shouldn't be empty");
}
if (!names.add(folderName)) {
TreeUtil.selectNode(myTree, node);
throw new ConfigurationException("Folders name \'" + folderName + "\' is duplicated");
}
}
}
// try to apply all
for (RunConfigurationBean bean : stableConfigurations) {
final SingleConfigurationConfigurable configurable = bean.getConfigurable();
if (configurable != null) {
applyConfiguration(typeNode, configurable);
}
}
// if apply succeeded, update the list of configurations in RunManager
Set<RunnerAndConfigurationSettings> toDeleteSettings = new THashSet<RunnerAndConfigurationSettings>();
for (RunConfiguration each : manager.getConfigurationsList(type)) {
ContainerUtil.addIfNotNull(toDeleteSettings, manager.getSettings(each));
}
//Just saved as 'stable' configuration shouldn't stay between temporary ones (here we order model to save)
int shift = 0;
if (selectedSettings != null && selectedSettings.getType() == type) {
shift = adjustOrder();
}
if (shift != 0 && indexToMove != -1) {
stableConfigurations.add(indexToMove-shift, stableConfigurations.remove(indexToMove));
}
for (RunConfigurationBean each : stableConfigurations) {
toDeleteSettings.remove(each.getSettings());
manager.addConfiguration(each.getSettings(), each.isShared(), each.getStepsBeforeLaunch(), false);
}
for (RunnerAndConfigurationSettings each : toDeleteSettings) {
manager.removeConfiguration(each);
}
}
static void collectNodesRecursively(DefaultMutableTreeNode parentNode, List<DefaultMutableTreeNode> nodes, NodeKind... allowed) {
for (int i = 0; i < parentNode.getChildCount(); i++) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode)parentNode.getChildAt(i);
if (ArrayUtilRt.find(allowed, getKind(child)) != -1) {
nodes.add(child);
}
collectNodesRecursively(child, nodes, allowed);
}
}
@Nullable
private DefaultMutableTreeNode getConfigurationTypeNode(@NotNull final ConfigurationType type) {
for (int i = 0; i < myRoot.getChildCount(); i++) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)myRoot.getChildAt(i);
if (node.getUserObject() == type) return node;
}
return null;
}
private void applyConfiguration(DefaultMutableTreeNode typeNode, SingleConfigurationConfigurable<?> configurable) throws ConfigurationException {
try {
if (configurable != null) {
configurable.apply();
RunManagerImpl.getInstanceImpl(myProject).fireRunConfigurationChanged(configurable.getSettings());
}
}
catch (ConfigurationException e) {
for (int i = 0; i < typeNode.getChildCount(); i++) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)typeNode.getChildAt(i);
if (Comparing.equal(configurable, node.getUserObject())) {
TreeUtil.selectNode(myTree, node);
break;
}
}
throw e;
}
}
@Override
public boolean isModified() {
if (super.isModified()) return true;
final RunManagerImpl runManager = getRunManager();
final List<RunConfiguration> allConfigurations = runManager.getAllConfigurationsList();
final List<RunConfiguration> currentConfigurations = new ArrayList<RunConfiguration>();
for (int i = 0; i < myRoot.getChildCount(); i++) {
DefaultMutableTreeNode typeNode = (DefaultMutableTreeNode)myRoot.getChildAt(i);
final Object object = typeNode.getUserObject();
if (object instanceof ConfigurationType) {
final List<RunnerAndConfigurationSettings> configurationSettings = runManager.getConfigurationSettingsList(
(ConfigurationType)object);
List<DefaultMutableTreeNode> configurationNodes = new ArrayList<DefaultMutableTreeNode>();
collectNodesRecursively(typeNode, configurationNodes, CONFIGURATION, TEMPORARY_CONFIGURATION);
if (configurationSettings.size() != configurationNodes.size()) return true;
for (int j = 0; j < configurationNodes.size(); j++) {
DefaultMutableTreeNode configurationNode = configurationNodes.get(j);
final Object userObject = configurationNode.getUserObject();
if (userObject instanceof SingleConfigurationConfigurable) {
SingleConfigurationConfigurable configurable = (SingleConfigurationConfigurable)userObject;
if (!Comparing.strEqual(configurationSettings.get(j).getConfiguration().getName(), configurable.getConfiguration().getName())) {
return true;
}
if (configurable.isModified()) return true;
currentConfigurations.add(configurable.getConfiguration());
}
else if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
currentConfigurations.add(((RunnerAndConfigurationSettings)userObject).getConfiguration());
}
}
}
}
if (allConfigurations.size() != currentConfigurations.size() || !allConfigurations.containsAll(currentConfigurations)) return true;
for (Configurable configurable : myStoredComponents.values()) {
if (configurable.isModified()) return true;
}
for (Pair<UnnamedConfigurable, JComponent> each : myAdditionalSettings) {
if (each.first.isModified()) return true;
}
return false;
}
@Override
public void disposeUIResources() {
isDisposed = true;
for (Configurable configurable : myStoredComponents.values()) {
configurable.disposeUIResources();
}
myStoredComponents.clear();
for (Pair<UnnamedConfigurable, JComponent> each : myAdditionalSettings) {
each.first.disposeUIResources();
}
TreeUtil.traverseDepth(myRoot, new TreeUtil.Traverse() {
@Override
public boolean accept(Object node) {
if (node instanceof DefaultMutableTreeNode) {
final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node;
final Object userObject = treeNode.getUserObject();
if (userObject instanceof SingleConfigurationConfigurable) {
((SingleConfigurationConfigurable)userObject).disposeUIResources();
}
}
return true;
}
});
myRightPanel.removeAll();
myProperties.setFloat(DIVIDER_PROPORTION, mySplitter.getProportion());
mySplitter.dispose();
}
private void updateDialog() {
final Executor executor = myRunDialog != null ? myRunDialog.getExecutor() : null;
if (executor == null) return;
final StringBuilder buffer = new StringBuilder();
buffer.append(executor.getId());
final SingleConfigurationConfigurable<RunConfiguration> configuration = getSelectedConfiguration();
if (configuration != null) {
buffer.append(" - ");
buffer.append(configuration.getNameText());
}
myRunDialog.setOKActionEnabled(canRunConfiguration(configuration, executor));
myRunDialog.setTitle(buffer.toString());
}
private void setupDialogBounds() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
UIUtil.setupEnclosingDialogBounds(myWholePanel);
}
});
}
@Nullable
private SingleConfigurationConfigurable<RunConfiguration> getSelectedConfiguration() {
final TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath != null) {
final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
final Object userObject = treeNode.getUserObject();
if (userObject instanceof SingleConfigurationConfigurable) {
return (SingleConfigurationConfigurable<RunConfiguration>)userObject;
}
}
return null;
}
private static boolean canRunConfiguration(@Nullable SingleConfigurationConfigurable<RunConfiguration> configuration, final @NotNull Executor executor) {
try {
return configuration != null && RunManagerImpl.canRunConfiguration(configuration.getSnapshot(), executor);
}
catch (ConfigurationException e) {
return false;
}
}
RunManagerImpl getRunManager() {
return RunManagerImpl.getInstanceImpl(myProject);
}
@Override
public String getHelpTopic() {
final ConfigurationType type = getSelectedConfigurationType();
if (type != null) {
return "reference.dialogs.rundebug." + type.getId();
}
return "reference.dialogs.rundebug";
}
private void clickDefaultButton() {
if (myRunDialog != null) myRunDialog.clickDefaultButton();
}
@Nullable
private DefaultMutableTreeNode getSelectedConfigurationTypeNode() {
TreePath selectionPath = myTree.getSelectionPath();
DefaultMutableTreeNode node = selectionPath != null ? (DefaultMutableTreeNode)selectionPath.getLastPathComponent() : null;
while(node != null) {
Object userObject = node.getUserObject();
if (userObject instanceof ConfigurationType) {
return node;
}
node = (DefaultMutableTreeNode)node.getParent();
}
return null;
}
@NotNull
private DefaultMutableTreeNode getNode(int row) {
return (DefaultMutableTreeNode)myTree.getPathForRow(row).getLastPathComponent();
}
@Nullable
Trinity<Integer, Integer, RowsDnDSupport.RefinedDropSupport.Position> getAvailableDropPosition(int direction) {
int[] rows = myTree.getSelectionRows();
if (rows == null || rows.length != 1) {
return null;
}
int oldIndex = rows[0];
int newIndex = oldIndex + direction;
if (!getKind((DefaultMutableTreeNode)myTree.getPathForRow(oldIndex).getLastPathComponent()).supportsDnD())
return null;
while (newIndex > 0 && newIndex < myTree.getRowCount()) {
TreePath targetPath = myTree.getPathForRow(newIndex);
boolean allowInto = getKind((DefaultMutableTreeNode)targetPath.getLastPathComponent()) == FOLDER && !myTree.isExpanded(targetPath);
RowsDnDSupport.RefinedDropSupport.Position position = allowInto && myTreeModel.isDropInto(myTree, oldIndex, newIndex) ?
INTO :
direction > 0 ? BELOW : ABOVE;
DefaultMutableTreeNode oldNode = getNode(oldIndex);
DefaultMutableTreeNode newNode = getNode(newIndex);
if (oldNode.getParent() != newNode.getParent() && getKind(newNode) != FOLDER) {
RowsDnDSupport.RefinedDropSupport.Position copy = position;
if (position == BELOW) {
copy = ABOVE;
}
else if (position == ABOVE) {
copy = BELOW;
}
if (myTreeModel.canDrop(oldIndex, newIndex, copy)) {
return Trinity.create(oldIndex, newIndex, copy);
}
}
if (myTreeModel.canDrop(oldIndex, newIndex, position)) {
return Trinity.create(oldIndex, newIndex, position);
}
if (position == BELOW && newIndex < myTree.getRowCount() - 1 && myTreeModel.canDrop(oldIndex, newIndex + 1, ABOVE)) {
return Trinity.create(oldIndex, newIndex + 1, ABOVE);
}
if (position == ABOVE && newIndex > 1 && myTreeModel.canDrop(oldIndex, newIndex - 1, BELOW)) {
return Trinity.create(oldIndex, newIndex - 1, BELOW);
}
if (position == BELOW && myTreeModel.canDrop(oldIndex, newIndex, ABOVE)) {
return Trinity.create(oldIndex, newIndex, ABOVE);
}
if (position == ABOVE && myTreeModel.canDrop(oldIndex, newIndex, BELOW)) {
return Trinity.create(oldIndex, newIndex, BELOW);
}
newIndex += direction;
}
return null;
}
@NotNull
private static String createUniqueName(DefaultMutableTreeNode typeNode, @Nullable String baseName, NodeKind...kinds) {
String str = (baseName == null) ? ExecutionBundle.message("run.configuration.unnamed.name.prefix") : baseName;
List<DefaultMutableTreeNode> configurationNodes = new ArrayList<DefaultMutableTreeNode>();
collectNodesRecursively(typeNode, configurationNodes, kinds);
final ArrayList<String> currentNames = new ArrayList<String>();
for (DefaultMutableTreeNode node : configurationNodes) {
final Object userObject = node.getUserObject();
if (userObject instanceof SingleConfigurationConfigurable) {
currentNames.add(((SingleConfigurationConfigurable)userObject).getNameText());
}
else if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
currentNames.add(((RunnerAndConfigurationSettings)userObject).getName());
}
else if (userObject instanceof String) {
currentNames.add((String)userObject);
}
}
return RunManager.suggestUniqueName(str, currentNames);
}
private SingleConfigurationConfigurable<RunConfiguration> createNewConfiguration(final RunnerAndConfigurationSettings settings, final DefaultMutableTreeNode node) {
final SingleConfigurationConfigurable<RunConfiguration> configurationConfigurable =
SingleConfigurationConfigurable.editSettings(settings, null);
installUpdateListeners(configurationConfigurable);
DefaultMutableTreeNode nodeToAdd = new DefaultMutableTreeNode(configurationConfigurable);
myTreeModel.insertNodeInto(nodeToAdd, node, node.getChildCount());
TreeUtil.selectNode(myTree, nodeToAdd);
return configurationConfigurable;
}
private void createNewConfiguration(final ConfigurationFactory factory) {
DefaultMutableTreeNode node = null;
DefaultMutableTreeNode selectedNode = null;
TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath != null) {
selectedNode = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
}
DefaultMutableTreeNode typeNode = getConfigurationTypeNode(factory.getType());
if (typeNode == null) {
typeNode = new DefaultMutableTreeNode(factory.getType());
myRoot.add(typeNode);
sortTopLevelBranches();
((DefaultTreeModel)myTree.getModel()).reload();
}
node = typeNode;
if (selectedNode != null && typeNode.isNodeDescendant(selectedNode)) {
node = selectedNode;
if (getKind(node).isConfiguration()) {
node = (DefaultMutableTreeNode)node.getParent();
}
}
final RunnerAndConfigurationSettings settings = getRunManager().createConfiguration(createUniqueName(typeNode, null, CONFIGURATION, TEMPORARY_CONFIGURATION), factory);
if (factory instanceof ConfigurationFactoryEx) {
((ConfigurationFactoryEx)factory).onNewConfigurationCreated(settings.getConfiguration());
}
createNewConfiguration(settings, node);
}
private class MyToolbarAddAction extends AnAction implements AnActionButtonRunnable {
public MyToolbarAddAction() {
super(ExecutionBundle.message("add.new.run.configuration.acrtion.name"),
ExecutionBundle.message("add.new.run.configuration.acrtion.name"), ADD_ICON);
registerCustomShortcutSet(CommonShortcuts.INSERT, myTree);
}
@Override
public void actionPerformed(AnActionEvent e) {
showAddPopup(true);
}
@Override
public void run(AnActionButton button) {
showAddPopup(true);
}
private void showAddPopup(final boolean showApplicableTypesOnly) {
ConfigurationType[] allTypes = getRunManager().getConfigurationFactories(false);
final List<ConfigurationType> configurationTypes = getTypesToShow(showApplicableTypesOnly, allTypes);
Collections.sort(configurationTypes, new Comparator<ConfigurationType>() {
@Override
public int compare(final ConfigurationType type1, final ConfigurationType type2) {
return type1.getDisplayName().compareToIgnoreCase(type2.getDisplayName());
}
});
final int hiddenCount = allTypes.length - configurationTypes.size();
if (hiddenCount > 0) {
configurationTypes.add(null);
}
final ListPopup popup = JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<ConfigurationType>(
ExecutionBundle.message("add.new.run.configuration.acrtion.name"), configurationTypes) {
@Override
@NotNull
public String getTextFor(final ConfigurationType type) {
return type != null ? type.getDisplayName() : hiddenCount + " items more (irrelevant)...";
}
@Override
public boolean isSpeedSearchEnabled() {
return true;
}
@Override
public boolean canBeHidden(ConfigurationType value) {
return true;
}
@Override
public Icon getIconFor(final ConfigurationType type) {
return type != null ? type.getIcon() : EmptyIcon.ICON_16;
}
@Override
public PopupStep onChosen(final ConfigurationType type, final boolean finalChoice) {
if (hasSubstep(type)) {
return getSupStep(type);
}
if (type == null) {
return doFinalStep(new Runnable() {
@Override
public void run() {
showAddPopup(false);
}
});
}
final ConfigurationFactory[] factories = type.getConfigurationFactories();
if (factories.length > 0) {
createNewConfiguration(factories[0]);
}
return FINAL_CHOICE;
}
@Override
public int getDefaultOptionIndex() {
ConfigurationType type = getSelectedConfigurationType();
return type != null ? configurationTypes.indexOf(type) : super.getDefaultOptionIndex();
}
private ListPopupStep getSupStep(final ConfigurationType type) {
final ConfigurationFactory[] factories = type.getConfigurationFactories();
Arrays.sort(factories, new Comparator<ConfigurationFactory>() {
@Override
public int compare(final ConfigurationFactory factory1, final ConfigurationFactory factory2) {
return factory1.getName().compareToIgnoreCase(factory2.getName());
}
});
return new BaseListPopupStep<ConfigurationFactory>(
ExecutionBundle.message("add.new.run.configuration.action.name", type.getDisplayName()), factories) {
@Override
@NotNull
public String getTextFor(final ConfigurationFactory value) {
return value.getName();
}
@Override
public Icon getIconFor(final ConfigurationFactory factory) {
return factory.getIcon();
}
@Override
public PopupStep onChosen(final ConfigurationFactory factory, final boolean finalChoice) {
createNewConfiguration(factory);
return FINAL_CHOICE;
}
};
}
@Override
public boolean hasSubstep(final ConfigurationType type) {
return type != null && type.getConfigurationFactories().length > 1;
}
});
//new TreeSpeedSearch(myTree);
popup.showUnderneathOf(myToolbarDecorator.getActionsPanel());
}
private List<ConfigurationType> getTypesToShow(boolean showApplicableTypesOnly, ConfigurationType[] allTypes) {
if (showApplicableTypesOnly) {
List<ConfigurationType> applicableTypes = new ArrayList<ConfigurationType>();
for (ConfigurationType type : allTypes) {
if (isApplicable(type)) {
applicableTypes.add(type);
}
}
if (applicableTypes.size() < allTypes.length - 3) {
return applicableTypes;
}
}
return new ArrayList<ConfigurationType>(Arrays.asList(allTypes));
}
private boolean isApplicable(ConfigurationType type) {
for (ConfigurationFactory factory : type.getConfigurationFactories()) {
if (factory.isApplicable(myProject)) {
return true;
}
}
return false;
}
}
private class MyRemoveAction extends AnAction implements AnActionButtonRunnable, AnActionButtonUpdater{
public MyRemoveAction() {
super(ExecutionBundle.message("remove.run.configuration.action.name"),
ExecutionBundle.message("remove.run.configuration.action.name"), REMOVE_ICON);
registerCustomShortcutSet(CommonShortcuts.DELETE, myTree);
}
@Override
public void actionPerformed(AnActionEvent e) {
doRemove();
}
@Override
public void run(AnActionButton button) {
doRemove();
}
private void doRemove() {
TreePath[] selections = myTree.getSelectionPaths();
myTree.clearSelection();
int nodeIndexToSelect = -1;
DefaultMutableTreeNode parentToSelect = null;
Set<DefaultMutableTreeNode> changedParents = new HashSet<DefaultMutableTreeNode>();
boolean wasRootChanged = false;
for (TreePath each : selections) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)each.getLastPathComponent();
DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
NodeKind kind = getKind(node);
if (!kind.isConfiguration() && kind != FOLDER)
continue;
if (node.getUserObject() instanceof SingleConfigurationConfigurable) {
((SingleConfigurationConfigurable)node.getUserObject()).disposeUIResources();
}
nodeIndexToSelect = parent.getIndex(node);
parentToSelect = parent;
myTreeModel.removeNodeFromParent(node);
changedParents.add(parent);
if (kind == FOLDER) {
List<DefaultMutableTreeNode> children = new ArrayList<DefaultMutableTreeNode>();
for (int i = 0; i < node.getChildCount(); i++) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(i);
Object userObject = getSafeUserObject(child);
if (userObject instanceof SingleConfigurationConfigurable) {
((SingleConfigurationConfigurable)userObject).setFolderName(null);
}
children.add(0, child);
}
int confIndex = 0;
for (int i = 0; i < parent.getChildCount(); i++) {
if (getKind((DefaultMutableTreeNode)parent.getChildAt(i)).isConfiguration()) {
confIndex = i;
break;
}
}
for (DefaultMutableTreeNode child : children) {
if (getKind(child) == CONFIGURATION)
myTreeModel.insertNodeInto(child, parent, confIndex);
}
confIndex = parent.getChildCount();
for (int i = 0; i < parent.getChildCount(); i++) {
if (getKind((DefaultMutableTreeNode)parent.getChildAt(i)) == TEMPORARY_CONFIGURATION) {
confIndex = i;
break;
}
}
for (DefaultMutableTreeNode child : children) {
if (getKind(child) == TEMPORARY_CONFIGURATION)
myTreeModel.insertNodeInto(child, parent, confIndex);
}
}
if (parent.getChildCount() == 0 && parent.getUserObject() instanceof ConfigurationType) {
changedParents.remove(parent);
wasRootChanged = true;
nodeIndexToSelect = myRoot.getIndex(parent);
nodeIndexToSelect = Math.max(0, nodeIndexToSelect - 1);
parentToSelect = myRoot;
parent.removeFromParent();
}
}
if (wasRootChanged) {
((DefaultTreeModel)myTree.getModel()).reload();
} else {
for (DefaultMutableTreeNode each : changedParents) {
myTreeModel.reload(each);
myTree.expandPath(new TreePath(each));
}
}
mySelectedConfigurable = null;
if (myRoot.getChildCount() == 0) {
drawPressAddButtonMessage(null);
}
else {
if (parentToSelect.getChildCount() > 0) {
TreeNode nodeToSelect = nodeIndexToSelect < parentToSelect.getChildCount()
? parentToSelect.getChildAt(nodeIndexToSelect)
: parentToSelect.getChildAt(nodeIndexToSelect - 1);
TreeUtil.selectInTree((DefaultMutableTreeNode)nodeToSelect, true, myTree);
}
}
}
@Override
public void update(AnActionEvent e) {
boolean enabled = isEnabled(e);
e.getPresentation().setEnabled(enabled);
}
@Override
public boolean isEnabled(AnActionEvent e) {
boolean enabled = false;
TreePath[] selections = myTree.getSelectionPaths();
if (selections != null) {
for (TreePath each : selections) {
NodeKind kind = getKind((DefaultMutableTreeNode)each.getLastPathComponent());
if (kind.isConfiguration() || kind == FOLDER) {
enabled = true;
break;
}
}
}
return enabled;
}
}
private class MyCopyAction extends AnAction {
public MyCopyAction() {
super(ExecutionBundle.message("copy.configuration.action.name"),
ExecutionBundle.message("copy.configuration.action.name"),
PlatformIcons.COPY_ICON);
final AnAction action = ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_DUPLICATE);
registerCustomShortcutSet(action.getShortcutSet(), myTree);
}
@Override
public void actionPerformed(AnActionEvent e) {
final SingleConfigurationConfigurable<RunConfiguration> configuration = getSelectedConfiguration();
LOG.assertTrue(configuration != null);
try {
final DefaultMutableTreeNode typeNode = getSelectedConfigurationTypeNode();
final RunnerAndConfigurationSettings settings = configuration.getSnapshot();
final String copyName = createUniqueName(typeNode, configuration.getNameText(), CONFIGURATION, TEMPORARY_CONFIGURATION);
settings.setName(copyName);
final ConfigurationFactory factory = settings.getFactory();
if (factory instanceof ConfigurationFactoryEx) {
((ConfigurationFactoryEx)factory).onConfigurationCopied(settings.getConfiguration());
}
final SingleConfigurationConfigurable<RunConfiguration> configurable = createNewConfiguration(settings, typeNode);
IdeFocusManager.getInstance(myProject).requestFocus(configurable.getNameTextField(), true);
configurable.getNameTextField().setSelectionStart(0);
configurable.getNameTextField().setSelectionEnd(copyName.length());
}
catch (ConfigurationException e1) {
Messages.showErrorDialog(myToolbarDecorator.getActionsPanel(), e1.getMessage(), e1.getTitle());
}
}
@Override
public void update(AnActionEvent e) {
final SingleConfigurationConfigurable<RunConfiguration> configuration = getSelectedConfiguration();
e.getPresentation().setEnabled(configuration != null && !(configuration.getConfiguration() instanceof UnknownRunConfiguration));
}
}
private class MySaveAction extends AnAction {
public MySaveAction() {
super(ExecutionBundle.message("action.name.save.configuration"), null, AllIcons.Actions.Menu_saveall);
}
@Override
public void actionPerformed(final AnActionEvent e) {
final SingleConfigurationConfigurable<RunConfiguration> configurationConfigurable = getSelectedConfiguration();
LOG.assertTrue(configurationConfigurable != null);
try {
configurationConfigurable.apply();
}
catch (ConfigurationException e1) {
//do nothing
}
final RunnerAndConfigurationSettings originalConfiguration = configurationConfigurable.getSettings();
if (originalConfiguration.isTemporary()) {
getRunManager().makeStable(originalConfiguration);
adjustOrder();
}
myTree.repaint();
}
@Override
public void update(final AnActionEvent e) {
final SingleConfigurationConfigurable<RunConfiguration> configuration = getSelectedConfiguration();
final Presentation presentation = e.getPresentation();
final boolean enabled;
if (configuration == null) {
enabled = false;
} else {
RunnerAndConfigurationSettings settings = configuration.getSettings();
enabled = settings != null && settings.isTemporary();
}
presentation.setEnabled(enabled);
presentation.setVisible(enabled);
}
}
/**
* Just saved as 'stable' configuration shouldn't stay between temporary ones (here we order nodes in JTree only)
* @return shift (positive) for move configuration "up" to other stable configurations. Zero means "there is nothing to change"
*/
private int adjustOrder() {
TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath == null)
return 0;
final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
RunnerAndConfigurationSettings selectedSettings = getSettings(treeNode);
if (selectedSettings == null || selectedSettings.isTemporary())
return 0;
MutableTreeNode parent = (MutableTreeNode)treeNode.getParent();
int initialPosition = parent.getIndex(treeNode);
int position = initialPosition;
DefaultMutableTreeNode node = treeNode.getPreviousSibling();
while (node != null) {
RunnerAndConfigurationSettings settings = getSettings(node);
if (settings != null && settings.isTemporary()) {
position--;
} else {
break;
}
node = node.getPreviousSibling();
}
for (int i = 0; i < initialPosition - position; i++) {
TreeUtil.moveSelectedRow(myTree, -1);
}
return initialPosition - position;
}
private class MyMoveAction extends AnAction implements AnActionButtonRunnable, AnActionButtonUpdater {
private final int myDirection;
protected MyMoveAction(String text, String description, Icon icon, int direction) {
super(text, description, icon);
myDirection = direction;
}
@Override
public void actionPerformed(final AnActionEvent e) {
doMove();
}
private void doMove() {
Trinity<Integer, Integer, RowsDnDSupport.RefinedDropSupport.Position> dropPosition = getAvailableDropPosition(myDirection);
if (dropPosition != null) {
myTreeModel.drop(dropPosition.first, dropPosition.second, dropPosition.third);
}
}
@Override
public void run(AnActionButton button) {
doMove();
}
@Override
public void update(final AnActionEvent e) {
e.getPresentation().setEnabled(isEnabled(e));
}
@Override
public boolean isEnabled(AnActionEvent e) {
return getAvailableDropPosition(myDirection) != null;
}
}
private class MyEditDefaultsAction extends AnAction {
public MyEditDefaultsAction() {
super(ExecutionBundle.message("run.configuration.edit.default.configuration.settings.text"),
ExecutionBundle.message("run.configuration.edit.default.configuration.settings.description"), AllIcons.General.Settings);
}
@Override
public void actionPerformed(final AnActionEvent e) {
TreeNode defaults = TreeUtil.findNodeWithObject(DEFAULTS, myTree.getModel(), myRoot);
if (defaults != null) {
final ConfigurationType configurationType = getSelectedConfigurationType();
if (configurationType != null) {
defaults = TreeUtil.findNodeWithObject(configurationType, myTree.getModel(), defaults);
}
final DefaultMutableTreeNode defaultsNode = (DefaultMutableTreeNode)defaults;
if (defaultsNode == null) {
return;
}
final TreePath path = TreeUtil.getPath(myRoot, defaultsNode);
myTree.expandPath(path);
TreeUtil.selectInTree(defaultsNode, true, myTree);
myTree.scrollPathToVisible(path);
}
}
@Override
public void update(AnActionEvent e) {
boolean isEnabled = TreeUtil.findNodeWithObject(DEFAULTS, myTree.getModel(), myRoot) != null;
TreePath path = myTree.getSelectionPath();
if (path != null) {
Object o = path.getLastPathComponent();
if (o instanceof DefaultMutableTreeNode && ((DefaultMutableTreeNode)o).getUserObject().equals(DEFAULTS)) {
isEnabled = false;
}
o = path.getParentPath().getLastPathComponent();
if (o instanceof DefaultMutableTreeNode && ((DefaultMutableTreeNode)o).getUserObject().equals(DEFAULTS)) {
isEnabled = false;
}
}
e.getPresentation().setEnabled(isEnabled);
}
}
private class MyCreateFolderAction extends AnAction {
private MyCreateFolderAction() {
super(ExecutionBundle.message("run.configuration.create.folder.text"),
ExecutionBundle.message("run.configuration.create.folder.description"), AllIcons.Nodes.Folder);
}
@Override
public void actionPerformed(AnActionEvent e) {
final ConfigurationType type = getSelectedConfigurationType();
if (type == null) {
return;
}
final DefaultMutableTreeNode[] selectedNodes = getSelectedNodes();
DefaultMutableTreeNode typeNode = getConfigurationTypeNode(type);
if (typeNode == null) {
return;
}
String folderName = createUniqueName(typeNode, "New Folder", FOLDER);
List<DefaultMutableTreeNode> folders = new ArrayList<DefaultMutableTreeNode>();
collectNodesRecursively(getConfigurationTypeNode(type), folders, FOLDER);
final DefaultMutableTreeNode folderNode = new DefaultMutableTreeNode(folderName);
myTreeModel.insertNodeInto(folderNode, typeNode, folders.size());
isFolderCreating = true;
try {
for (DefaultMutableTreeNode node : selectedNodes) {
int folderRow = myTree.getRowForPath(new TreePath(folderNode.getPath()));
int rowForPath = myTree.getRowForPath(new TreePath(node.getPath()));
if (getKind(node).isConfiguration() && myTreeModel.canDrop(rowForPath, folderRow, INTO)) {
myTreeModel.drop(rowForPath, folderRow, INTO);
}
}
myTree.setSelectionPath(new TreePath(folderNode.getPath()));
}
finally {
isFolderCreating = false;
}
}
@Override
public void update(AnActionEvent e) {
boolean isEnabled = false;
boolean toMove = false;
DefaultMutableTreeNode[] selectedNodes = getSelectedNodes();
ConfigurationType selectedType = null;
for (DefaultMutableTreeNode node : selectedNodes) {
ConfigurationType type = getType(node);
if (selectedType == null) {
selectedType = type;
} else {
if (!Comparing.equal(type, selectedType)) {
isEnabled = false;
break;
}
}
NodeKind kind = getKind(node);
if (kind.isConfiguration() || (kind == CONFIGURATION_TYPE && node.getParent() == myRoot) || kind == FOLDER) {
isEnabled = true;
}
if (kind.isConfiguration()) {
toMove = true;
}
}
e.getPresentation().setText(ExecutionBundle.message("run.configuration.create.folder.description" + (toMove ? ".move" : "")));
e.getPresentation().setEnabled(isEnabled);
}
}
@Nullable
private static ConfigurationType getType(DefaultMutableTreeNode node) {
while (node != null) {
if (node.getUserObject() instanceof ConfigurationType) {
return (ConfigurationType)node.getUserObject();
}
node = (DefaultMutableTreeNode)node.getParent();
}
return null;
}
@NotNull
private DefaultMutableTreeNode[] getSelectedNodes() {
return myTree.getSelectedNodes(DefaultMutableTreeNode.class, null);
}
@Nullable
private DefaultMutableTreeNode getSelectedNode() {
DefaultMutableTreeNode[] nodes = myTree.getSelectedNodes(DefaultMutableTreeNode.class, null);
return nodes.length > 1 ? nodes[0] : null;
}
@Nullable
private RunnerAndConfigurationSettings getSelectedSettings() {
TreePath selectionPath = myTree.getSelectionPath();
if (selectionPath == null)
return null;
return getSettings((DefaultMutableTreeNode)selectionPath.getLastPathComponent());
}
@Nullable
private static RunnerAndConfigurationSettings getSettings(DefaultMutableTreeNode treeNode) {
if (treeNode == null)
return null;
RunnerAndConfigurationSettings settings = null;
if (treeNode.getUserObject() instanceof SingleConfigurationConfigurable) {
settings = (RunnerAndConfigurationSettings)((SingleConfigurationConfigurable)treeNode.getUserObject()).getSettings();
}
if (treeNode.getUserObject() instanceof RunnerAndConfigurationSettings) {
settings = (RunnerAndConfigurationSettings)treeNode.getUserObject();
}
return settings;
}
private static class RunConfigurationBean {
private final RunnerAndConfigurationSettings mySettings;
private final boolean myShared;
private final List<BeforeRunTask> myStepsBeforeLaunch;
private final SingleConfigurationConfigurable myConfigurable;
public RunConfigurationBean(final RunnerAndConfigurationSettings settings,
final boolean shared,
final List<BeforeRunTask> stepsBeforeLaunch) {
mySettings = settings;
myShared = shared;
myStepsBeforeLaunch = Collections.unmodifiableList(stepsBeforeLaunch);
myConfigurable = null;
}
public RunConfigurationBean(final SingleConfigurationConfigurable configurable) {
myConfigurable = configurable;
mySettings = (RunnerAndConfigurationSettings)myConfigurable.getSettings();
final ConfigurationSettingsEditorWrapper editorWrapper = (ConfigurationSettingsEditorWrapper)myConfigurable.getEditor();
myShared = configurable.isStoreProjectConfiguration();
myStepsBeforeLaunch = editorWrapper.getStepsBeforeLaunch();
}
public RunnerAndConfigurationSettings getSettings() {
return mySettings;
}
public boolean isShared() {
return myShared;
}
public List<BeforeRunTask> getStepsBeforeLaunch() {
return myStepsBeforeLaunch;
}
public SingleConfigurationConfigurable getConfigurable() {
return myConfigurable;
}
@Override
public String toString() {
return String.valueOf(mySettings);
}
}
public interface RunDialogBase {
void setOKActionEnabled(boolean isEnabled);
@Nullable
Executor getExecutor();
void setTitle(String title);
void clickDefaultButton();
}
enum NodeKind {
CONFIGURATION_TYPE, FOLDER, CONFIGURATION, TEMPORARY_CONFIGURATION, UNKNOWN;
boolean supportsDnD() {
return this == FOLDER || this == CONFIGURATION || this == TEMPORARY_CONFIGURATION;
}
boolean isConfiguration() {
return this == CONFIGURATION | this == TEMPORARY_CONFIGURATION;
}
}
@NotNull
static NodeKind getKind(@Nullable DefaultMutableTreeNode node) {
if (node == null)
return UNKNOWN;
Object userObject = node.getUserObject();
if (userObject instanceof SingleConfigurationConfigurable || userObject instanceof RunnerAndConfigurationSettings) {
RunnerAndConfigurationSettings settings = getSettings(node);
if (settings == null) {
return UNKNOWN;
}
return settings.isTemporary() ? TEMPORARY_CONFIGURATION : CONFIGURATION;
}
if (userObject instanceof String) {
return FOLDER;
}
if (userObject instanceof ConfigurationType) {
return CONFIGURATION_TYPE;
}
return UNKNOWN;
}
class MyTreeModel extends DefaultTreeModel implements EditableModel, RowsDnDSupport.RefinedDropSupport {
private MyTreeModel(TreeNode root) {
super(root);
}
@Override
public void addRow() {
}
@Override
public void removeRow(int index) {
}
@Override
public void exchangeRows(int oldIndex, int newIndex) {
//Do nothing, use drop() instead
}
@Override
public boolean canExchangeRows(int oldIndex, int newIndex) {
return false;//Legacy, use canDrop() instead
}
@Override
public boolean canDrop(int oldIndex, int newIndex, @NotNull Position position) {
if (myTree.getRowCount() <= oldIndex || myTree.getRowCount() <= newIndex || oldIndex < 0 || newIndex < 0) {
return false;
}
DefaultMutableTreeNode oldNode = (DefaultMutableTreeNode)myTree.getPathForRow(oldIndex).getLastPathComponent();
DefaultMutableTreeNode newNode = (DefaultMutableTreeNode)myTree.getPathForRow(newIndex).getLastPathComponent();
DefaultMutableTreeNode oldParent = (DefaultMutableTreeNode)oldNode.getParent();
DefaultMutableTreeNode newParent = (DefaultMutableTreeNode)newNode.getParent();
NodeKind oldKind = getKind(oldNode);
NodeKind newKind = getKind(newNode);
ConfigurationType oldType = getType(oldNode);
ConfigurationType newType = getType(newNode);
if (oldParent == newParent) {
if (oldNode.getPreviousSibling() == newNode && position == BELOW) {
return false;
}
if (oldNode.getNextSibling() == newNode && position == ABOVE) {
return false;
}
}
if (oldType == null)
return false;
if (oldType != newType) {
DefaultMutableTreeNode typeNode = getConfigurationTypeNode(oldType);
if (getKind(oldParent) == FOLDER && typeNode != null && typeNode.getNextSibling() == newNode && position == ABOVE) {
return true;
}
if (getKind(oldParent) == CONFIGURATION_TYPE &&
oldKind == FOLDER &&
typeNode != null &&
typeNode.getNextSibling() == newNode &&
position == ABOVE &&
oldParent.getLastChild() != oldNode &&
getKind((DefaultMutableTreeNode)oldParent.getLastChild()) == FOLDER) {
return true;
}
return false;
}
if (newParent == oldNode || oldParent == newNode)
return false;
if (oldKind == FOLDER && newKind != FOLDER) {
if (newKind.isConfiguration() &&
position == ABOVE &&
getKind(newParent) == CONFIGURATION_TYPE &&
newIndex > 1 &&
getKind((DefaultMutableTreeNode)myTree.getPathForRow(newIndex - 1).getParentPath().getLastPathComponent()) == FOLDER) {
return true;
}
return false;
}
if (!oldKind.supportsDnD() || !newKind.supportsDnD()) {
return false;
}
if (oldKind.isConfiguration() && newKind == FOLDER && position == ABOVE)
return false;
if (oldKind == TEMPORARY_CONFIGURATION && newKind == CONFIGURATION && position == ABOVE)
return false;
if (oldKind == CONFIGURATION && newKind == TEMPORARY_CONFIGURATION && position == BELOW)
return false;
if (oldKind == CONFIGURATION && newKind == TEMPORARY_CONFIGURATION && position == ABOVE) {
return newNode.getPreviousSibling() == null ||
getKind(newNode.getPreviousSibling()) == CONFIGURATION ||
getKind(newNode.getPreviousSibling()) == FOLDER;
}
if (oldKind == TEMPORARY_CONFIGURATION && newKind == CONFIGURATION && position == BELOW)
return newNode.getNextSibling() == null || getKind(newNode.getNextSibling()) == TEMPORARY_CONFIGURATION;
if (oldParent == newParent) { //Same parent
if (oldKind.isConfiguration() && newKind.isConfiguration()) {
return oldKind == newKind;//both are temporary or saved
} else if (oldKind == FOLDER) {
return !myTree.isExpanded(newIndex) || position == ABOVE;
}
}
return true;
}
@Override
public boolean isDropInto(JComponent component, int oldIndex, int newIndex) {
TreePath oldPath = myTree.getPathForRow(oldIndex);
TreePath newPath = myTree.getPathForRow(newIndex);
if (oldPath == null || newPath == null) {
return false;
}
DefaultMutableTreeNode oldNode = (DefaultMutableTreeNode)oldPath.getLastPathComponent();
DefaultMutableTreeNode newNode = (DefaultMutableTreeNode)newPath.getLastPathComponent();
return getKind(oldNode).isConfiguration() && getKind(newNode) == FOLDER;
}
@Override
public void drop(int oldIndex, int newIndex, @NotNull Position position) {
DefaultMutableTreeNode oldNode = (DefaultMutableTreeNode)myTree.getPathForRow(oldIndex).getLastPathComponent();
DefaultMutableTreeNode newNode = (DefaultMutableTreeNode)myTree.getPathForRow(newIndex).getLastPathComponent();
DefaultMutableTreeNode newParent = (DefaultMutableTreeNode)newNode.getParent();
NodeKind oldKind = getKind(oldNode);
boolean wasExpanded = myTree.isExpanded(new TreePath(oldNode.getPath()));
if (isDropInto(myTree, oldIndex, newIndex)) { //Drop in folder
removeNodeFromParent(oldNode);
int index = newNode.getChildCount();
if (oldKind.isConfiguration()) {
int middleIndex = newNode.getChildCount();
for (int i = 0; i < newNode.getChildCount(); i++) {
if (getKind((DefaultMutableTreeNode)newNode.getChildAt(i)) == TEMPORARY_CONFIGURATION) {
middleIndex = i;//index of first temporary configuration in target folder
break;
}
}
if (position != INTO) {
if (oldIndex < newIndex) {
index = oldKind == CONFIGURATION ? 0 : middleIndex;
}
else {
index = oldKind == CONFIGURATION ? middleIndex : newNode.getChildCount();
}
} else {
index = oldKind == TEMPORARY_CONFIGURATION ? newNode.getChildCount() : middleIndex;
}
}
insertNodeInto(oldNode, newNode, index);
myTree.expandPath(new TreePath(newNode.getPath()));
}
else {
ConfigurationType type = getType(oldNode);
assert type != null;
removeNodeFromParent(oldNode);
int index;
if (type != getType(newNode)) {
DefaultMutableTreeNode typeNode = getConfigurationTypeNode(type);
assert typeNode != null;
newParent = typeNode;
index = newParent.getChildCount();
} else {
index = newParent.getIndex(newNode);
if (position == BELOW)
index++;
}
insertNodeInto(oldNode, newParent, index);
}
TreePath treePath = new TreePath(oldNode.getPath());
myTree.setSelectionPath(treePath);
if (wasExpanded) {
myTree.expandPath(treePath);
}
}
@Override
public void insertNodeInto(MutableTreeNode newChild, MutableTreeNode parent, int index) {
super.insertNodeInto(newChild, parent, index);
if (!getKind((DefaultMutableTreeNode)newChild).isConfiguration()) {
return;
}
Object userObject = getSafeUserObject((DefaultMutableTreeNode)newChild);
String newFolderName = getKind((DefaultMutableTreeNode)parent) == FOLDER
? (String)((DefaultMutableTreeNode)parent).getUserObject()
: null;
if (userObject instanceof SingleConfigurationConfigurable) {
((SingleConfigurationConfigurable)userObject).setFolderName(newFolderName);
}
}
@Override
public void reload(TreeNode node) {
super.reload(node);
Object userObject = ((DefaultMutableTreeNode)node).getUserObject();
if (userObject instanceof String) {
String folderName = (String)userObject;
for (int i = 0; i < node.getChildCount(); i++) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(i);
Object safeUserObject = getSafeUserObject(child);
if (safeUserObject instanceof SingleConfigurationConfigurable) {
((SingleConfigurationConfigurable)safeUserObject).setFolderName(folderName);
}
}
}
}
@Nullable
private RunnerAndConfigurationSettings getSettings(@NotNull DefaultMutableTreeNode treeNode) {
Object userObject = treeNode.getUserObject();
if (userObject instanceof SingleConfigurationConfigurable) {
SingleConfigurationConfigurable configurable = (SingleConfigurationConfigurable)userObject;
return (RunnerAndConfigurationSettings)configurable.getSettings();
} else if (userObject instanceof RunnerAndConfigurationSettings) {
return (RunnerAndConfigurationSettings)userObject;
}
return null;
}
@Nullable
private ConfigurationType getType(@Nullable DefaultMutableTreeNode treeNode) {
if (treeNode == null)
return null;
Object userObject = treeNode.getUserObject();
if (userObject instanceof SingleConfigurationConfigurable) {
SingleConfigurationConfigurable configurable = (SingleConfigurationConfigurable)userObject;
return configurable.getConfiguration().getType();
} else if (userObject instanceof RunnerAndConfigurationSettings) {
return ((RunnerAndConfigurationSettings)userObject).getType();
} else if (userObject instanceof ConfigurationType) {
return (ConfigurationType)userObject;
}
if (treeNode.getParent() instanceof DefaultMutableTreeNode) {
return getType((DefaultMutableTreeNode)treeNode.getParent());
}
return null;
}
}
}
| IDEA-94140 Run Configurations: first configurations of every type is shown below Defaults on creation
| platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java | IDEA-94140 Run Configurations: first configurations of every type is shown below Defaults on creation | <ide><path>latform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java
<ide> else if (userObject1 == DEFAULTS && userObject2 instanceof ConfigurationType) {
<ide> return 1;
<ide> }
<add> else if (userObject2 == DEFAULTS && userObject1 instanceof ConfigurationType) {
<add> return -1;
<add> }
<ide>
<ide> return 0;
<ide> } |
|
JavaScript | mit | e6bf82fba5b3c07c34f05f48a3e287ab06469d02 | 0 | azum4roll/Pokemon-Showdown,azum4roll/Pokemon-Showdown | 'use strict';
exports.BattleStatuses = {
brn: {
inherit: true,
onResidual: function (pokemon) {
this.damage(pokemon.maxhp / 8);
},
},
par: {
inherit: true,
onModifySpe: function (spe, pokemon) {
if (!pokemon.hasAbility('quickfeet')) {
return this.chainModify(0.25);
}
},
},
confusion: {
inherit: true,
onBeforeMove: function (pokemon) {
pokemon.volatiles.confusion.time--;
if (!pokemon.volatiles.confusion.time) {
pokemon.removeVolatile('confusion');
return;
}
this.add('-activate', pokemon, 'confusion');
if (this.random(2) === 0) {
return;
}
this.damage(this.getDamage(pokemon, pokemon, 40), pokemon, pokemon, {
id: 'confused',
effectType: 'Move',
type: '???',
});
return false;
},
},
choicelock: {
onBeforeMove: function () {},
},
};
| mods/gen6/statuses.js | 'use strict';
exports.BattleStatuses = {
brn: {
inherit: true,
onResidual: function (pokemon) {
this.damage(pokemon.maxhp / 8);
},
},
par: {
inherit: true,
onModifySpe: function (spe, pokemon) {
if (!pokemon.hasAbility('quickfeet')) {
return this.chainModify(0.25);
}
},
},
confusion: {
inherit: true,
onBeforeMove: function (pokemon) {
pokemon.volatiles.confusion.time--;
if (!pokemon.volatiles.confusion.time) {
pokemon.removeVolatile('confusion');
return;
}
this.add('-activate', pokemon, 'confusion');
if (this.random(2) === 0) {
return;
}
this.damage(this.getDamage(pokemon, pokemon, 40), pokemon, pokemon, {
id: 'confused',
effectType: 'Move',
type: '???',
});
return false;
},
},
};
| Update Choice-lock mechanics
| mods/gen6/statuses.js | Update Choice-lock mechanics | <ide><path>ods/gen6/statuses.js
<ide> return false;
<ide> },
<ide> },
<add> choicelock: {
<add> onBeforeMove: function () {},
<add> },
<ide> }; |
|
Java | agpl-3.0 | 310c038363fe2b244bb8f991a46dc1c7d2b85a7f | 0 | cryptomator/cryptofs | /*******************************************************************************
* Copyright (c) 2016 Sebastian Stenzel and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the accompanying LICENSE.txt.
*
* Contributors:
* Sebastian Stenzel - initial API and implementation
*******************************************************************************/
package org.cryptomator.cryptofs;
import com.google.common.base.Strings;
import org.cryptomator.cryptofs.common.Constants;
import org.cryptomator.cryptolib.api.Masterkey;
import org.cryptomator.cryptolib.api.MasterkeyLoader;
import org.cryptomator.cryptolib.api.MasterkeyLoadingFailedException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mockito;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.function.Predicate;
import java.util.stream.Stream;
import static java.nio.file.StandardOpenOption.CREATE_NEW;
import static org.cryptomator.cryptofs.CryptoFileSystemUri.create;
/**
* Regression tests https://github.com/cryptomator/cryptofs/issues/17.
*/
public class DeleteNonEmptyCiphertextDirectoryIntegrationTest {
private static Path pathToVault;
private static FileSystem fileSystem;
@BeforeAll
public static void setupClass(@TempDir Path tmpDir) throws IOException, MasterkeyLoadingFailedException {
pathToVault = tmpDir.resolve("vault");
Files.createDirectory(pathToVault);
MasterkeyLoader keyLoader = Mockito.mock(MasterkeyLoader.class);
Mockito.when(keyLoader.loadKey(Mockito.any())).thenAnswer(ignored -> new Masterkey(new byte[64]));
CryptoFileSystemProperties properties = CryptoFileSystemProperties.cryptoFileSystemProperties().withKeyLoader(keyLoader).build();
CryptoFileSystemProvider.initialize(pathToVault, properties, URI.create("test:key"));
fileSystem = new CryptoFileSystemProvider().newFileSystem(create(pathToVault), properties);
}
@Test
public void testDeleteCiphertextDirectoryContainingNonCryptoFile() throws IOException {
Path cleartextDirectory = fileSystem.getPath("/z");
Files.createDirectory(cleartextDirectory);
Path ciphertextDirectory = firstEmptyCiphertextDirectory();
createFile(ciphertextDirectory, "foo01234.txt", new byte[]{65});
Assertions.assertDoesNotThrow(() -> {
Files.delete(cleartextDirectory);
});
}
@Test
public void testDeleteCiphertextDirectoryContainingDirectories() throws IOException {
Path cleartextDirectory = fileSystem.getPath("/a");
Files.createDirectory(cleartextDirectory);
Path ciphertextDirectory = firstEmptyCiphertextDirectory();
// ciphertextDir
// .. foo0123
// .... foobar
// ...... test.baz
// .... text.txt
// .... text.data
Path foo0123 = createFolder(ciphertextDirectory, "foo0123");
Path foobar = createFolder(foo0123, "foobar");
createFile(foo0123, "test.txt", new byte[]{65});
createFile(foo0123, "text.data", new byte[]{65});
createFile(foobar, "test.baz", new byte[]{65});
Assertions.assertDoesNotThrow(() -> {
Files.delete(cleartextDirectory);
});
}
@Test
@Disabled // c9s not yet implemented
public void testDeleteDirectoryContainingLongNameFileWithoutMetadata() throws IOException {
Path cleartextDirectory = fileSystem.getPath("/b");
Files.createDirectory(cleartextDirectory);
Path ciphertextDirectory = firstEmptyCiphertextDirectory();
Path longNameDir = createFolder(ciphertextDirectory, "HHEZJURE.c9s");
createFile(longNameDir, Constants.CONTENTS_FILE_NAME, new byte[]{65});
Assertions.assertDoesNotThrow(() -> {
Files.delete(cleartextDirectory);
});
}
@Test
@Disabled // c9s not yet implemented
public void testDeleteDirectoryContainingUnauthenticLongNameDirectoryFile() throws IOException {
Path cleartextDirectory = fileSystem.getPath("/c");
Files.createDirectory(cleartextDirectory);
Path ciphertextDirectory = firstEmptyCiphertextDirectory();
Path longNameDir = createFolder(ciphertextDirectory, "HHEZJURE.c9s");
createFile(longNameDir, Constants.INFLATED_FILE_NAME, "HHEZJUREHHEZJUREHHEZJURE".getBytes());
createFile(longNameDir, Constants.CONTENTS_FILE_NAME, new byte[]{65});
Assertions.assertDoesNotThrow(() -> {
Files.delete(cleartextDirectory);
});
}
@Test
public void testDeleteNonEmptyDir() throws IOException {
Path cleartextDirectory = fileSystem.getPath("/d");
Files.createDirectory(cleartextDirectory);
createFile(cleartextDirectory, "test", new byte[]{65});
Assertions.assertThrows(DirectoryNotEmptyException.class, () -> {
Files.delete(cleartextDirectory);
});
}
@Test
public void testDeleteDirectoryContainingLongNamedDirectory() throws IOException {
Path cleartextDirectory = fileSystem.getPath("/e");
Files.createDirectory(cleartextDirectory);
// a
// .. LongNameaaa...
String name = "LongName" + Strings.repeat("a", Constants.DEFAULT_SHORTENING_THRESHOLD);
createFolder(cleartextDirectory, name);
Assertions.assertThrows(DirectoryNotEmptyException.class, () -> {
Files.delete(cleartextDirectory);
});
}
@Test
public void testDeleteEmptyDir() throws IOException {
Path cleartextDirectory = fileSystem.getPath("/f");
Files.createDirectory(cleartextDirectory);
Assertions.assertDoesNotThrow(() -> {
Files.delete(cleartextDirectory);
});
}
private Path firstEmptyCiphertextDirectory() throws IOException {
try (Stream<Path> allFilesInVaultDir = Files.walk(pathToVault)) {
return allFilesInVaultDir //
.filter(Files::isDirectory) //
.filter(this::isEmptyCryptoFsDirectory) //
.filter(this::isEncryptedDirectory) //
.findFirst() //
.get();
}
}
private boolean isEmptyCryptoFsDirectory(Path path) {
Predicate<Path> isIgnoredFile = p -> Constants.DIR_ID_FILE.equals(p.getFileName().toString());
try (Stream<Path> files = Files.list(path)) {
return files.noneMatch(isIgnoredFile.negate());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Test
@DisplayName("Tests internal cryptofs directory emptiness definition")
public void testCryptoFsDirEmptiness() throws IOException {
var emptiness = pathToVault.getParent().resolve("emptiness");
var ignoredFile = emptiness.resolve(Constants.DIR_ID_FILE);
Files.createDirectory(emptiness);
Files.createFile(ignoredFile);
boolean result = isEmptyCryptoFsDirectory(emptiness);
Assertions.assertTrue(result, "Ciphertext directory containing only dirId-file should be accepted as an empty dir");
}
private boolean isEncryptedDirectory(Path pathInVault) {
Path relativePath = pathToVault.relativize(pathInVault);
String relativePathAsString = relativePath.toString().replace(File.separatorChar, '/');
return relativePathAsString.matches("d/[2-7A-Z]{2}/[2-7A-Z]{30}");
}
private Path createFolder(Path parent, String name) throws IOException {
Path result = parent.resolve(name);
Files.createDirectory(result);
return result;
}
private Path createFile(Path parent, String name, byte[] data) throws IOException {
Path result = parent.resolve(name);
Files.write(result, data, CREATE_NEW);
return result;
}
}
| src/test/java/org/cryptomator/cryptofs/DeleteNonEmptyCiphertextDirectoryIntegrationTest.java | /*******************************************************************************
* Copyright (c) 2016 Sebastian Stenzel and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the accompanying LICENSE.txt.
*
* Contributors:
* Sebastian Stenzel - initial API and implementation
*******************************************************************************/
package org.cryptomator.cryptofs;
import com.google.common.base.Strings;
import org.cryptomator.cryptofs.common.Constants;
import org.cryptomator.cryptolib.api.Masterkey;
import org.cryptomator.cryptolib.api.MasterkeyLoader;
import org.cryptomator.cryptolib.api.MasterkeyLoadingFailedException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mockito;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.function.Predicate;
import java.util.stream.Stream;
import static java.nio.file.StandardOpenOption.CREATE_NEW;
import static org.cryptomator.cryptofs.CryptoFileSystemUri.create;
/**
* Regression tests https://github.com/cryptomator/cryptofs/issues/17.
*/
public class DeleteNonEmptyCiphertextDirectoryIntegrationTest {
private static Path pathToVault;
private static FileSystem fileSystem;
@BeforeAll
public static void setupClass(@TempDir Path tmpDir) throws IOException, MasterkeyLoadingFailedException {
pathToVault = tmpDir.resolve("vault");
Files.createDirectory(pathToVault);
MasterkeyLoader keyLoader = Mockito.mock(MasterkeyLoader.class);
Mockito.when(keyLoader.loadKey(Mockito.any())).thenAnswer(ignored -> new Masterkey(new byte[64]));
CryptoFileSystemProperties properties = CryptoFileSystemProperties.cryptoFileSystemProperties().withKeyLoader(keyLoader).build();
CryptoFileSystemProvider.initialize(pathToVault, properties, URI.create("test:key"));
fileSystem = new CryptoFileSystemProvider().newFileSystem(create(pathToVault), properties);
}
@Test
public void testDeleteCiphertextDirectoryContainingNonCryptoFile() throws IOException {
Path cleartextDirectory = fileSystem.getPath("/z");
Files.createDirectory(cleartextDirectory);
Path ciphertextDirectory = firstEmptyCiphertextDirectory();
createFile(ciphertextDirectory, "foo01234.txt", new byte[]{65});
Assertions.assertDoesNotThrow(() -> {
Files.delete(cleartextDirectory);
});
}
@Test
public void testDeleteCiphertextDirectoryContainingDirectories() throws IOException {
Path cleartextDirectory = fileSystem.getPath("/a");
Files.createDirectory(cleartextDirectory);
Path ciphertextDirectory = firstEmptyCiphertextDirectory();
// ciphertextDir
// .. foo0123
// .... foobar
// ...... test.baz
// .... text.txt
// .... text.data
Path foo0123 = createFolder(ciphertextDirectory, "foo0123");
Path foobar = createFolder(foo0123, "foobar");
createFile(foo0123, "test.txt", new byte[]{65});
createFile(foo0123, "text.data", new byte[]{65});
createFile(foobar, "test.baz", new byte[]{65});
Assertions.assertDoesNotThrow(() -> {
Files.delete(cleartextDirectory);
});
}
@Test
@Disabled // c9s not yet implemented
public void testDeleteDirectoryContainingLongNameFileWithoutMetadata() throws IOException {
Path cleartextDirectory = fileSystem.getPath("/b");
Files.createDirectory(cleartextDirectory);
Path ciphertextDirectory = firstEmptyCiphertextDirectory();
Path longNameDir = createFolder(ciphertextDirectory, "HHEZJURE.c9s");
createFile(longNameDir, Constants.CONTENTS_FILE_NAME, new byte[]{65});
Assertions.assertDoesNotThrow(() -> {
Files.delete(cleartextDirectory);
});
}
@Test
@Disabled // c9s not yet implemented
public void testDeleteDirectoryContainingUnauthenticLongNameDirectoryFile() throws IOException {
Path cleartextDirectory = fileSystem.getPath("/c");
Files.createDirectory(cleartextDirectory);
Path ciphertextDirectory = firstEmptyCiphertextDirectory();
Path longNameDir = createFolder(ciphertextDirectory, "HHEZJURE.c9s");
createFile(longNameDir, Constants.INFLATED_FILE_NAME, "HHEZJUREHHEZJUREHHEZJURE".getBytes());
createFile(longNameDir, Constants.CONTENTS_FILE_NAME, new byte[]{65});
Assertions.assertDoesNotThrow(() -> {
Files.delete(cleartextDirectory);
});
}
@Test
public void testDeleteNonEmptyDir() throws IOException {
Path cleartextDirectory = fileSystem.getPath("/d");
Files.createDirectory(cleartextDirectory);
createFile(cleartextDirectory, "test", new byte[]{65});
Assertions.assertThrows(DirectoryNotEmptyException.class, () -> {
Files.delete(cleartextDirectory);
});
}
@Test
public void testDeleteDirectoryContainingLongNamedDirectory() throws IOException {
Path cleartextDirectory = fileSystem.getPath("/e");
Files.createDirectory(cleartextDirectory);
// a
// .. LongNameaaa...
String name = "LongName" + Strings.repeat("a", Constants.DEFAULT_SHORTENING_THRESHOLD);
createFolder(cleartextDirectory, name);
Assertions.assertThrows(DirectoryNotEmptyException.class, () -> {
Files.delete(cleartextDirectory);
});
}
@Test
public void testDeleteEmptyDir() throws IOException {
Path cleartextDirectory = fileSystem.getPath("/f");
Files.createDirectory(cleartextDirectory);
Assertions.assertDoesNotThrow(() -> {
Files.delete(cleartextDirectory);
});
}
private Path firstEmptyCiphertextDirectory() throws IOException {
try (Stream<Path> allFilesInVaultDir = Files.walk(pathToVault)) {
return allFilesInVaultDir //
.filter(Files::isDirectory) //
.filter(this::isEmptyCryptoFsDirectory) //
.filter(this::isEncryptedDirectory) //
.findFirst() //
.get();
}
}
private boolean isEmptyCryptoFsDirectory(Path path) {
Predicate<Path> isIgnoredFile = p -> Constants.DIR_ID_FILE.equals(p.getFileName().toString());
try (Stream<Path> files = Files.list(path)) {
return files.filter(isIgnoredFile.negate()).findFirst().isEmpty();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Test
@DisplayName("Tests internal cryptofs directory emptiness definition")
public void testCryptoFsDirEmptiness() throws IOException {
var emptiness = pathToVault.getParent().resolve("emptiness");
var ignoredFile = emptiness.resolve(Constants.DIR_ID_FILE);
Files.createDirectory(emptiness);
Files.createFile(ignoredFile);
boolean result = isEmptyCryptoFsDirectory(emptiness);
Assertions.assertTrue(result, "Ciphertext directory containing only dirId-file should be accepted as an empty dir");
}
private boolean isEncryptedDirectory(Path pathInVault) {
Path relativePath = pathToVault.relativize(pathInVault);
String relativePathAsString = relativePath.toString().replace(File.separatorChar, '/');
return relativePathAsString.matches("d/[2-7A-Z]{2}/[2-7A-Z]{30}");
}
private Path createFolder(Path parent, String name) throws IOException {
Path result = parent.resolve(name);
Files.createDirectory(result);
return result;
}
private Path createFile(Path parent, String name, byte[] data) throws IOException {
Path result = parent.resolve(name);
Files.write(result, data, CREATE_NEW);
return result;
}
}
| Partially revert 2c0b6d6d1db43c696b4c6bd33f24468a575c41e0
| src/test/java/org/cryptomator/cryptofs/DeleteNonEmptyCiphertextDirectoryIntegrationTest.java | Partially revert 2c0b6d6d1db43c696b4c6bd33f24468a575c41e0 | <ide><path>rc/test/java/org/cryptomator/cryptofs/DeleteNonEmptyCiphertextDirectoryIntegrationTest.java
<ide> private boolean isEmptyCryptoFsDirectory(Path path) {
<ide> Predicate<Path> isIgnoredFile = p -> Constants.DIR_ID_FILE.equals(p.getFileName().toString());
<ide> try (Stream<Path> files = Files.list(path)) {
<del> return files.filter(isIgnoredFile.negate()).findFirst().isEmpty();
<add> return files.noneMatch(isIgnoredFile.negate());
<ide> } catch (IOException e) {
<ide> throw new UncheckedIOException(e);
<ide> } |
|
Java | epl-1.0 | e671274bd329927e311a50c7fae2bc320fd15c36 | 0 | sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt | /*******************************************************************************
* Copyright (c) 2007 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.chart.reportitem.ui;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.model.Chart;
import org.eclipse.birt.chart.model.ChartWithAxes;
import org.eclipse.birt.chart.model.DialChart;
import org.eclipse.birt.chart.model.component.Series;
import org.eclipse.birt.chart.model.data.Query;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.chart.model.type.BubbleSeries;
import org.eclipse.birt.chart.model.type.DifferenceSeries;
import org.eclipse.birt.chart.model.type.GanttSeries;
import org.eclipse.birt.chart.model.type.StockSeries;
import org.eclipse.birt.chart.plugin.ChartEnginePlugin;
import org.eclipse.birt.chart.reportitem.ChartReportItemUtil;
import org.eclipse.birt.chart.reportitem.ui.dialogs.ChartColumnBindingDialog;
import org.eclipse.birt.chart.reportitem.ui.dialogs.ExtendedItemFilterDialog;
import org.eclipse.birt.chart.reportitem.ui.dialogs.ReportItemParametersDialog;
import org.eclipse.birt.chart.reportitem.ui.i18n.Messages;
import org.eclipse.birt.chart.ui.swt.ColorPalette;
import org.eclipse.birt.chart.ui.swt.CustomPreviewTable;
import org.eclipse.birt.chart.ui.swt.DataDefinitionTextManager;
import org.eclipse.birt.chart.ui.swt.DefaultChartDataSheet;
import org.eclipse.birt.chart.ui.swt.SimpleTextTransfer;
import org.eclipse.birt.chart.ui.swt.wizard.ChartAdapter;
import org.eclipse.birt.chart.ui.swt.wizard.ChartWizard;
import org.eclipse.birt.chart.ui.util.ChartHelpContextIds;
import org.eclipse.birt.chart.ui.util.ChartUIUtil;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.ui.frameworks.taskwizard.WizardBase;
import org.eclipse.birt.report.designer.internal.ui.dialogs.ExpressionFilter;
import org.eclipse.birt.report.designer.internal.ui.views.ViewsTreeProvider;
import org.eclipse.birt.report.designer.ui.actions.NewDataSetAction;
import org.eclipse.birt.report.designer.ui.dialogs.ColumnBindingDialog;
import org.eclipse.birt.report.designer.ui.dialogs.ExpressionProvider;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.metadata.IClassInfo;
import org.eclipse.birt.report.model.api.olap.CubeHandle;
import org.eclipse.birt.report.model.api.olap.DimensionHandle;
import org.eclipse.birt.report.model.api.olap.LevelHandle;
import org.eclipse.birt.report.model.api.olap.MeasureHandle;
import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.PlatformUI;
/**
* Data sheet implementation for Standard Chart
*/
public final class StandardChartDataSheet extends DefaultChartDataSheet
implements
Listener
{
final private ExtendedItemHandle itemHandle;
final private ReportDataServiceProvider dataProvider;
/**
* The field indicates if any operation in this class cause some exception
* or error.
*/
private boolean fbException = false;
private Button btnInherit = null;
private Button btnUseData = null;
private Combo cmbDataItems = null;
private Button btnNewData = null;
private StackLayout stackLayout = null;
private Composite cmpStack = null;
private Composite cmpCubeTree = null;
private Composite cmpDataPreview = null;
private CustomPreviewTable tablePreview = null;
private TreeViewer cubeTreeViewer = null;
private Button btnFilters = null;
private Button btnParameters = null;
private Button btnBinding = null;
private static final int SELECT_NONE = 0;
private static final int SELECT_NEXT = 1;
private static final int SELECT_DATA_SET = 2;
private static final int SELECT_DATA_CUBE = 3;
private static final int SELECT_REPORT_ITEM = 4;
private List selectDataTypes = new ArrayList( );
public StandardChartDataSheet( ExtendedItemHandle itemHandle,
ReportDataServiceProvider dataProvider )
{
this.itemHandle = itemHandle;
this.dataProvider = dataProvider;
}
public Composite createActionButtons( Composite parent )
{
Composite composite = ChartUIUtil.createCompositeWrapper( parent );
{
composite.setLayoutData( new GridData( GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_END ) );
}
btnFilters = new Button( composite, SWT.NONE );
{
btnFilters.setAlignment( SWT.CENTER );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
btnFilters.setLayoutData( gridData );
btnFilters.setText( Messages.getString( "StandardChartDataSheet.Label.Filters" ) ); //$NON-NLS-1$
btnFilters.addListener( SWT.Selection, this );
}
btnParameters = new Button( composite, SWT.NONE );
{
btnParameters.setAlignment( SWT.CENTER );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
btnParameters.setLayoutData( gridData );
btnParameters.setText( Messages.getString( "StandardChartDataSheet.Label.Parameters" ) ); //$NON-NLS-1$
btnParameters.addListener( SWT.Selection, this );
}
btnBinding = new Button( composite, SWT.NONE );
{
btnBinding.setAlignment( SWT.CENTER );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
btnBinding.setLayoutData( gridData );
btnBinding.setText( Messages.getString( "StandardChartDataSheet.Label.DataBinding" ) ); //$NON-NLS-1$
btnBinding.addListener( SWT.Selection, this );
}
setEnabledForButtons( );
return composite;
}
private void setEnabledForButtons( )
{
btnNewData.setEnabled( btnUseData.getSelection( ) );
if ( isCubeMode( ) )
{
btnFilters.setEnabled( false );
// btnFilters.setEnabled( getDataServiceProvider(
// ).isInvokingSupported( ) );
btnBinding.setEnabled( getDataServiceProvider( ).isInvokingSupported( ) );
btnParameters.setEnabled( false );
}
else
{
btnFilters.setEnabled( hasDataSet( )
&& getDataServiceProvider( ).isInvokingSupported( ) );
// Bugzilla#177704 Chart inheriting data from container doesn't
// support parameters due to limitation in DtE
btnParameters.setEnabled( getDataServiceProvider( ).getBoundDataSet( ) != null
&& getDataServiceProvider( ).isInvokingSupported( ) );
btnBinding.setEnabled( hasDataSet( )
&& getDataServiceProvider( ).isInvokingSupported( ) );
}
}
private boolean hasDataSet( )
{
return getDataServiceProvider( ).getReportDataSet( ) != null
|| getDataServiceProvider( ).getBoundDataSet( ) != null;
}
void fireEvent( Widget widget, int eventType )
{
Event event = new Event( );
event.data = this;
event.widget = widget;
event.type = eventType;
notifyListeners( eventType, event );
}
public Composite createDataDragSource( Composite parent )
{
cmpStack = new Composite( parent, SWT.NONE );
cmpStack.setLayoutData( new GridData( GridData.FILL_BOTH ) );
stackLayout = new StackLayout( );
stackLayout.marginHeight = 0;
stackLayout.marginWidth = 0;
cmpStack.setLayout( stackLayout );
cmpCubeTree = ChartUIUtil.createCompositeWrapper( cmpStack );
cmpDataPreview = ChartUIUtil.createCompositeWrapper( cmpStack );
Label label = new Label( cmpCubeTree, SWT.NONE );
{
label.setText( Messages.getString( "StandardChartDataSheet.Label.CubeTree" ) ); //$NON-NLS-1$
label.setFont( JFaceResources.getBannerFont( ) );
}
Label description = new Label( cmpCubeTree, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
description.setLayoutData( gd );
description.setText( Messages.getString( "StandardChartDataSheet.Label.DragCube" ) ); //$NON-NLS-1$
}
cubeTreeViewer = new TreeViewer( cmpCubeTree, SWT.SINGLE
| SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER );
cubeTreeViewer.getTree( )
.setLayoutData( new GridData( GridData.FILL_BOTH ) );
( (GridData) cubeTreeViewer.getTree( ).getLayoutData( ) ).heightHint = 120;
ViewsTreeProvider provider = new ViewsTreeProvider( );
cubeTreeViewer.setLabelProvider( provider );
cubeTreeViewer.setContentProvider( provider );
cubeTreeViewer.setInput( getCube( ) );
final DragSource dragSource = new DragSource( cubeTreeViewer.getTree( ),
DND.DROP_COPY );
dragSource.setTransfer( new Transfer[]{
SimpleTextTransfer.getInstance( )
} );
dragSource.addDragListener( new DragSourceListener( ) {
private String text = null;
public void dragFinished( DragSourceEvent event )
{
// TODO Auto-generated method stub
}
public void dragSetData( DragSourceEvent event )
{
event.data = text;
}
public void dragStart( DragSourceEvent event )
{
text = createCubeExpression( );
if ( text == null )
{
event.doit = false;
}
}
} );
cubeTreeViewer.getTree( ).addListener( SWT.MouseDown, new Listener( ) {
public void handleEvent( Event event )
{
if ( event.button == 3 && event.widget instanceof Tree )
{
Tree tree = (Tree) event.widget;
TreeItem treeItem = tree.getSelection( )[0];
if ( treeItem.getData( ) instanceof LevelHandle
|| treeItem.getData( ) instanceof MeasureHandle )
{
tree.setMenu( createMenuManager( treeItem.getData( ) ).createContextMenu( tree ) );
tree.getMenu( ).setVisible( true );
}
else
{
tree.setMenu( null );
}
}
}
} );
label = new Label( cmpDataPreview, SWT.NONE );
{
label.setText( Messages.getString( "StandardChartDataSheet.Label.DataPreview" ) ); //$NON-NLS-1$
label.setFont( JFaceResources.getBannerFont( ) );
}
description = new Label( cmpDataPreview, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
description.setLayoutData( gd );
description.setText( Messages.getString( "StandardChartDataSheet.Label.ToBindADataColumn" ) ); //$NON-NLS-1$
}
tablePreview = new CustomPreviewTable( cmpDataPreview, SWT.SINGLE
| SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION );
{
GridData gridData = new GridData( GridData.FILL_BOTH );
gridData.widthHint = 400;
gridData.heightHint = 120;
tablePreview.setLayoutData( gridData );
tablePreview.setHeaderAlignment( SWT.LEFT );
tablePreview.addListener( CustomPreviewTable.MOUSE_RIGHT_CLICK_TYPE,
this );
}
updateDragDataSource( );
return cmpStack;
}
private void updateDragDataSource( )
{
if ( isCubeMode( ) )
{
stackLayout.topControl = cmpCubeTree;
cubeTreeViewer.setInput( getCube( ) );
}
else
{
stackLayout.topControl = cmpDataPreview;
refreshTablePreview( );
}
cmpStack.layout( );
}
public Composite createDataSelector( Composite parent )
{
Composite cmpDataSet = ChartUIUtil.createCompositeWrapper( parent );
{
cmpDataSet.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
}
Label label = new Label( cmpDataSet, SWT.NONE );
{
label.setText( Messages.getString( "StandardChartDataSheet.Label.SelectDataSet" ) ); //$NON-NLS-1$
label.setFont( JFaceResources.getBannerFont( ) );
}
Composite cmpDetail = new Composite( cmpDataSet, SWT.NONE );
{
GridLayout gridLayout = new GridLayout( 3, false );
gridLayout.marginWidth = 10;
gridLayout.marginHeight = 0;
cmpDetail.setLayout( gridLayout );
cmpDetail.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
}
Composite compRadios = ChartUIUtil.createCompositeWrapper( cmpDetail );
{
GridData gd = new GridData( );
gd.verticalSpan = 2;
compRadios.setLayoutData( gd );
}
btnInherit = new Button( compRadios, SWT.RADIO );
btnInherit.setText( Messages.getString( "StandardChartDataSheet.Label.UseReportData" ) ); //$NON-NLS-1$
btnInherit.addListener( SWT.Selection, this );
btnUseData = new Button( compRadios, SWT.RADIO );
btnUseData.setText( Messages.getString( "StandardChartDataSheet.Label.UseDataSet" ) ); //$NON-NLS-1$
btnUseData.addListener( SWT.Selection, this );
new Label( cmpDetail, SWT.NONE );
new Label( cmpDetail, SWT.NONE );
cmbDataItems = new Combo( cmpDetail, SWT.DROP_DOWN | SWT.READ_ONLY );
cmbDataItems.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
cmbDataItems.addListener( SWT.Selection, this );
btnNewData = new Button( cmpDetail, SWT.NONE );
{
btnNewData.setText( Messages.getString( "StandardChartDataSheet.Label.CreateNew" ) ); //$NON-NLS-1$
btnNewData.setToolTipText( Messages.getString( "StandardChartDataSheet.Tooltip.CreateNewDataset" ) ); //$NON-NLS-1$
btnNewData.addListener( SWT.Selection, this );
}
initDataSelector( );
return cmpDataSet;
}
int invokeNewDataSet( )
{
IAction action = new NewDataSetAction( );
PlatformUI.getWorkbench( ).getHelpSystem( ).setHelp( action,
ChartHelpContextIds.DIALOG_NEW_DATA_SET );
action.run( );
// Due to the limitation of the action execution, always return ok
return Window.OK;
}
int invokeEditFilter( )
{
ExtendedItemHandle handle = getItemHandle( );
handle.getModuleHandle( ).getCommandStack( ).startTrans( null );
ExtendedItemFilterDialog page = new ExtendedItemFilterDialog( handle );
int openStatus = page.open( );
if ( openStatus == Window.OK )
{
handle.getModuleHandle( ).getCommandStack( ).commit( );
}
else
{
handle.getModuleHandle( ).getCommandStack( ).rollback( );
}
return openStatus;
}
int invokeEditParameter( )
{
ReportItemParametersDialog page = new ReportItemParametersDialog( getItemHandle( ) );
return page.open( );
}
int invokeDataBinding( )
{
Shell shell = new Shell( Display.getDefault( ), SWT.DIALOG_TRIM
| SWT.RESIZE | SWT.APPLICATION_MODAL );
// #194163: Do not register CS help in chart since it's registered in
// super column binding dialog.
// ChartUIUtil.bindHelp( shell,
// ChartHelpContextIds.DIALOG_DATA_SET_COLUMN_BINDING );
ColumnBindingDialog page = new ChartColumnBindingDialog( shell );
ExtendedItemHandle handle = getItemHandle();
handle.getModuleHandle( ).getCommandStack( ).startTrans( null );
page.setInput( handle );
ExpressionProvider ep = new ExpressionProvider( getItemHandle( ) );
ep.addFilter( new ExpressionFilter( ) {
public boolean select( Object parentElement, Object element )
{
// Remove unsupported expression. See bugzilla#132768
return !( parentElement.equals( ExpressionProvider.BIRT_OBJECTS ) &&
element instanceof IClassInfo && ( (IClassInfo) element ).getName( )
.equals( "Total" ) ); //$NON-NLS-1$
}
} );
page.setExpressionProvider( ep );
int openStatus = page.open( );
if ( openStatus == Window.OK )
{
handle.getModuleHandle( ).getCommandStack( ).commit( );
}
else
{
handle.getModuleHandle( ).getCommandStack( ).rollback( );
}
return openStatus;
}
private void initDataSelector( )
{
// create Combo items
cmbDataItems.setItems( createDataComboItems( ) );
// Select report item reference
// Since handle may have data set or data cube besides reference, always
// check reference first
String sItemRef = getDataServiceProvider( ).getReportItemReference( );
if ( sItemRef != null )
{
btnUseData.setSelection( true );
cmbDataItems.setText( sItemRef );
return;
}
// Select data set
String sDataSet = getDataServiceProvider( ).getBoundDataSet( );
if ( sDataSet != null )
{
btnUseData.setSelection( true );
cmbDataItems.setText( sDataSet );
if ( sDataSet != null )
{
switchDataTable( );
}
return;
}
// Select data cube
String sDataCube = getDataServiceProvider( ).getDataCube( );
if ( sDataCube != null )
{
btnUseData.setSelection( true );
cmbDataItems.setText( sDataCube );
return;
}
btnInherit.setSelection( true );
cmbDataItems.select( 0 );
cmbDataItems.setEnabled( false );
// Initializes column bindings from container
getDataServiceProvider( ).setDataSet( null );
String reportDataSet = getDataServiceProvider( ).getReportDataSet( );
if ( reportDataSet != null )
{
switchDataTable( );
}
// select reference item
// selectItemRef( );
// if ( cmbReferences.getSelectionIndex( ) > 0 )
// {
// cmbDataSet.setEnabled( false );
// btnUseReference.setSelection( true );
// btnUseReportData.setSelection( false );
// btnUseDataSet.setSelection( false );
// }
// else
// {
// cmbReferences.setEnabled( false );
// }
//
// String dataCube = getDataServiceProvider( ).getDataCube( );
// if ( dataCube != null )
// {
// cmbCubes.setText( dataCube );
// btnUseReference.setSelection( false );
// btnUseReportData.setSelection( false );
// btnUseDataSet.setSelection( false );
// btnUseCubes.setSelection( true );
// }
// else
// {
// cmbCubes.select( 0 );
// }
}
public void handleEvent( Event event )
{
fbException = false;
// Right click to display the menu. Menu display by clicking
// application key is triggered by os, so do nothing.
if ( event.type == CustomPreviewTable.MOUSE_RIGHT_CLICK_TYPE )
{
if ( getDataServiceProvider( ).getBoundDataSet( ) != null
|| getDataServiceProvider( ).getReportDataSet( ) != null )
{
if ( event.widget instanceof Button )
{
Button header = (Button) event.widget;
// Bind context menu to each header button
if ( header.getMenu( ) == null )
{
header.setMenu( createMenuManager( event.data ).createContextMenu( tablePreview ) );
}
header.getMenu( ).setVisible( true );
}
}
}
else if ( event.type == SWT.Selection )
{
if ( event.widget instanceof MenuItem )
{
MenuItem item = (MenuItem) event.widget;
IAction action = (IAction) item.getData( );
action.setChecked( !action.isChecked( ) );
action.run( );
}
else if ( event.widget == btnFilters )
{
if ( invokeEditFilter( ) == Window.OK )
{
refreshTablePreview( );
// Update preview via event
fireEvent( btnFilters, EVENT_UPDATE );
}
}
else if ( event.widget == btnParameters )
{
if ( invokeEditParameter( ) == Window.OK )
{
refreshTablePreview( );
// Update preview via event
fireEvent( btnParameters, EVENT_UPDATE );
}
}
else if ( event.widget == btnBinding )
{
if ( invokeDataBinding( ) == Window.OK )
{
refreshTablePreview( );
// Update preview via event
fireEvent( btnBinding, EVENT_UPDATE );
}
}
try
{
if ( event.widget == btnInherit )
{
ColorPalette.getInstance( ).restore( );
// Skip when selection is false
if ( !btnInherit.getSelection( ) )
{
return;
}
getDataServiceProvider( ).setReportItemReference( null );
getDataServiceProvider( ).setDataSet( null );
switchDataSet( null );
cmbDataItems.select( 0 );
cmbDataItems.setEnabled( false );
setEnabledForButtons( );
updateDragDataSource( );
}
else if ( event.widget == btnUseData )
{
// Skip when selection is false
if ( !btnUseData.getSelection( ) )
{
return;
}
getDataServiceProvider( ).setReportItemReference( null );
selectDataSet( );
cmbDataItems.setEnabled( true );
setEnabledForButtons( );
updateDragDataSource( );
}
else if ( event.widget == cmbDataItems )
{
ColorPalette.getInstance( ).restore( );
int selectedIndex = cmbDataItems.getSelectionIndex( );
Integer selectState = (Integer) selectDataTypes.get( selectedIndex );
switch ( selectState.intValue( ) )
{
case SELECT_NONE :
// Inherit data from container
btnInherit.setSelection( true );
btnUseData.setSelection( false );
btnInherit.notifyListeners( SWT.Selection,
new Event( ) );
break;
case SELECT_NEXT :
selectedIndex++;
selectState = (Integer) selectDataTypes.get( selectedIndex );
cmbDataItems.select( selectedIndex );
break;
}
switch ( selectState.intValue( ) )
{
case SELECT_DATA_SET :
if ( getDataServiceProvider( ).getBoundDataSet( ) != null
&& getDataServiceProvider( ).getBoundDataSet( )
.equals( cmbDataItems.getText( ) ) )
{
return;
}
getDataServiceProvider( ).setDataSet( cmbDataItems.getText( ) );
switchDataSet( cmbDataItems.getText( ) );
setEnabledForButtons( );
updateDragDataSource( );
break;
case SELECT_DATA_CUBE :
getDataServiceProvider( ).setDataCube( cmbDataItems.getText( ) );
updateDragDataSource( );
setEnabledForButtons( );
break;
case SELECT_REPORT_ITEM :
if ( cmbDataItems.getText( )
.equals( getDataServiceProvider( ).getReportItemReference( ) ) )
{
return;
}
getDataServiceProvider( ).setReportItemReference( cmbDataItems.getText( ) );
// selectDataSet( );
// switchDataSet( cmbDataItems.getText( ) );
setEnabledForButtons( );
updateDragDataSource( );
break;
}
}
// else if ( event.widget == btnUseReference )
// {
// // Skip when selection is false
// if ( !btnUseReference.getSelection( ) )
// {
// return;
// }
// cmbDataSet.setEnabled( false );
// cmbReferences.setEnabled( true );
// selectItemRef( );
// setEnabledForButtons( );
// }
// else if ( event.widget == cmbReferences )
// {
// if ( cmbReferences.getSelectionIndex( ) == 0 )
// {
// if ( getDataServiceProvider( ).getReportItemReference( ) ==
// null )
// {
// return;
// }
// getDataServiceProvider( ).setReportItemReference( null );
//
// // Auto select the data set
// selectDataSet( );
// cmbReferences.setEnabled( false );
// cmbDataSet.setEnabled( true );
// btnUseReference.setSelection( false );
// btnUseDataSet.setSelection( true );
// }
// else
// {
// if ( cmbReferences.getText( )
// .equals( getDataServiceProvider( ).getReportItemReference( )
// ) )
// {
// return;
// }
// getDataServiceProvider( ).setReportItemReference(
// cmbReferences.getText( ) );
// selectDataSet( );
// }
// switchDataSet( cmbDataSet.getText( ) );
// setEnabledForButtons( );
// }
else if ( event.widget == btnNewData )
{
// Bring up the dialog to create a dataset
int result = invokeNewDataSet( );
if ( result == Window.CANCEL )
{
return;
}
String currentDataSet = cmbDataItems.getText( );
cmbDataItems.removeAll( );
cmbDataItems.setItems( createDataComboItems( ) );
cmbDataItems.setText( currentDataSet );
}
}
catch ( ChartException e1 )
{
fbException = true;
ChartWizard.showException( e1.getLocalizedMessage( ) );
}
}
if ( !fbException )
{
WizardBase.removeException( );
}
}
private void selectDataSet( )
{
String currentDS = getDataServiceProvider( ).getBoundDataSet( );
if ( currentDS == null )
{
cmbDataItems.select( 0 );
}
else
{
cmbDataItems.setText( currentDS );
}
}
private void refreshTablePreview( )
{
if ( dataProvider.getDataSetFromHandle( ) == null )
{
return;
}
tablePreview.clearContents( );
switchDataTable( );
tablePreview.layout( );
}
private void switchDataSet( String datasetName ) throws ChartException
{
if ( isCubeMode( ) )
{
return;
}
try
{
// Clear old dataset and preview data
tablePreview.clearContents( );
// Try to get report data set
if ( datasetName == null )
{
datasetName = getDataServiceProvider( ).getReportDataSet( );
}
if ( datasetName != null )
{
switchDataTable( );
}
else
{
tablePreview.createDummyTable( );
}
tablePreview.layout( );
}
catch ( Throwable t )
{
throw new ChartException( ChartEnginePlugin.ID,
ChartException.DATA_BINDING,
t );
}
DataDefinitionTextManager.getInstance( ).refreshAll( );
// Update preview via event
fireEvent( tablePreview, EVENT_UPDATE );
}
private void switchDataTable( )
{
if ( isCubeMode( ) )
{
return;
}
// 1. Create a runnable.
Runnable runnable = new Runnable( ) {
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
*/
public void run( )
{
try
{
// Get header and data in other thread.
final String[] header = getDataServiceProvider( ).getPreviewHeader( );
final List dataList = getDataServiceProvider( ).getPreviewData( );
// Execute UI operation in UI thread.
Display.getDefault( ).syncExec( new Runnable( ) {
public void run( )
{
if ( tablePreview.isDisposed( ) )
{
return;
}
if ( header == null )
{
tablePreview.setEnabled( false );
tablePreview.createDummyTable( );
}
else
{
tablePreview.setEnabled( true );
tablePreview.setColumns( header );
refreshTableColor( );
// Add data value
for ( Iterator iterator = dataList.iterator( ); iterator.hasNext( ); )
{
String[] dataRow = (String[]) iterator.next( );
for ( int i = 0; i < dataRow.length; i++ )
{
tablePreview.addEntry( dataRow[i], i );
}
}
}
tablePreview.layout( );
}
} );
}
catch ( Exception e )
{
// Catch any exception.
final String msg = e.getMessage( );
Display.getDefault( ).syncExec( new Runnable( ) {
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
public void run( )
{
fbException = true;
WizardBase.showException( msg );
}
} );
}
}
};
// 2. Run it.
new Thread( runnable ).start( );
}
private void refreshTableColor( )
{
if ( isCubeMode( ) )
{
return;
}
// Reset column color
for ( int i = 0; i < tablePreview.getColumnNumber( ); i++ )
{
tablePreview.setColumnColor( i,
ColorPalette.getInstance( )
.getColor( ExpressionUtil.createJSRowExpression( tablePreview.getColumnHeading( i ) ) ) );
}
}
private void manageColorAndQuery( Query query, String expr )
{
// If it's not used any more, remove color binding
if ( DataDefinitionTextManager.getInstance( )
.getNumberOfSameDataDefinition( query.getDefinition( ) ) == 0 )
{
ColorPalette.getInstance( ).retrieveColor( query.getDefinition( ) );
}
query.setDefinition( expr );
DataDefinitionTextManager.getInstance( ).updateText( query );
// Reset table column color
refreshTableColor( );
// Refresh all data definition text
DataDefinitionTextManager.getInstance( ).refreshAll( );
}
class CategoryXAxisAction extends Action
{
String expr;
CategoryXAxisAction( String expr )
{
super( getBaseSeriesTitle( getChartModel( ) ) );
this.expr = expr;
}
public void run( )
{
Query query = ( (Query) ( (SeriesDefinition) ChartUIUtil.getBaseSeriesDefinitions( getChartModel( ) )
.get( 0 ) ).getDesignTimeSeries( )
.getDataDefinition( )
.get( 0 ) );
manageColorAndQuery( query, expr );
}
}
class GroupYSeriesAction extends Action
{
Query query;
String expr;
GroupYSeriesAction( Query query, String expr )
{
super( getGroupSeriesTitle( getChartModel( ) ) );
this.query = query;
this.expr = expr;
}
public void run( )
{
// Use the first group, and copy to the all groups
ChartAdapter.beginIgnoreNotifications( );
ChartUIUtil.setAllGroupingQueryExceptFirst( getChartModel( ), expr );
ChartAdapter.endIgnoreNotifications( );
manageColorAndQuery( query, expr );
}
}
class ValueYSeriesAction extends Action
{
Query query;
String expr;
ValueYSeriesAction( Query query, String expr )
{
super( getOrthogonalSeriesTitle( getChartModel( ) ) );
this.query = query;
this.expr = expr;
}
public void run( )
{
manageColorAndQuery( query, expr );
}
}
class HeaderShowAction extends Action
{
HeaderShowAction( String header )
{
super( header );
setEnabled( false );
}
}
ExtendedItemHandle getItemHandle( )
{
return this.itemHandle;
}
ReportDataServiceProvider getDataServiceProvider( )
{
return this.dataProvider;
}
private MenuManager createMenuManager( final Object data )
{
MenuManager menuManager = new MenuManager( );
menuManager.setRemoveAllWhenShown( true );
menuManager.addMenuListener( new IMenuListener( ) {
public void menuAboutToShow( IMenuManager manager )
{
if ( data instanceof Integer )
{
// Menu for table
addMenu( manager,
new HeaderShowAction( tablePreview.getCurrentColumnHeading( ) ) );
String expr = ExpressionUtil.createJSRowExpression( tablePreview.getCurrentColumnHeading( ) );
addMenu( manager,
getBaseSeriesMenu( getChartModel( ), expr ) );
addMenu( manager,
getOrthogonalSeriesMenu( getChartModel( ), expr ) );
addMenu( manager, getGroupSeriesMenu( getChartModel( ),
expr ) );
}
else if ( data instanceof MeasureHandle )
{
// Menu for Measure
String expr = createCubeExpression( );
addMenu( manager,
getOrthogonalSeriesMenu( getChartModel( ), expr ) );
}
else if ( data instanceof LevelHandle )
{
// Menu for Level
String expr = createCubeExpression( );
addMenu( manager,
getBaseSeriesMenu( getChartModel( ), expr ) );
addMenu( manager, getGroupSeriesMenu( getChartModel( ),
expr ) );
}
}
private void addMenu( IMenuManager manager, Object item )
{
if ( item instanceof IAction )
{
manager.add( (IAction) item );
}
else if ( item instanceof IContributionItem )
{
manager.add( (IContributionItem) item );
}
}
} );
return menuManager;
}
private Object getBaseSeriesMenu( Chart chart, String expr )
{
EList sds = ChartUIUtil.getBaseSeriesDefinitions( chart );
if ( sds.size( ) == 1 )
{
return new CategoryXAxisAction( expr );
}
return null;
}
private Object getGroupSeriesMenu( Chart chart, String expr )
{
IMenuManager topManager = new MenuManager( getGroupSeriesTitle( getChartModel( ) ) );
int axisNum = ChartUIUtil.getOrthogonalAxisNumber( chart );
for ( int axisIndex = 0; axisIndex < axisNum; axisIndex++ )
{
List sds = ChartUIUtil.getOrthogonalSeriesDefinitions( chart,
axisIndex );
for ( int i = 0; i < sds.size( ); i++ )
{
SeriesDefinition sd = (SeriesDefinition) sds.get( i );
IAction action = new GroupYSeriesAction( sd.getQuery( ), expr );
// ONLY USE FIRST GROUPING SERIES FOR CHART ENGINE SUPPORT
// if ( axisNum == 1 && sds.size( ) == 1 )
{
// Simply cascade menu
return action;
}
// action.setText( getSecondMenuText( axisIndex,
// i,
// sd.getDesignTimeSeries( ) ) );
// topManager.add( action );
}
}
return topManager;
}
private Object getOrthogonalSeriesMenu( Chart chart, String expr )
{
IMenuManager topManager = new MenuManager( getOrthogonalSeriesTitle( getChartModel( ) ) );
int axisNum = ChartUIUtil.getOrthogonalAxisNumber( chart );
for ( int axisIndex = 0; axisIndex < axisNum; axisIndex++ )
{
List sds = ChartUIUtil.getOrthogonalSeriesDefinitions( chart,
axisIndex );
for ( int i = 0; i < sds.size( ); i++ )
{
Series series = ( (SeriesDefinition) sds.get( i ) ).getDesignTimeSeries( );
EList dataDefns = series.getDataDefinition( );
if ( series instanceof StockSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( (Query) dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getStockTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else if ( series instanceof BubbleSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( (Query) dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getBubbleTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else if ( series instanceof DifferenceSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( (Query) dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getDifferenceTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else if ( series instanceof GanttSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( (Query) dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getGanttTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else
{
IAction action = new ValueYSeriesAction( (Query) dataDefns.get( 0 ),
expr );
if ( axisNum == 1 && sds.size( ) == 1 )
{
// Simplify cascade menu
return action;
}
action.setText( getSecondMenuText( axisIndex, i, series ) );
topManager.add( action );
}
}
}
return topManager;
}
private String getSecondMenuText( int axisIndex, int seriesIndex,
Series series )
{
StringBuffer sb = new StringBuffer( );
if ( ChartUIUtil.getOrthogonalAxisNumber( getChartModel( ) ) > 2 )
{
sb.append( Messages.getString( "DataDefinitionSelector.Label.Axis" ) ); //$NON-NLS-1$
sb.append( axisIndex + 1 );
sb.append( " - " ); //$NON-NLS-1$
}
else
{
if ( axisIndex > 0 )
{
sb.append( Messages.getString( "StandardChartDataSheet.Label.Overlay" ) ); //$NON-NLS-1$
}
}
sb.append( Messages.getString( "StandardChartDataSheet.Label.Series" ) //$NON-NLS-1$
+ ( seriesIndex + 1 ) + " (" + series.getDisplayName( ) + ")" ); //$NON-NLS-1$ //$NON-NLS-2$
return sb.toString( );
}
private String getBaseSeriesTitle( Chart chart )
{
if ( chart instanceof ChartWithAxes )
{
return Messages.getString( "StandardChartDataSheet.Label.UseAsCategoryXAxis" ); //$NON-NLS-1$
}
return Messages.getString( "StandardChartDataSheet.Label.UseAsCategorySeries" ); //$NON-NLS-1$
}
private String getOrthogonalSeriesTitle( Chart chart )
{
if ( chart instanceof ChartWithAxes )
{
return Messages.getString( "StandardChartDataSheet.Label.PlotAsValueYSeries" ); //$NON-NLS-1$
}
else if ( chart instanceof DialChart )
{
return Messages.getString( "StandardChartDataSheet.Label.PlotAsGaugeValue" ); //$NON-NLS-1$
}
return Messages.getString( "StandardChartDataSheet.Label.PlotAsValueSeries" ); //$NON-NLS-1$
}
private String getGroupSeriesTitle( Chart chart )
{
if ( chart instanceof ChartWithAxes )
{
return Messages.getString( "StandardChartDataSheet.Label.UseToGroupYSeries" ); //$NON-NLS-1$
}
return Messages.getString( "StandardChartDataSheet.Label.UseToGroupValueSeries" ); //$NON-NLS-1$
}
private boolean isCubeMode( )
{
return ChartReportItemUtil.getBindingCube( itemHandle ) != null;
}
private CubeHandle getCube( )
{
return ChartReportItemUtil.getBindingCube( itemHandle );
}
/**
* Creates the cube expression
*
* @return expression
*/
private String createCubeExpression( )
{
if ( cubeTreeViewer == null )
{
return null;
}
TreeItem[] selection = cubeTreeViewer.getTree( ).getSelection( );
String expr = null;
if ( selection.length > 0 )
{
TreeItem treeItem = selection[0];
if ( treeItem.getData( ) instanceof LevelHandle )
{
TreeItem dimensionItem = treeItem.getParentItem( );
while ( !( dimensionItem.getData( ) instanceof DimensionHandle ) )
{
dimensionItem = dimensionItem.getParentItem( );
}
expr = ExpressionUtil.createJSDimensionExpression( dimensionItem.getText( ),
treeItem.getText( ) );
}
else if ( treeItem.getData( ) instanceof MeasureHandle )
{
expr = ExpressionUtil.createJSMeasureExpression( treeItem.getText( ) );
}
}
return expr;
}
private String[] createDataComboItems( )
{
List items = new ArrayList( );
selectDataTypes.clear( );
items.add( ReportDataServiceProvider.OPTION_NONE );
selectDataTypes.add( new Integer( SELECT_NONE ) );
String[] dataSets = getDataServiceProvider( ).getAllDataSets( );
if ( dataSets.length > 0 )
{
items.add( Messages.getString( "StandardChartDataSheet.Combo.DataSets" ) ); //$NON-NLS-1$
selectDataTypes.add( new Integer( SELECT_NEXT ) );
for ( int i = 0; i < dataSets.length; i++ )
{
items.add( dataSets[i] );
selectDataTypes.add( new Integer( SELECT_DATA_SET ) );
}
}
String[] dataCubes = getDataServiceProvider( ).getAllDataCubes( );
if ( dataCubes.length > 0 )
{
items.add( Messages.getString( "StandardChartDataSheet.Combo.DataCubes" ) ); //$NON-NLS-1$
selectDataTypes.add( new Integer( SELECT_NEXT ) );
for ( int i = 0; i < dataCubes.length; i++ )
{
items.add( dataCubes[i] );
selectDataTypes.add( new Integer( SELECT_DATA_CUBE ) );
}
}
String[] dataRefs = getDataServiceProvider( ).getAllReportItemReferences( );
if ( dataRefs.length > 0 )
{
items.add( Messages.getString( "StandardChartDataSheet.Combo.ReportItems" ) ); //$NON-NLS-1$
selectDataTypes.add( new Integer( SELECT_NEXT ) );
for ( int i = 0; i < dataRefs.length; i++ )
{
items.add( dataRefs[i] );
selectDataTypes.add( new Integer( SELECT_REPORT_ITEM ) );
}
}
return (String[]) items.toArray( new String[items.size( )] );
}
}
| chart/org.eclipse.birt.chart.reportitem.ui/src/org/eclipse/birt/chart/reportitem/ui/StandardChartDataSheet.java | /*******************************************************************************
* Copyright (c) 2007 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.chart.reportitem.ui;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.model.Chart;
import org.eclipse.birt.chart.model.ChartWithAxes;
import org.eclipse.birt.chart.model.DialChart;
import org.eclipse.birt.chart.model.component.Series;
import org.eclipse.birt.chart.model.data.Query;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.chart.model.type.BubbleSeries;
import org.eclipse.birt.chart.model.type.DifferenceSeries;
import org.eclipse.birt.chart.model.type.GanttSeries;
import org.eclipse.birt.chart.model.type.StockSeries;
import org.eclipse.birt.chart.plugin.ChartEnginePlugin;
import org.eclipse.birt.chart.reportitem.ChartReportItemUtil;
import org.eclipse.birt.chart.reportitem.ui.dialogs.ChartColumnBindingDialog;
import org.eclipse.birt.chart.reportitem.ui.dialogs.ExtendedItemFilterDialog;
import org.eclipse.birt.chart.reportitem.ui.dialogs.ReportItemParametersDialog;
import org.eclipse.birt.chart.reportitem.ui.i18n.Messages;
import org.eclipse.birt.chart.ui.swt.ColorPalette;
import org.eclipse.birt.chart.ui.swt.CustomPreviewTable;
import org.eclipse.birt.chart.ui.swt.DataDefinitionTextManager;
import org.eclipse.birt.chart.ui.swt.DefaultChartDataSheet;
import org.eclipse.birt.chart.ui.swt.SimpleTextTransfer;
import org.eclipse.birt.chart.ui.swt.wizard.ChartAdapter;
import org.eclipse.birt.chart.ui.swt.wizard.ChartWizard;
import org.eclipse.birt.chart.ui.util.ChartHelpContextIds;
import org.eclipse.birt.chart.ui.util.ChartUIUtil;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.ui.frameworks.taskwizard.WizardBase;
import org.eclipse.birt.report.designer.internal.ui.dialogs.ExpressionFilter;
import org.eclipse.birt.report.designer.internal.ui.views.ViewsTreeProvider;
import org.eclipse.birt.report.designer.ui.actions.NewDataSetAction;
import org.eclipse.birt.report.designer.ui.dialogs.ColumnBindingDialog;
import org.eclipse.birt.report.designer.ui.dialogs.ExpressionProvider;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.metadata.IClassInfo;
import org.eclipse.birt.report.model.api.olap.CubeHandle;
import org.eclipse.birt.report.model.api.olap.DimensionHandle;
import org.eclipse.birt.report.model.api.olap.LevelHandle;
import org.eclipse.birt.report.model.api.olap.MeasureHandle;
import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.PlatformUI;
/**
* Data sheet implementation for Standard Chart
*/
public final class StandardChartDataSheet extends DefaultChartDataSheet
implements
Listener
{
final private ExtendedItemHandle itemHandle;
final private ReportDataServiceProvider dataProvider;
/**
* The field indicates if any operation in this class cause some exception
* or error.
*/
private boolean fbException = false;
private Button btnInherit = null;
private Button btnUseData = null;
private Combo cmbDataItems = null;
private Button btnNewData = null;
private StackLayout stackLayout = null;
private Composite cmpStack = null;
private Composite cmpCubeTree = null;
private Composite cmpDataPreview = null;
private CustomPreviewTable tablePreview = null;
private TreeViewer cubeTreeViewer = null;
private Button btnFilters = null;
private Button btnParameters = null;
private Button btnBinding = null;
private static final int SELECT_NONE = 0;
private static final int SELECT_NEXT = 1;
private static final int SELECT_DATA_SET = 2;
private static final int SELECT_DATA_CUBE = 3;
private static final int SELECT_REPORT_ITEM = 4;
private List selectDataTypes = new ArrayList( );
public StandardChartDataSheet( ExtendedItemHandle itemHandle,
ReportDataServiceProvider dataProvider )
{
this.itemHandle = itemHandle;
this.dataProvider = dataProvider;
}
public Composite createActionButtons( Composite parent )
{
Composite composite = ChartUIUtil.createCompositeWrapper( parent );
{
composite.setLayoutData( new GridData( GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_END ) );
}
btnFilters = new Button( composite, SWT.NONE );
{
btnFilters.setAlignment( SWT.CENTER );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
btnFilters.setLayoutData( gridData );
btnFilters.setText( Messages.getString( "StandardChartDataSheet.Label.Filters" ) ); //$NON-NLS-1$
btnFilters.addListener( SWT.Selection, this );
}
btnParameters = new Button( composite, SWT.NONE );
{
btnParameters.setAlignment( SWT.CENTER );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
btnParameters.setLayoutData( gridData );
btnParameters.setText( Messages.getString( "StandardChartDataSheet.Label.Parameters" ) ); //$NON-NLS-1$
btnParameters.addListener( SWT.Selection, this );
}
btnBinding = new Button( composite, SWT.NONE );
{
btnBinding.setAlignment( SWT.CENTER );
GridData gridData = new GridData( GridData.FILL_HORIZONTAL );
btnBinding.setLayoutData( gridData );
btnBinding.setText( Messages.getString( "StandardChartDataSheet.Label.DataBinding" ) ); //$NON-NLS-1$
btnBinding.addListener( SWT.Selection, this );
}
setEnabledForButtons( );
return composite;
}
private void setEnabledForButtons( )
{
btnNewData.setEnabled( btnUseData.getSelection( ) );
if ( isCubeMode( ) )
{
btnFilters.setEnabled( false );
// btnFilters.setEnabled( getDataServiceProvider(
// ).isInvokingSupported( ) );
btnBinding.setEnabled( getDataServiceProvider( ).isInvokingSupported( ) );
btnParameters.setEnabled( false );
}
else
{
btnFilters.setEnabled( hasDataSet( )
&& getDataServiceProvider( ).isInvokingSupported( ) );
// Bugzilla#177704 Chart inheriting data from container doesn't
// support parameters due to limitation in DtE
btnParameters.setEnabled( getDataServiceProvider( ).getBoundDataSet( ) != null
&& getDataServiceProvider( ).isInvokingSupported( ) );
btnBinding.setEnabled( hasDataSet( )
&& getDataServiceProvider( ).isInvokingSupported( ) );
}
}
private boolean hasDataSet( )
{
return getDataServiceProvider( ).getReportDataSet( ) != null
|| getDataServiceProvider( ).getBoundDataSet( ) != null;
}
void fireEvent( Widget widget, int eventType )
{
Event event = new Event( );
event.data = this;
event.widget = widget;
event.type = eventType;
notifyListeners( eventType, event );
}
public Composite createDataDragSource( Composite parent )
{
cmpStack = new Composite( parent, SWT.NONE );
cmpStack.setLayoutData( new GridData( GridData.FILL_BOTH ) );
stackLayout = new StackLayout( );
stackLayout.marginHeight = 0;
stackLayout.marginWidth = 0;
cmpStack.setLayout( stackLayout );
cmpCubeTree = ChartUIUtil.createCompositeWrapper( cmpStack );
cmpDataPreview = ChartUIUtil.createCompositeWrapper( cmpStack );
Label label = new Label( cmpCubeTree, SWT.NONE );
{
label.setText( Messages.getString( "StandardChartDataSheet.Label.CubeTree" ) ); //$NON-NLS-1$
label.setFont( JFaceResources.getBannerFont( ) );
}
Label description = new Label( cmpCubeTree, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
description.setLayoutData( gd );
description.setText( Messages.getString( "StandardChartDataSheet.Label.DragCube" ) ); //$NON-NLS-1$
}
cubeTreeViewer = new TreeViewer( cmpCubeTree, SWT.SINGLE
| SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER );
cubeTreeViewer.getTree( )
.setLayoutData( new GridData( GridData.FILL_BOTH ) );
( (GridData) cubeTreeViewer.getTree( ).getLayoutData( ) ).heightHint = 120;
ViewsTreeProvider provider = new ViewsTreeProvider( );
cubeTreeViewer.setLabelProvider( provider );
cubeTreeViewer.setContentProvider( provider );
cubeTreeViewer.setInput( getCube( ) );
final DragSource dragSource = new DragSource( cubeTreeViewer.getTree( ),
DND.DROP_COPY );
dragSource.setTransfer( new Transfer[]{
SimpleTextTransfer.getInstance( )
} );
dragSource.addDragListener( new DragSourceListener( ) {
private String text = null;
public void dragFinished( DragSourceEvent event )
{
// TODO Auto-generated method stub
}
public void dragSetData( DragSourceEvent event )
{
event.data = text;
}
public void dragStart( DragSourceEvent event )
{
text = createCubeExpression( );
if ( text == null )
{
event.doit = false;
}
}
} );
cubeTreeViewer.getTree( ).addListener( SWT.MouseDown, new Listener( ) {
public void handleEvent( Event event )
{
if ( event.button == 3 && event.widget instanceof Tree )
{
Tree tree = (Tree) event.widget;
TreeItem treeItem = tree.getSelection( )[0];
if ( treeItem.getData( ) instanceof LevelHandle
|| treeItem.getData( ) instanceof MeasureHandle )
{
tree.setMenu( createMenuManager( treeItem.getData( ) ).createContextMenu( tree ) );
tree.getMenu( ).setVisible( true );
}
else
{
tree.setMenu( null );
}
}
}
} );
label = new Label( cmpDataPreview, SWT.NONE );
{
label.setText( Messages.getString( "StandardChartDataSheet.Label.DataPreview" ) ); //$NON-NLS-1$
label.setFont( JFaceResources.getBannerFont( ) );
}
description = new Label( cmpDataPreview, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
description.setLayoutData( gd );
description.setText( Messages.getString( "StandardChartDataSheet.Label.ToBindADataColumn" ) ); //$NON-NLS-1$
}
tablePreview = new CustomPreviewTable( cmpDataPreview, SWT.SINGLE
| SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION );
{
GridData gridData = new GridData( GridData.FILL_BOTH );
gridData.widthHint = 400;
gridData.heightHint = 120;
tablePreview.setLayoutData( gridData );
tablePreview.setHeaderAlignment( SWT.LEFT );
tablePreview.addListener( CustomPreviewTable.MOUSE_RIGHT_CLICK_TYPE,
this );
}
updateDragDataSource( );
return cmpStack;
}
private void updateDragDataSource( )
{
if ( isCubeMode( ) )
{
stackLayout.topControl = cmpCubeTree;
cubeTreeViewer.setInput( getCube( ) );
}
else
{
stackLayout.topControl = cmpDataPreview;
refreshTablePreview( );
}
cmpStack.layout( );
}
public Composite createDataSelector( Composite parent )
{
Composite cmpDataSet = ChartUIUtil.createCompositeWrapper( parent );
{
cmpDataSet.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
}
Label label = new Label( cmpDataSet, SWT.NONE );
{
label.setText( Messages.getString( "StandardChartDataSheet.Label.SelectDataSet" ) ); //$NON-NLS-1$
label.setFont( JFaceResources.getBannerFont( ) );
}
Composite cmpDetail = new Composite( cmpDataSet, SWT.NONE );
{
GridLayout gridLayout = new GridLayout( 3, false );
gridLayout.marginWidth = 10;
gridLayout.marginHeight = 0;
cmpDetail.setLayout( gridLayout );
cmpDetail.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
}
Composite compRadios = ChartUIUtil.createCompositeWrapper( cmpDetail );
{
GridData gd = new GridData( );
gd.verticalSpan = 2;
compRadios.setLayoutData( gd );
}
btnInherit = new Button( compRadios, SWT.RADIO );
btnInherit.setText( Messages.getString( "StandardChartDataSheet.Label.UseReportData" ) ); //$NON-NLS-1$
btnInherit.addListener( SWT.Selection, this );
btnUseData = new Button( compRadios, SWT.RADIO );
btnUseData.setText( Messages.getString( "StandardChartDataSheet.Label.UseDataSet" ) ); //$NON-NLS-1$
btnUseData.addListener( SWT.Selection, this );
new Label( cmpDetail, SWT.NONE );
new Label( cmpDetail, SWT.NONE );
cmbDataItems = new Combo( cmpDetail, SWT.DROP_DOWN | SWT.READ_ONLY );
cmbDataItems.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
cmbDataItems.addListener( SWT.Selection, this );
btnNewData = new Button( cmpDetail, SWT.NONE );
{
btnNewData.setText( Messages.getString( "StandardChartDataSheet.Label.CreateNew" ) ); //$NON-NLS-1$
btnNewData.setToolTipText( Messages.getString( "StandardChartDataSheet.Tooltip.CreateNewDataset" ) ); //$NON-NLS-1$
btnNewData.addListener( SWT.Selection, this );
}
initDataSelector( );
return cmpDataSet;
}
int invokeNewDataSet( )
{
IAction action = new NewDataSetAction( );
PlatformUI.getWorkbench( ).getHelpSystem( ).setHelp( action,
ChartHelpContextIds.DIALOG_NEW_DATA_SET );
action.run( );
// Due to the limitation of the action execution, always return ok
return Window.OK;
}
int invokeEditFilter( )
{
ExtendedItemFilterDialog page = new ExtendedItemFilterDialog( getItemHandle( ) );
return page.open( );
}
int invokeEditParameter( )
{
ReportItemParametersDialog page = new ReportItemParametersDialog( getItemHandle( ) );
return page.open( );
}
int invokeDataBinding( )
{
Shell shell = new Shell( Display.getDefault( ), SWT.DIALOG_TRIM
| SWT.RESIZE | SWT.APPLICATION_MODAL );
// #194163: Do not register CS help in chart since it's registered in
// super column binding dialog.
// ChartUIUtil.bindHelp( shell,
// ChartHelpContextIds.DIALOG_DATA_SET_COLUMN_BINDING );
ColumnBindingDialog page = new ChartColumnBindingDialog( shell );
page.setInput( getItemHandle( ) );
ExpressionProvider ep = new ExpressionProvider( getItemHandle( ) );
ep.addFilter( new ExpressionFilter( ) {
public boolean select( Object parentElement, Object element )
{
// Remove unsupported expression. See bugzilla#132768
return !( parentElement.equals( ExpressionProvider.BIRT_OBJECTS )
&& element instanceof IClassInfo && ( (IClassInfo) element ).getName( )
.equals( "Total" ) ); //$NON-NLS-1$
}
} );
page.setExpressionProvider( ep );
return page.open( );
}
private void initDataSelector( )
{
// create Combo items
cmbDataItems.setItems( createDataComboItems( ) );
// Select report item reference
// Since handle may have data set or data cube besides reference, always
// check reference first
String sItemRef = getDataServiceProvider( ).getReportItemReference( );
if ( sItemRef != null )
{
btnUseData.setSelection( true );
cmbDataItems.setText( sItemRef );
return;
}
// Select data set
String sDataSet = getDataServiceProvider( ).getBoundDataSet( );
if ( sDataSet != null )
{
btnUseData.setSelection( true );
cmbDataItems.setText( sDataSet );
if ( sDataSet != null )
{
switchDataTable( );
}
return;
}
// Select data cube
String sDataCube = getDataServiceProvider( ).getDataCube( );
if ( sDataCube != null )
{
btnUseData.setSelection( true );
cmbDataItems.setText( sDataCube );
return;
}
btnInherit.setSelection( true );
cmbDataItems.select( 0 );
cmbDataItems.setEnabled( false );
// Initializes column bindings from container
getDataServiceProvider( ).setDataSet( null );
String reportDataSet = getDataServiceProvider( ).getReportDataSet( );
if ( reportDataSet != null )
{
switchDataTable( );
}
// select reference item
// selectItemRef( );
// if ( cmbReferences.getSelectionIndex( ) > 0 )
// {
// cmbDataSet.setEnabled( false );
// btnUseReference.setSelection( true );
// btnUseReportData.setSelection( false );
// btnUseDataSet.setSelection( false );
// }
// else
// {
// cmbReferences.setEnabled( false );
// }
//
// String dataCube = getDataServiceProvider( ).getDataCube( );
// if ( dataCube != null )
// {
// cmbCubes.setText( dataCube );
// btnUseReference.setSelection( false );
// btnUseReportData.setSelection( false );
// btnUseDataSet.setSelection( false );
// btnUseCubes.setSelection( true );
// }
// else
// {
// cmbCubes.select( 0 );
// }
}
public void handleEvent( Event event )
{
fbException = false;
// Right click to display the menu. Menu display by clicking
// application key is triggered by os, so do nothing.
if ( event.type == CustomPreviewTable.MOUSE_RIGHT_CLICK_TYPE )
{
if ( getDataServiceProvider( ).getBoundDataSet( ) != null
|| getDataServiceProvider( ).getReportDataSet( ) != null )
{
if ( event.widget instanceof Button )
{
Button header = (Button) event.widget;
// Bind context menu to each header button
if ( header.getMenu( ) == null )
{
header.setMenu( createMenuManager( event.data ).createContextMenu( tablePreview ) );
}
header.getMenu( ).setVisible( true );
}
}
}
else if ( event.type == SWT.Selection )
{
if ( event.widget instanceof MenuItem )
{
MenuItem item = (MenuItem) event.widget;
IAction action = (IAction) item.getData( );
action.setChecked( !action.isChecked( ) );
action.run( );
}
else if ( event.widget == btnFilters )
{
if ( invokeEditFilter( ) == Window.OK )
{
refreshTablePreview( );
// Update preview via event
fireEvent( btnFilters, EVENT_UPDATE );
}
}
else if ( event.widget == btnParameters )
{
if ( invokeEditParameter( ) == Window.OK )
{
refreshTablePreview( );
// Update preview via event
fireEvent( btnParameters, EVENT_UPDATE );
}
}
else if ( event.widget == btnBinding )
{
if ( invokeDataBinding( ) == Window.OK )
{
refreshTablePreview( );
// Update preview via event
fireEvent( btnBinding, EVENT_UPDATE );
}
}
try
{
if ( event.widget == btnInherit )
{
ColorPalette.getInstance( ).restore( );
// Skip when selection is false
if ( !btnInherit.getSelection( ) )
{
return;
}
getDataServiceProvider( ).setReportItemReference( null );
getDataServiceProvider( ).setDataSet( null );
switchDataSet( null );
cmbDataItems.select( 0 );
cmbDataItems.setEnabled( false );
setEnabledForButtons( );
updateDragDataSource( );
}
else if ( event.widget == btnUseData )
{
// Skip when selection is false
if ( !btnUseData.getSelection( ) )
{
return;
}
getDataServiceProvider( ).setReportItemReference( null );
selectDataSet( );
cmbDataItems.setEnabled( true );
setEnabledForButtons( );
updateDragDataSource( );
}
else if ( event.widget == cmbDataItems )
{
ColorPalette.getInstance( ).restore( );
int selectedIndex = cmbDataItems.getSelectionIndex( );
Integer selectState = (Integer) selectDataTypes.get( selectedIndex );
switch ( selectState.intValue( ) )
{
case SELECT_NONE :
// Inherit data from container
btnInherit.setSelection( true );
btnUseData.setSelection( false );
btnInherit.notifyListeners( SWT.Selection,
new Event( ) );
break;
case SELECT_NEXT :
selectedIndex++;
selectState = (Integer) selectDataTypes.get( selectedIndex );
cmbDataItems.select( selectedIndex );
break;
}
switch ( selectState.intValue( ) )
{
case SELECT_DATA_SET :
if ( getDataServiceProvider( ).getBoundDataSet( ) != null
&& getDataServiceProvider( ).getBoundDataSet( )
.equals( cmbDataItems.getText( ) ) )
{
return;
}
getDataServiceProvider( ).setDataSet( cmbDataItems.getText( ) );
switchDataSet( cmbDataItems.getText( ) );
setEnabledForButtons( );
updateDragDataSource( );
break;
case SELECT_DATA_CUBE :
getDataServiceProvider( ).setDataCube( cmbDataItems.getText( ) );
updateDragDataSource( );
setEnabledForButtons( );
break;
case SELECT_REPORT_ITEM :
if ( cmbDataItems.getText( )
.equals( getDataServiceProvider( ).getReportItemReference( ) ) )
{
return;
}
getDataServiceProvider( ).setReportItemReference( cmbDataItems.getText( ) );
// selectDataSet( );
// switchDataSet( cmbDataItems.getText( ) );
setEnabledForButtons( );
updateDragDataSource( );
break;
}
}
// else if ( event.widget == btnUseReference )
// {
// // Skip when selection is false
// if ( !btnUseReference.getSelection( ) )
// {
// return;
// }
// cmbDataSet.setEnabled( false );
// cmbReferences.setEnabled( true );
// selectItemRef( );
// setEnabledForButtons( );
// }
// else if ( event.widget == cmbReferences )
// {
// if ( cmbReferences.getSelectionIndex( ) == 0 )
// {
// if ( getDataServiceProvider( ).getReportItemReference( ) ==
// null )
// {
// return;
// }
// getDataServiceProvider( ).setReportItemReference( null );
//
// // Auto select the data set
// selectDataSet( );
// cmbReferences.setEnabled( false );
// cmbDataSet.setEnabled( true );
// btnUseReference.setSelection( false );
// btnUseDataSet.setSelection( true );
// }
// else
// {
// if ( cmbReferences.getText( )
// .equals( getDataServiceProvider( ).getReportItemReference( )
// ) )
// {
// return;
// }
// getDataServiceProvider( ).setReportItemReference(
// cmbReferences.getText( ) );
// selectDataSet( );
// }
// switchDataSet( cmbDataSet.getText( ) );
// setEnabledForButtons( );
// }
else if ( event.widget == btnNewData )
{
// Bring up the dialog to create a dataset
int result = invokeNewDataSet( );
if ( result == Window.CANCEL )
{
return;
}
String currentDataSet = cmbDataItems.getText( );
cmbDataItems.removeAll( );
cmbDataItems.setItems( createDataComboItems( ) );
cmbDataItems.setText( currentDataSet );
}
}
catch ( ChartException e1 )
{
fbException = true;
ChartWizard.showException( e1.getLocalizedMessage( ) );
}
}
if ( !fbException )
{
WizardBase.removeException( );
}
}
private void selectDataSet( )
{
String currentDS = getDataServiceProvider( ).getBoundDataSet( );
if ( currentDS == null )
{
cmbDataItems.select( 0 );
}
else
{
cmbDataItems.setText( currentDS );
}
}
private void refreshTablePreview( )
{
if ( dataProvider.getDataSetFromHandle( ) == null )
{
return;
}
tablePreview.clearContents( );
switchDataTable( );
tablePreview.layout( );
}
private void switchDataSet( String datasetName ) throws ChartException
{
if ( isCubeMode( ) )
{
return;
}
try
{
// Clear old dataset and preview data
tablePreview.clearContents( );
// Try to get report data set
if ( datasetName == null )
{
datasetName = getDataServiceProvider( ).getReportDataSet( );
}
if ( datasetName != null )
{
switchDataTable( );
}
else
{
tablePreview.createDummyTable( );
}
tablePreview.layout( );
}
catch ( Throwable t )
{
throw new ChartException( ChartEnginePlugin.ID,
ChartException.DATA_BINDING,
t );
}
DataDefinitionTextManager.getInstance( ).refreshAll( );
// Update preview via event
fireEvent( tablePreview, EVENT_UPDATE );
}
private void switchDataTable( )
{
if ( isCubeMode( ) )
{
return;
}
// 1. Create a runnable.
Runnable runnable = new Runnable( ) {
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
*/
public void run( )
{
try
{
// Get header and data in other thread.
final String[] header = getDataServiceProvider( ).getPreviewHeader( );
final List dataList = getDataServiceProvider( ).getPreviewData( );
// Execute UI operation in UI thread.
Display.getDefault( ).syncExec( new Runnable( ) {
public void run( )
{
if ( tablePreview.isDisposed( ) )
{
return;
}
if ( header == null )
{
tablePreview.setEnabled( false );
tablePreview.createDummyTable( );
}
else
{
tablePreview.setEnabled( true );
tablePreview.setColumns( header );
refreshTableColor( );
// Add data value
for ( Iterator iterator = dataList.iterator( ); iterator.hasNext( ); )
{
String[] dataRow = (String[]) iterator.next( );
for ( int i = 0; i < dataRow.length; i++ )
{
tablePreview.addEntry( dataRow[i], i );
}
}
}
tablePreview.layout( );
}
} );
}
catch ( Exception e )
{
// Catch any exception.
final String msg = e.getMessage( );
Display.getDefault( ).syncExec( new Runnable( ) {
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
public void run( )
{
fbException = true;
WizardBase.showException( msg );
}
} );
}
}
};
// 2. Run it.
new Thread( runnable ).start( );
}
private void refreshTableColor( )
{
if ( isCubeMode( ) )
{
return;
}
// Reset column color
for ( int i = 0; i < tablePreview.getColumnNumber( ); i++ )
{
tablePreview.setColumnColor( i,
ColorPalette.getInstance( )
.getColor( ExpressionUtil.createJSRowExpression( tablePreview.getColumnHeading( i ) ) ) );
}
}
private void manageColorAndQuery( Query query, String expr )
{
// If it's not used any more, remove color binding
if ( DataDefinitionTextManager.getInstance( )
.getNumberOfSameDataDefinition( query.getDefinition( ) ) == 0 )
{
ColorPalette.getInstance( ).retrieveColor( query.getDefinition( ) );
}
query.setDefinition( expr );
DataDefinitionTextManager.getInstance( ).updateText( query );
// Reset table column color
refreshTableColor( );
// Refresh all data definition text
DataDefinitionTextManager.getInstance( ).refreshAll( );
}
class CategoryXAxisAction extends Action
{
String expr;
CategoryXAxisAction( String expr )
{
super( getBaseSeriesTitle( getChartModel( ) ) );
this.expr = expr;
}
public void run( )
{
Query query = ( (Query) ( (SeriesDefinition) ChartUIUtil.getBaseSeriesDefinitions( getChartModel( ) )
.get( 0 ) ).getDesignTimeSeries( )
.getDataDefinition( )
.get( 0 ) );
manageColorAndQuery( query, expr );
}
}
class GroupYSeriesAction extends Action
{
Query query;
String expr;
GroupYSeriesAction( Query query, String expr )
{
super( getGroupSeriesTitle( getChartModel( ) ) );
this.query = query;
this.expr = expr;
}
public void run( )
{
// Use the first group, and copy to the all groups
ChartAdapter.beginIgnoreNotifications( );
ChartUIUtil.setAllGroupingQueryExceptFirst( getChartModel( ), expr );
ChartAdapter.endIgnoreNotifications( );
manageColorAndQuery( query, expr );
}
}
class ValueYSeriesAction extends Action
{
Query query;
String expr;
ValueYSeriesAction( Query query, String expr )
{
super( getOrthogonalSeriesTitle( getChartModel( ) ) );
this.query = query;
this.expr = expr;
}
public void run( )
{
manageColorAndQuery( query, expr );
}
}
class HeaderShowAction extends Action
{
HeaderShowAction( String header )
{
super( header );
setEnabled( false );
}
}
ExtendedItemHandle getItemHandle( )
{
return this.itemHandle;
}
ReportDataServiceProvider getDataServiceProvider( )
{
return this.dataProvider;
}
private MenuManager createMenuManager( final Object data )
{
MenuManager menuManager = new MenuManager( );
menuManager.setRemoveAllWhenShown( true );
menuManager.addMenuListener( new IMenuListener( ) {
public void menuAboutToShow( IMenuManager manager )
{
if ( data instanceof Integer )
{
// Menu for table
addMenu( manager,
new HeaderShowAction( tablePreview.getCurrentColumnHeading( ) ) );
String expr = ExpressionUtil.createJSRowExpression( tablePreview.getCurrentColumnHeading( ) );
addMenu( manager,
getBaseSeriesMenu( getChartModel( ), expr ) );
addMenu( manager,
getOrthogonalSeriesMenu( getChartModel( ), expr ) );
addMenu( manager, getGroupSeriesMenu( getChartModel( ),
expr ) );
}
else if ( data instanceof MeasureHandle )
{
// Menu for Measure
String expr = createCubeExpression( );
addMenu( manager,
getOrthogonalSeriesMenu( getChartModel( ), expr ) );
}
else if ( data instanceof LevelHandle )
{
// Menu for Level
String expr = createCubeExpression( );
addMenu( manager,
getBaseSeriesMenu( getChartModel( ), expr ) );
addMenu( manager, getGroupSeriesMenu( getChartModel( ),
expr ) );
}
}
private void addMenu( IMenuManager manager, Object item )
{
if ( item instanceof IAction )
{
manager.add( (IAction) item );
}
else if ( item instanceof IContributionItem )
{
manager.add( (IContributionItem) item );
}
}
} );
return menuManager;
}
private Object getBaseSeriesMenu( Chart chart, String expr )
{
EList sds = ChartUIUtil.getBaseSeriesDefinitions( chart );
if ( sds.size( ) == 1 )
{
return new CategoryXAxisAction( expr );
}
return null;
}
private Object getGroupSeriesMenu( Chart chart, String expr )
{
IMenuManager topManager = new MenuManager( getGroupSeriesTitle( getChartModel( ) ) );
int axisNum = ChartUIUtil.getOrthogonalAxisNumber( chart );
for ( int axisIndex = 0; axisIndex < axisNum; axisIndex++ )
{
List sds = ChartUIUtil.getOrthogonalSeriesDefinitions( chart,
axisIndex );
for ( int i = 0; i < sds.size( ); i++ )
{
SeriesDefinition sd = (SeriesDefinition) sds.get( i );
IAction action = new GroupYSeriesAction( sd.getQuery( ), expr );
// ONLY USE FIRST GROUPING SERIES FOR CHART ENGINE SUPPORT
// if ( axisNum == 1 && sds.size( ) == 1 )
{
// Simply cascade menu
return action;
}
// action.setText( getSecondMenuText( axisIndex,
// i,
// sd.getDesignTimeSeries( ) ) );
// topManager.add( action );
}
}
return topManager;
}
private Object getOrthogonalSeriesMenu( Chart chart, String expr )
{
IMenuManager topManager = new MenuManager( getOrthogonalSeriesTitle( getChartModel( ) ) );
int axisNum = ChartUIUtil.getOrthogonalAxisNumber( chart );
for ( int axisIndex = 0; axisIndex < axisNum; axisIndex++ )
{
List sds = ChartUIUtil.getOrthogonalSeriesDefinitions( chart,
axisIndex );
for ( int i = 0; i < sds.size( ); i++ )
{
Series series = ( (SeriesDefinition) sds.get( i ) ).getDesignTimeSeries( );
EList dataDefns = series.getDataDefinition( );
if ( series instanceof StockSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( (Query) dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getStockTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else if ( series instanceof BubbleSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( (Query) dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getBubbleTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else if ( series instanceof DifferenceSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( (Query) dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getDifferenceTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else if ( series instanceof GanttSeries )
{
IMenuManager secondManager = new MenuManager( getSecondMenuText( axisIndex,
i,
series ) );
topManager.add( secondManager );
for ( int j = 0; j < dataDefns.size( ); j++ )
{
IAction action = new ValueYSeriesAction( (Query) dataDefns.get( j ),
expr );
action.setText( ChartUIUtil.getGanttTitle( j )
+ Messages.getString( "StandardChartDataSheet.Label.Component" ) ); //$NON-NLS-1$
secondManager.add( action );
}
}
else
{
IAction action = new ValueYSeriesAction( (Query) dataDefns.get( 0 ),
expr );
if ( axisNum == 1 && sds.size( ) == 1 )
{
// Simplify cascade menu
return action;
}
action.setText( getSecondMenuText( axisIndex, i, series ) );
topManager.add( action );
}
}
}
return topManager;
}
private String getSecondMenuText( int axisIndex, int seriesIndex,
Series series )
{
StringBuffer sb = new StringBuffer( );
if ( ChartUIUtil.getOrthogonalAxisNumber( getChartModel( ) ) > 2 )
{
sb.append( Messages.getString( "DataDefinitionSelector.Label.Axis" ) ); //$NON-NLS-1$
sb.append( axisIndex + 1 );
sb.append( " - " ); //$NON-NLS-1$
}
else
{
if ( axisIndex > 0 )
{
sb.append( Messages.getString( "StandardChartDataSheet.Label.Overlay" ) ); //$NON-NLS-1$
}
}
sb.append( Messages.getString( "StandardChartDataSheet.Label.Series" ) //$NON-NLS-1$
+ ( seriesIndex + 1 ) + " (" + series.getDisplayName( ) + ")" ); //$NON-NLS-1$ //$NON-NLS-2$
return sb.toString( );
}
private String getBaseSeriesTitle( Chart chart )
{
if ( chart instanceof ChartWithAxes )
{
return Messages.getString( "StandardChartDataSheet.Label.UseAsCategoryXAxis" ); //$NON-NLS-1$
}
return Messages.getString( "StandardChartDataSheet.Label.UseAsCategorySeries" ); //$NON-NLS-1$
}
private String getOrthogonalSeriesTitle( Chart chart )
{
if ( chart instanceof ChartWithAxes )
{
return Messages.getString( "StandardChartDataSheet.Label.PlotAsValueYSeries" ); //$NON-NLS-1$
}
else if ( chart instanceof DialChart )
{
return Messages.getString( "StandardChartDataSheet.Label.PlotAsGaugeValue" ); //$NON-NLS-1$
}
return Messages.getString( "StandardChartDataSheet.Label.PlotAsValueSeries" ); //$NON-NLS-1$
}
private String getGroupSeriesTitle( Chart chart )
{
if ( chart instanceof ChartWithAxes )
{
return Messages.getString( "StandardChartDataSheet.Label.UseToGroupYSeries" ); //$NON-NLS-1$
}
return Messages.getString( "StandardChartDataSheet.Label.UseToGroupValueSeries" ); //$NON-NLS-1$
}
private boolean isCubeMode( )
{
return ChartReportItemUtil.getBindingCube( itemHandle ) != null;
}
private CubeHandle getCube( )
{
return ChartReportItemUtil.getBindingCube( itemHandle );
}
/**
* Creates the cube expression
*
* @return expression
*/
private String createCubeExpression( )
{
if ( cubeTreeViewer == null )
{
return null;
}
TreeItem[] selection = cubeTreeViewer.getTree( ).getSelection( );
String expr = null;
if ( selection.length > 0 )
{
TreeItem treeItem = selection[0];
if ( treeItem.getData( ) instanceof LevelHandle )
{
TreeItem dimensionItem = treeItem.getParentItem( );
while ( !( dimensionItem.getData( ) instanceof DimensionHandle ) )
{
dimensionItem = dimensionItem.getParentItem( );
}
expr = ExpressionUtil.createJSDimensionExpression( dimensionItem.getText( ),
treeItem.getText( ) );
}
else if ( treeItem.getData( ) instanceof MeasureHandle )
{
expr = ExpressionUtil.createJSMeasureExpression( treeItem.getText( ) );
}
}
return expr;
}
private String[] createDataComboItems( )
{
List items = new ArrayList( );
selectDataTypes.clear( );
items.add( ReportDataServiceProvider.OPTION_NONE );
selectDataTypes.add( new Integer( SELECT_NONE ) );
String[] dataSets = getDataServiceProvider( ).getAllDataSets( );
if ( dataSets.length > 0 )
{
items.add( Messages.getString( "StandardChartDataSheet.Combo.DataSets" ) ); //$NON-NLS-1$
selectDataTypes.add( new Integer( SELECT_NEXT ) );
for ( int i = 0; i < dataSets.length; i++ )
{
items.add( dataSets[i] );
selectDataTypes.add( new Integer( SELECT_DATA_SET ) );
}
}
String[] dataCubes = getDataServiceProvider( ).getAllDataCubes( );
if ( dataCubes.length > 0 )
{
items.add( Messages.getString( "StandardChartDataSheet.Combo.DataCubes" ) ); //$NON-NLS-1$
selectDataTypes.add( new Integer( SELECT_NEXT ) );
for ( int i = 0; i < dataCubes.length; i++ )
{
items.add( dataCubes[i] );
selectDataTypes.add( new Integer( SELECT_DATA_CUBE ) );
}
}
String[] dataRefs = getDataServiceProvider( ).getAllReportItemReferences( );
if ( dataRefs.length > 0 )
{
items.add( Messages.getString( "StandardChartDataSheet.Combo.ReportItems" ) ); //$NON-NLS-1$
selectDataTypes.add( new Integer( SELECT_NEXT ) );
for ( int i = 0; i < dataRefs.length; i++ )
{
items.add( dataRefs[i] );
selectDataTypes.add( new Integer( SELECT_REPORT_ITEM ) );
}
}
return (String[]) items.toArray( new String[items.size( )] );
}
}
| Solution: Start a transaction when opening a Select Data Binding or Filters dialog, so the operations can be canceled.
| chart/org.eclipse.birt.chart.reportitem.ui/src/org/eclipse/birt/chart/reportitem/ui/StandardChartDataSheet.java | Solution: Start a transaction when opening a Select Data Binding or Filters dialog, so the operations can be canceled. | <ide><path>hart/org.eclipse.birt.chart.reportitem.ui/src/org/eclipse/birt/chart/reportitem/ui/StandardChartDataSheet.java
<ide>
<ide> int invokeEditFilter( )
<ide> {
<del> ExtendedItemFilterDialog page = new ExtendedItemFilterDialog( getItemHandle( ) );
<del> return page.open( );
<add> ExtendedItemHandle handle = getItemHandle( );
<add> handle.getModuleHandle( ).getCommandStack( ).startTrans( null );
<add> ExtendedItemFilterDialog page = new ExtendedItemFilterDialog( handle );
<add> int openStatus = page.open( );
<add> if ( openStatus == Window.OK )
<add> {
<add> handle.getModuleHandle( ).getCommandStack( ).commit( );
<add> }
<add> else
<add> {
<add> handle.getModuleHandle( ).getCommandStack( ).rollback( );
<add> }
<add>
<add> return openStatus;
<ide> }
<ide>
<ide> int invokeEditParameter( )
<ide> // ChartUIUtil.bindHelp( shell,
<ide> // ChartHelpContextIds.DIALOG_DATA_SET_COLUMN_BINDING );
<ide> ColumnBindingDialog page = new ChartColumnBindingDialog( shell );
<del> page.setInput( getItemHandle( ) );
<del>
<add>
<add> ExtendedItemHandle handle = getItemHandle();
<add> handle.getModuleHandle( ).getCommandStack( ).startTrans( null );
<add> page.setInput( handle );
<add>
<ide> ExpressionProvider ep = new ExpressionProvider( getItemHandle( ) );
<ide> ep.addFilter( new ExpressionFilter( ) {
<ide>
<ide> public boolean select( Object parentElement, Object element )
<ide> {
<ide> // Remove unsupported expression. See bugzilla#132768
<del> return !( parentElement.equals( ExpressionProvider.BIRT_OBJECTS )
<del> && element instanceof IClassInfo && ( (IClassInfo) element ).getName( )
<add> return !( parentElement.equals( ExpressionProvider.BIRT_OBJECTS ) &&
<add> element instanceof IClassInfo && ( (IClassInfo) element ).getName( )
<ide> .equals( "Total" ) ); //$NON-NLS-1$
<ide> }
<ide> } );
<ide> page.setExpressionProvider( ep );
<del> return page.open( );
<add>
<add> int openStatus = page.open( );
<add> if ( openStatus == Window.OK )
<add> {
<add> handle.getModuleHandle( ).getCommandStack( ).commit( );
<add> }
<add> else
<add> {
<add> handle.getModuleHandle( ).getCommandStack( ).rollback( );
<add> }
<add>
<add> return openStatus;
<ide> }
<ide>
<ide> private void initDataSelector( ) |
|
Java | apache-2.0 | f4df39cc5b8c69e436fb4e134e4864df2141986a | 0 | moko256/twicalico,moko256/twicalico | /*
* Copyright 2017 The twicalico 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.github.moko256.twicalico;
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;
import com.github.moko256.twicalico.database.CachedIdListSQLiteOpenHelper;
import com.github.moko256.twicalico.text.TwitterStringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import rx.Observable;
import rx.Single;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.TwitterException;
/**
* Created by moko256 on 2016/03/27.
*
* @author moko256
*/
public abstract class BaseTweetListFragment extends BaseListFragment {
StatusesAdapter adapter;
ArrayList<Long> list;
CompositeSubscription subscription;
CachedIdListSQLiteOpenHelper statusIdsDatabase;
int LAST_SAVED_LIST_POSITION;
@Override
public void onCreate(Bundle savedInstanceState) {
list=new ArrayList<>();
subscription = new CompositeSubscription();
statusIdsDatabase = new CachedIdListSQLiteOpenHelper(getContext(), GlobalApplication.userId, getCachedIdsDatabaseName());
if (savedInstanceState == null){
ArrayList<Long> c = statusIdsDatabase.getIds();
if (c.size() > 0) {
list.addAll(c);
setProgressCircleLoading(false);
}
}
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=super.onCreateView(inflater, container, savedInstanceState);
getRecyclerView().addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
int span = ((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex();
float dens = getResources().getDisplayMetrics().density;
outRect.left = Math.round(dens * (span == 0 ? 8f : 4f));
outRect.right = Math.round(dens * (span == ((StaggeredGridLayoutManager) parent.getLayoutManager()).getSpanCount() - 1 ? 8f : 4f));
outRect.top = Math.round(dens * 8f);
}
});
adapter=new StatusesAdapter(getContext(), list);
adapter.setOnLoadMoreClick(position -> subscription.add(
getResponseSingle(
new Paging()
.maxId(list.get(position-1)-1L)
.sinceId(list.get(list.size() >= position + 2? position + 2: position + 1))
.count(GlobalApplication.statusLimit))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
result -> {
if (result.size() > 0) {
list.remove(position);
statusIdsDatabase.deleteIds(new long[]{-1L});
adapter.notifyItemRemoved(position);
List<Long>ids = Observable
.from(result)
.map(Status::getId)
.toList().toSingle().toBlocking().value();
if (ids.get(ids.size() - 1).equals(list.get(position))) {
ids.remove(ids.size() - 1);
} else {
ids.add(-1L);
}
list.addAll(position, ids);
statusIdsDatabase.insertIds(position, ids);
adapter.notifyItemRangeInserted(position, ids.size());
} else {
list.remove(position);
statusIdsDatabase.deleteIds(new long[]{-1L});
adapter.notifyItemRemoved(position);
}
},
e -> {
e.printStackTrace();
Snackbar.make(getSnackBarParentContainer(), TwitterStringUtils.convertErrorToText(e), Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.retry, v -> onLoadMoreList())
.show();
}
)
));
setAdapter(adapter);
if (!isInitializedList()){
adapter.notifyDataSetChanged();
}
LAST_SAVED_LIST_POSITION = statusIdsDatabase.getListViewPosition();
getRecyclerView().getLayoutManager().scrollToPosition(LAST_SAVED_LIST_POSITION);
return view;
}
@Override
public void onStart() {
super.onStart();
LAST_SAVED_LIST_POSITION = statusIdsDatabase.getListViewPosition();
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null){
ArrayList l=(ArrayList) savedInstanceState.getSerializable("list");
if(l!=null){
Long longs[] = new Long[l.size()];
for (int i = 0; i < longs.length; i++) {
longs[i] = (Long)l.get(i);
}
list.addAll(Arrays.asList(longs));
}
}
}
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putSerializable("list", list);
}
@Override
public void onDestroyView() {
StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) getRecyclerView().getLayoutManager();
int[] positions = layoutManager.findFirstVisibleItemPositions(null);
ArrayList<Long> ids = statusIdsDatabase.getIds();
if (ids.size() - positions[0] > 1000){
List<Long> list = ids.subList(positions[0] + 1000, ids.size());
statusIdsDatabase.deleteIds(list);
boolean[] results = statusIdsDatabase.hasIdsOtherTable(list);
List<Long> deletableIds = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
if (!results[i]) {
deletableIds.add(list.get(i));
}
}
GlobalApplication.statusCache.delete(deletableIds);
}
super.onDestroyView();
subscription.unsubscribe();
adapter=null;
}
@Override
public void onStop() {
super.onStop();
StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) getRecyclerView().getLayoutManager();
int[] positions = layoutManager.findFirstVisibleItemPositions(null);
if (positions[0]!= LAST_SAVED_LIST_POSITION){
statusIdsDatabase.setListViewPosition(positions[0]);
}
}
@Override
public void onDestroy() {
super.onDestroy();
statusIdsDatabase.close();
statusIdsDatabase = null;
subscription = null;
list=null;
}
@Override
protected void onInitializeList() {
subscription.add(
getResponseSingle(new Paging(1,20))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
result-> {
List<Long> ids = Observable
.from(result)
.map(Status::getId)
.toList().toSingle().toBlocking().value();
list.addAll(ids);
statusIdsDatabase.addIds(ids);
adapter.notifyDataSetChanged();
getSwipeRefreshLayout().setRefreshing(false);
setProgressCircleLoading(false);
},
e -> {
e.printStackTrace();
Snackbar.make(getSnackBarParentContainer(), TwitterStringUtils.convertErrorToText(e), Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.retry, v -> onInitializeList())
.show();
}
)
);
}
@Override
protected void onUpdateList() {
subscription.add(
getResponseSingle(new Paging(list.get(list.size() >= 2? 1: 0)).count(GlobalApplication.statusLimit))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
result -> {
if (result.size() > 0) {
List<Long> ids = Observable
.from(result)
.map(Status::getId)
.toList().toSingle().toBlocking().value();
if (ids.get(ids.size() - 1).equals(list.get(0))) {
ids.remove(ids.size() - 1);
} else {
ids.add(-1L);
}
if (ids.size() > 0){
list.addAll(0, ids);
statusIdsDatabase.insertIds(0, ids);
adapter.notifyItemRangeInserted(0, ids.size());
TypedValue value=new TypedValue();
Toast t=Toast.makeText(getContext(),R.string.new_tweet,Toast.LENGTH_SHORT);
t.setGravity(
Gravity.TOP|Gravity.CENTER,
0,
getContext().getTheme().resolveAttribute(R.attr.actionBarSize, value, true)?
TypedValue.complexToDimensionPixelOffset(value.data, getResources().getDisplayMetrics()):
0
);
t.show();
}
}
getSwipeRefreshLayout().setRefreshing(false);
},
e -> {
e.printStackTrace();
getSwipeRefreshLayout().setRefreshing(false);
Snackbar.make(getSnackBarParentContainer(), TwitterStringUtils.convertErrorToText(e), Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.retry, v -> onUpdateList())
.show();
}
)
);
}
@Override
protected void onLoadMoreList() {
subscription.add(
getResponseSingle(new Paging().maxId(list.get(list.size()-1)-1L).count(GlobalApplication.statusLimit))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
result -> {
int size = result.size();
if (size > 0) {
List<Long> ids = Observable
.from(result)
.map(Status::getId)
.toList().toSingle().toBlocking().value();
list.addAll(ids);
statusIdsDatabase.insertIds(list.size() - size, ids);
adapter.notifyItemRangeInserted(list.size() - size, size);
}
},
e -> {
e.printStackTrace();
Snackbar.make(getSnackBarParentContainer(), TwitterStringUtils.convertErrorToText(e), Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.retry, v -> onLoadMoreList())
.show();
}
)
);
}
@Override
protected boolean isInitializedList() {
return !list.isEmpty();
}
@Override
protected RecyclerView.LayoutManager initializeRecyclerViewLayoutManager() {
WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return new StaggeredGridLayoutManager(
(int) Math.ceil(
(double)
//Calculated as:
//Picture area: (16 : 9) + Other content: (16 : 3)
(size.x * 12) / (size.y * 16)
),
StaggeredGridLayoutManager.VERTICAL
);
}
protected abstract String getCachedIdsDatabaseName();
public Single<ResponseList<Status>> getResponseSingle(Paging paging) {
return Single.create(
subscriber->{
try {
ResponseList<Status> statuses = getResponseList(paging);
if (statuses.size() > 0){
GlobalApplication.statusCache.addAll(statuses);
}
subscriber.onSuccess(statuses);
} catch (TwitterException e) {
subscriber.onError(e);
}
}
);
}
public abstract ResponseList<Status> getResponseList(Paging paging) throws TwitterException;
} | app/src/main/java/com/github/moko256/twicalico/BaseTweetListFragment.java | /*
* Copyright 2017 The twicalico 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.github.moko256.twicalico;
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;
import com.github.moko256.twicalico.database.CachedIdListSQLiteOpenHelper;
import com.github.moko256.twicalico.text.TwitterStringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import rx.Observable;
import rx.Single;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.TwitterException;
/**
* Created by moko256 on 2016/03/27.
*
* @author moko256
*/
public abstract class BaseTweetListFragment extends BaseListFragment {
StatusesAdapter adapter;
ArrayList<Long> list;
CompositeSubscription subscription;
CachedIdListSQLiteOpenHelper statusIdsDatabase;
int LAST_SAVED_LIST_POSITION;
@Override
public void onCreate(Bundle savedInstanceState) {
list=new ArrayList<>();
subscription = new CompositeSubscription();
statusIdsDatabase = new CachedIdListSQLiteOpenHelper(getContext(), GlobalApplication.userId, getCachedIdsDatabaseName());
if (savedInstanceState == null){
ArrayList<Long> c = statusIdsDatabase.getIds();
if (c.size() > 0) {
list.addAll(c);
setProgressCircleLoading(false);
}
}
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=super.onCreateView(inflater, container, savedInstanceState);
getRecyclerView().addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
int span = ((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex();
float dens = getContext().getResources().getDisplayMetrics().density;
outRect.left = Math.round(dens * (span == 0 ? 8f : 4f));
outRect.right = Math.round(dens * (span == ((StaggeredGridLayoutManager) parent.getLayoutManager()).getSpanCount() - 1 ? 8f : 4f));
outRect.top = Math.round(dens * 8f);
}
});
adapter=new StatusesAdapter(getContext(), list);
adapter.setOnLoadMoreClick(position -> subscription.add(
getResponseSingle(
new Paging()
.maxId(list.get(position-1)-1L)
.sinceId(list.get(list.size() >= position + 2? position + 2: position + 1))
.count(GlobalApplication.statusLimit))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
result -> {
if (result.size() > 0) {
list.remove(position);
statusIdsDatabase.deleteIds(new long[]{-1L});
adapter.notifyItemRemoved(position);
List<Long>ids = Observable
.from(result)
.map(Status::getId)
.toList().toSingle().toBlocking().value();
if (ids.get(ids.size() - 1).equals(list.get(position))) {
ids.remove(ids.size() - 1);
} else {
ids.add(-1L);
}
list.addAll(position, ids);
statusIdsDatabase.insertIds(position, ids);
adapter.notifyItemRangeInserted(position, ids.size());
} else {
list.remove(position);
statusIdsDatabase.deleteIds(new long[]{-1L});
adapter.notifyItemRemoved(position);
}
},
e -> {
e.printStackTrace();
Snackbar.make(getSnackBarParentContainer(), TwitterStringUtils.convertErrorToText(e), Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.retry, v -> onLoadMoreList())
.show();
}
)
));
setAdapter(adapter);
if (!isInitializedList()){
adapter.notifyDataSetChanged();
}
LAST_SAVED_LIST_POSITION = statusIdsDatabase.getListViewPosition();
getRecyclerView().getLayoutManager().scrollToPosition(LAST_SAVED_LIST_POSITION);
return view;
}
@Override
public void onStart() {
super.onStart();
LAST_SAVED_LIST_POSITION = statusIdsDatabase.getListViewPosition();
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null){
ArrayList l=(ArrayList) savedInstanceState.getSerializable("list");
if(l!=null){
Long longs[] = new Long[l.size()];
for (int i = 0; i < longs.length; i++) {
longs[i] = (Long)l.get(i);
}
list.addAll(Arrays.asList(longs));
}
}
}
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putSerializable("list", list);
}
@Override
public void onDestroyView() {
StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) getRecyclerView().getLayoutManager();
int[] positions = layoutManager.findFirstVisibleItemPositions(null);
ArrayList<Long> ids = statusIdsDatabase.getIds();
if (ids.size() - positions[0] > 1000){
List<Long> list = ids.subList(positions[0] + 1000, ids.size());
statusIdsDatabase.deleteIds(list);
boolean[] results = statusIdsDatabase.hasIdsOtherTable(list);
List<Long> deletableIds = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
if (!results[i]) {
deletableIds.add(list.get(i));
}
}
GlobalApplication.statusCache.delete(deletableIds);
}
super.onDestroyView();
subscription.unsubscribe();
adapter=null;
}
@Override
public void onStop() {
super.onStop();
StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) getRecyclerView().getLayoutManager();
int[] positions = layoutManager.findFirstVisibleItemPositions(null);
if (positions[0]!= LAST_SAVED_LIST_POSITION){
statusIdsDatabase.setListViewPosition(positions[0]);
}
}
@Override
public void onDestroy() {
super.onDestroy();
statusIdsDatabase.close();
statusIdsDatabase = null;
subscription = null;
list=null;
}
@Override
protected void onInitializeList() {
subscription.add(
getResponseSingle(new Paging(1,20))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
result-> {
List<Long> ids = Observable
.from(result)
.map(Status::getId)
.toList().toSingle().toBlocking().value();
list.addAll(ids);
statusIdsDatabase.addIds(ids);
adapter.notifyDataSetChanged();
getSwipeRefreshLayout().setRefreshing(false);
setProgressCircleLoading(false);
},
e -> {
e.printStackTrace();
Snackbar.make(getSnackBarParentContainer(), TwitterStringUtils.convertErrorToText(e), Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.retry, v -> onInitializeList())
.show();
}
)
);
}
@Override
protected void onUpdateList() {
subscription.add(
getResponseSingle(new Paging(list.get(list.size() >= 2? 1: 0)).count(GlobalApplication.statusLimit))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
result -> {
if (result.size() > 0) {
List<Long> ids = Observable
.from(result)
.map(Status::getId)
.toList().toSingle().toBlocking().value();
if (ids.get(ids.size() - 1).equals(list.get(0))) {
ids.remove(ids.size() - 1);
} else {
ids.add(-1L);
}
if (ids.size() > 0){
list.addAll(0, ids);
statusIdsDatabase.insertIds(0, ids);
adapter.notifyItemRangeInserted(0, ids.size());
TypedValue value=new TypedValue();
Toast t=Toast.makeText(getContext(),R.string.new_tweet,Toast.LENGTH_SHORT);
t.setGravity(
Gravity.TOP|Gravity.CENTER,
0,
getContext().getTheme().resolveAttribute(R.attr.actionBarSize, value, true)?
TypedValue.complexToDimensionPixelOffset(value.data, getResources().getDisplayMetrics()):
0
);
t.show();
}
}
getSwipeRefreshLayout().setRefreshing(false);
},
e -> {
e.printStackTrace();
getSwipeRefreshLayout().setRefreshing(false);
Snackbar.make(getSnackBarParentContainer(), TwitterStringUtils.convertErrorToText(e), Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.retry, v -> onUpdateList())
.show();
}
)
);
}
@Override
protected void onLoadMoreList() {
subscription.add(
getResponseSingle(new Paging().maxId(list.get(list.size()-1)-1L).count(GlobalApplication.statusLimit))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
result -> {
int size = result.size();
if (size > 0) {
List<Long> ids = Observable
.from(result)
.map(Status::getId)
.toList().toSingle().toBlocking().value();
list.addAll(ids);
statusIdsDatabase.insertIds(list.size() - size, ids);
adapter.notifyItemRangeInserted(list.size() - size, size);
}
},
e -> {
e.printStackTrace();
Snackbar.make(getSnackBarParentContainer(), TwitterStringUtils.convertErrorToText(e), Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.retry, v -> onLoadMoreList())
.show();
}
)
);
}
@Override
protected boolean isInitializedList() {
return !list.isEmpty();
}
@Override
protected RecyclerView.LayoutManager initializeRecyclerViewLayoutManager() {
WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return new StaggeredGridLayoutManager(
(int) Math.ceil(
(double)
//Calculated as:
//Picture area: (16 : 9) + Other content: (16 : 3)
(size.x * 12) / (size.y * 16)
),
StaggeredGridLayoutManager.VERTICAL
);
}
protected abstract String getCachedIdsDatabaseName();
public Single<ResponseList<Status>> getResponseSingle(Paging paging) {
return Single.create(
subscriber->{
try {
ResponseList<Status> statuses = getResponseList(paging);
if (statuses.size() > 0){
GlobalApplication.statusCache.addAll(statuses);
}
subscriber.onSuccess(statuses);
} catch (TwitterException e) {
subscriber.onError(e);
}
}
);
}
public abstract ResponseList<Status> getResponseList(Paging paging) throws TwitterException;
} | replace using method to other having a same functional in Fragment
| app/src/main/java/com/github/moko256/twicalico/BaseTweetListFragment.java | replace using method to other having a same functional in Fragment | <ide><path>pp/src/main/java/com/github/moko256/twicalico/BaseTweetListFragment.java
<ide> super.getItemOffsets(outRect, view, parent, state);
<ide>
<ide> int span = ((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex();
<del> float dens = getContext().getResources().getDisplayMetrics().density;
<add> float dens = getResources().getDisplayMetrics().density;
<ide>
<ide> outRect.left = Math.round(dens * (span == 0 ? 8f : 4f));
<ide> outRect.right = Math.round(dens * (span == ((StaggeredGridLayoutManager) parent.getLayoutManager()).getSpanCount() - 1 ? 8f : 4f)); |
|
Java | apache-2.0 | f590d433f64ba57509f58ae76c7cc7ff5a429cd4 | 0 | apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj | /*
* 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.uima.migratev3.jcas;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import org.apache.uima.UIMARuntimeException;
import org.apache.uima.cas.impl.TypeImpl;
import org.apache.uima.cas.impl.TypeSystemImpl;
import org.apache.uima.cas.impl.UimaDecompiler;
import org.apache.uima.internal.util.CommandLineParser;
import org.apache.uima.internal.util.Misc;
import org.apache.uima.internal.util.UIMAClassLoader;
import org.apache.uima.internal.util.function.Runnable_withException;
import org.apache.uima.pear.tools.PackageBrowser;
import org.apache.uima.pear.tools.PackageInstaller;
import org.apache.uima.util.FileUtils;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.PackageDeclaration;
import com.github.javaparser.ast.body.AnnotationDeclaration;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.ConstructorDeclaration;
import com.github.javaparser.ast.body.EnumDeclaration;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.body.TypeDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.AssignExpr;
import com.github.javaparser.ast.expr.BinaryExpr;
import com.github.javaparser.ast.expr.CastExpr;
import com.github.javaparser.ast.expr.EnclosedExpr;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.FieldAccessExpr;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.ast.expr.Name;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.expr.NullLiteralExpr;
import com.github.javaparser.ast.expr.ObjectCreationExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.expr.StringLiteralExpr;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.EmptyStmt;
import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt;
import com.github.javaparser.ast.stmt.ExpressionStmt;
import com.github.javaparser.ast.stmt.IfStmt;
import com.github.javaparser.ast.stmt.ReturnStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.PrimitiveType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import com.github.javaparser.printer.PrettyPrinter;
import com.github.javaparser.printer.PrettyPrinterConfiguration;
/**
* <p>A driver that scans given roots for source and/or class Java files that contain JCas classes
*
* <ul><li>identifies which ones appear to be JCas classes (heuristic)
* <ul><li>of these, identifies which ones appear to be v2
* <ul><li>converts these to v3</li></ul></li></ul>
*
* <li>also can receive a list of individual class names</li>
* </ul>
*
* <p>Creates summary and detailed reports of its actions.
*
* <p>Files representing JCas classes to convert are discovered by walking file system
* directories from various roots, specified as input. The tool operates in 1 of two exclusive
* "modes": migrating from sources (e.g., .java files) and migrating using compiled classes.
*
* <p>Compiled classes are decompiled and then migrated. This decompilation step usually
* requires a java classpath, which is supplied using the -migrateClasspath parameter.
* Exception: migrating PEAR files, which contain their own specification for a classpath.
*
* <p>The same JCas class may be encountered multiple
* times while walking the directory tree from the roots,
* with the same or different definition. All of these definitions are migrated.
*
* <p>Copies of the original and the converted files are put into the output file tree.
*
* <p>Directory structure, starting at -outputDirectory (which if not specified, is a new temp directory).
* The "a0", "a1" represent non-identical alternative definitions for the same class.
* <pre>
* converted/
* v2/ these are the decompiled or "found" source files
* a0/x/y/z/javapath/.../Classname.java root-id + fully qualified java class + package as slashified name
* /Classname2.java etc.
* a1/x/y/z/javapath/.../Classname.java if there are different root-ids
* ...
* v3/
* a0/x/y/z/javapath/.../Classname.java fully qualified java class + package as slashified name
* /Classname2.java etc.
* a1/x/y/z/javapath/.../Classname.java if there are different root-ids
* ...
*
* v3-classes - the compiled form if from classes and a java compiler was available
* The first directory is the id of the Jar or PEAR container.
* The second directory is the alternative.
*
* 23/a0/fully/slashified/package/class-name.class << parallel structure as v3/
*
* jars/ - copies of the original JARs with the converted JCas classes
* The first directory is the id of the Jar or PEAR container
* 7/jar-file-name-last-part.jar
* 12/jar-file-name-last-part.jar
* 14/ etc.
*
* pears - copies of the original PEARs with the converted JCas classes, if there were no duplicates
* 8/pear-file-name-last-art.pear
* 9/ etc.
*
* not-converted/ (skipped)
* logs/
* jar-map.txt list of index to paths
* pear-map.txt list of index to paths
* processed.txt
* duplicates.txt
* builtinsNotExtended.txt
* failed.txt
* skippedBuiltins.txt
* nonJCasFiles.txt
* woraroundDir.txt
* deletedCheckModified.txt
* manualInspection.txt
* pearFileUpdates.txt
* jarFileUpdates.txt
* ...
* </pre>
*
* <p>Operates in one of two modes:
* <pre>
* Mode 1: Given classes-roots and/or individual class names, and a migrateClasspath,
* scans the classes-routes looking for classes candidates
* - determines the class name,
* - decompiles that
* - migrates that decompiled source.
*
* if a Java compiler (JDK) is available,
* - compiles the results
* - does reassembly for Jars and PEARs, replacing the JCas classes.
*
* Mode 2: Given sources-roots
* scans the sources-routes looking for candidates
* - migrates that decompiled source.
* </pre>
*
* <p>Note: Each run clears the output directory before starting the migration.
*
* <p>Note: classpath may be specified using -migrateClassPath or as the class path used to run this tool.
*/
public class MigrateJCas extends VoidVisitorAdapter<Object> {
/* *****************************************************
* Internals
*
* Unique IDs of v2 and v3 artifacts:
* RootId + classname
*
* RootIdContainers (Set<RootId>) hold all discovered rootIds, at each Jar/Pear nesting level
* including outer level (no Jar/Pear).
* These are kept in a push-down stack
*
*
* Processing roots collection: done for source or class
* - iterate, for all roots
* -- processCollection for candidates rooted at that root
* --- candidate is .java or .class, with path, with pearClasspath string
* ---- migrate called on each candidate
* ----- check to see if already done, and if so, skip.
* ------ means: same byte or source code associated with same fqcn
*
* Root-ids: created for each unique pathpart in front of fully-qualified class name
* created for each unique path to Jar or PEAR
*
* Caching to speed up duplicate processing:
* - decompiling: if the byte[] is already done, use other value (if augmented migrateClasspath is the same)
* - source-migrating: if the source strings are the same.
*
* Multiple sources for single class:
* classname2multiSources: TreeMap from fqcn to CommonConverted (string or bytes)
* CommonConverted: supports multiple paths having identical string/bytes.
*
* Compiling: driven from c2ps array of fqcn, path
* - may have multiple entries for same fqcn, with different paths,
* -- only if different values for the impl
* - set when visiting top-level compilation unit non-built-in type
*
*/
/** manange the indention of printing routines */
private static final int[] indent = new int[1];
private static StringBuilder si(StringBuilder sb) { return Misc.indent(sb, indent); }
private static StringBuilder flush(StringBuilder sb) {
System.out.print(sb);
sb.setLength(0);
return sb;
}
private static final Integer INTEGER0 = Integer.valueOf(0);
private static int nextContainerId = 0;
/******************************************************************
* Container - exists in tree structure, has super, sub containers
* -- subcontainers: has path to it
* - holds set of rootIds in that container
* - topmost one has null parent, and null pathToJarOrPear
******************************************************************/
private static class Container {
final int id = nextContainerId++;
final Container parent; // null if at top level
/** root to scan from.
* Pears: is the loc in temp space of installed pear
* Jars: is the file system mounted on the Jar
* -- for inner Jars, the Jar is copied out into temp space. */
Path root;
final Path rootOrig; // for Jars and Pears, the original path ending in jar or pear
final Set<Container> subContainers = new HashSet<>();
final List<Path> candidates = new ArrayList<>();
final List<CommonConverted> convertedItems = new ArrayList<>();
final List<V3CompiledPathAndContainerItemPath> v3CompiledPathAndContainerItemPath = new ArrayList<>();
final boolean isPear;
final boolean isJar;
/** can't use Path as the type, because the equals for Path is object == */
final Set<String> _Types = new HashSet<>(); // has the non_Type path only if the _Type is found
boolean haveDifferentCapitalizedNamesCollidingOnWindows = false;
String pearClasspath; // not final - set by subroutine after defaulting
/** Cache of already done compiled classes, to avoid redoing them
* Kept by container, because the classpath could change the decompile */
private Map<byte[], CommonConverted> origBytesToCommonConverted = new HashMap<>();
Container(Container parent, Path root) {
this.parent = parent;
if (parent != null) {
parent.subContainers.add(this);
this.pearClasspath = parent.pearClasspath; // default, when expanding Jars.
}
this.rootOrig = root;
String s = root.toString().toLowerCase();
isJar = s.endsWith(".jar");
isPear = s.endsWith(".pear");
this.root = isPear
? installPear()
: isJar
? prepareJar()
: root;
// // debug
// if (!isPear && isJar) {
// System.out.println("debug prepare jar: " + this);
// }
}
/**
* Called when a new container is created
* @param container
* @param path
* @return install directory
*/
private Path installPear() {
try {
File pearInstallDir = Files.createTempDirectory(getTempDir(), "installedPear").toFile();
PackageBrowser ip = PackageInstaller.installPackage(pearInstallDir, rootOrig.toFile(), false);
String newClasspath = ip.buildComponentClassPath();
String parentClasspath = parent.pearClasspath;
this.pearClasspath = (null == parentClasspath || 0 == parentClasspath.length())
? newClasspath
: newClasspath + File.pathSeparator + parentClasspath;
return Paths.get(pearInstallDir.toURI());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* copies embedded Jar to temp position in default file system if embedded.
* @return overlayed zip file system
*/
private Path prepareJar() {
try {
Path theJar = rootOrig;
if (!theJar.getFileSystem().equals(FileSystems.getDefault())) {
// embedded Jar: copy the Jar (intact) to a temp spot so it's no longer embedded
theJar = getTempOutputPathForJar(theJar);
Files.copy(rootOrig, theJar, StandardCopyOption.REPLACE_EXISTING);
}
FileSystem jfs = FileSystems.newFileSystem(theJar, null);
return jfs.getPath("/");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
si(sb); // initial nl and indentation
sb.append(isJar ? "Jar " : isPear ? "PEAR " : "");
sb.append("container [id=").append(id)
.append(", parent.id=").append((null == parent) ? "null" : parent.id)
.append(", root or pathToJarOrPear=").append(rootOrig).append(',');
indent[0] += 2;
try {
si(sb); // new line + indent
sb.append("subContainers=");
Misc.addElementsToStringBuilder(indent, sb, Misc.setAsList(subContainers), -1, (sbx, i) -> sbx.append(i.id)).append(',');
si(sb).append("paths migrated="); // new line + indent
Misc.addElementsToStringBuilder(indent, sb, candidates, -1, StringBuilder::append).append(',');
// si(sb).append("v3CompilePath="); // new line + indent
// Misc.addElementsToStringBuilder(indent, sb, v3CompiledPathAndContainerItemPath, 100, StringBuilder::append);
} finally {
indent[0] -=2;
si(sb).append(']');
}
return sb.toString();
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return 31 * id;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Container other = (Container) obj;
if (id != other.id)
return false;
return true;
}
}
private static class ContainerAndPath {
final Path path;
final Container container;
ContainerAndPath(Path path, Container container) {
this.path = path;
this.container = container;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ContainerAndPath [path=").append(path).append(", container=").append(container.id).append("]");
return sb.toString();
}
}
/**
* a pair of the v3CompiledPath, and the Container origRoot up to the start of the package and class name
* for the item being compiled.
* - Note: if a Jar has the same compiled class at multiple nesting levels, each one will have
* an instance of this class
*/
private static class V3CompiledPathAndContainerItemPath {
final Path v3CompiledPath;
final String pathInContainer;
public V3CompiledPathAndContainerItemPath(Path v3CompiledPath, String pathInContainer) {
this.v3CompiledPath = v3CompiledPath;
this.pathInContainer = pathInContainer;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
si(sb).append("v3CompiledPathAndContainerPartPath [");
indent[0] += 2;
try {
si(sb).append("v3CompiledPath=").append(v3CompiledPath);
si(sb).append("pathInContainer=").append(pathInContainer);
} finally {
indent[0] -= 2;
si(sb).append("]");
}
return sb.toString();
}
}
private static final JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
/****************************************************************
* Command line parameters
****************************************************************/
private static final String SOURCE_FILE_ROOTS = "-sourcesRoots";
private static final String CLASS_FILE_ROOTS = "-classesRoots";
private static final String OUTPUT_DIRECTORY = "-outputDirectory";
// private static final String SKIP_TYPE_CHECK = "-skipTypeCheck";
private static final String MIGRATE_CLASSPATH = "-migrateClasspath";
// private static final String CLASSES = "-classes"; // individual classes to migrate, get from supplied classpath
private static final Type intType = PrimitiveType.intType();
private static final EnumSet<Modifier> public_static_final =
EnumSet.of(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL);
private static final PrettyPrinterConfiguration printWithoutComments =
new PrettyPrinterConfiguration();
static { printWithoutComments.setPrintComments(false); }
private static final PrettyPrinterConfiguration printCu =
new PrettyPrinterConfiguration();
static { printCu.setIndent(" "); }
private static final String ERROR_DECOMPILING = "!!! ERROR:";
static private boolean isSource = false;
static private Path tempDir = null;
/***************************************************************************************************/
private String packageName; // with dots?
private String className; // (omitting package)
private String packageAndClassNameSlash;
// next 3 set at start of migrate for item being migrated
private CommonConverted current_cc;
private Path current_path;
private Container current_container;
/** includes trailing / */
private String outputDirectory;
/** includes trailing / */
private String outDirConverted;
/** includes trailing / */
private String outDirSkipped;
/** includes trailing / */
private String outDirLog;
private Container[] sourcesRoots = new Container[0]; // only one of these has 1 or more Container instances
private Container[] classesRoots = new Container[0];
private CompilationUnit cu;
// save this value in the class instance to avoid recomputing it
private ClassLoader cachedMigrateClassLoader = null;
private String migrateClasspath = null;
// private String individualClasses = null; // to decompile
/**
* CommonConverted next id, by fqcn
* key: fqcn_slashes value: next id
*/
private Map<String, Integer> nextCcId = new HashMap<>();
/**
* Common info about a particular source-code instance of a class
* Used to avoid duplicate work for the same JCas definition
* Used to track identical and non-identical duplicate defs
*
* When processing from sourcesRoots:
* use map: origSourceToCommonConverted key = source string
* if found, skip conversion, use previous converted result.
*
* When processing from classesRoots:
* use map: origBytesToCommonConverted key = byte[], kept by container in container
* if found, use previous converted results
*/
private class CommonConverted {
/**
* starts at 0, incr for each new instance for a particular fqcn_slash
* can't be assigned until fqcn known
*/
int id = -1; // temp value
final String v2Source; // remembered original source
final byte[] v2ByteCode; // remembered original bytes
/** all paths + their containers having the same converted result
* Need container because might change classpath for compiling
* - path is to v2 source or compiled class*/
final Set<ContainerAndPath> containersAndV2Paths = new HashSet<>();
String v3Source; // if converted, the result
/** converted/v3/id-of-cc/pkg/name/classname.java */
Path v3SourcePath; // path to converted source or null
String fqcn_slash; // full name of the class e.g. java/util/Foo. unknown for sources at first
CommonConverted(String origSource, byte[] v2ByteCode, Path path, Container container, String fqcn_slash) {
this.v2Source = origSource;
this.v2ByteCode = v2ByteCode;
containersAndV2Paths.add(new ContainerAndPath(path, container));
this.fqcn_slash = fqcn_slash;
}
Path getV2SourcePath(Container container) {
for (ContainerAndPath cp : containersAndV2Paths) {
if (cp.container == container) {
return cp.path;
}
}
throw new RuntimeException("internalError");
}
int getId() {
if (id < 0) {
Integer nextId = nextCcId.computeIfAbsent(fqcn_slash, s -> INTEGER0);
nextCcId.put(fqcn_slash, nextId + 1);
this.id = nextId;
}
return id;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return v2Source == null ? 0 : v2Source.hashCode();
}
/* equal if the v2source is equal
*/
@Override
public boolean equals(Object obj) {
return obj instanceof CommonConverted &&
v2Source != null &&
v2Source.equals(((CommonConverted)obj).v2Source);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
int maxLen = 10;
si(sb).append("CommonConverted [v2Source=").append(Misc.elide(v2Source, 100));
indent[0] += 2;
try {
si(sb).append("v2ByteCode=");
sb.append(v2ByteCode != null
? Arrays.toString(Arrays.copyOf(v2ByteCode, Math.min(v2ByteCode.length, maxLen))) :
"null").append(',');
si(sb).append("containersAndPaths=")
.append(containersAndV2Paths != null
? Misc.ppList(indent, Misc.setAsList(containersAndV2Paths), -1, StringBuilder::append)
: "null").append(',');
si(sb).append("v3SourcePath=").append(v3SourcePath).append(',');
si(sb).append("fqcn_slash=").append(fqcn_slash).append("]").append(Misc.ls);
} finally {
indent[0] -= 2;
}
return sb.toString();
}
}
/** Cache of already converted source classes, to avoid redoing them;
* - key is the actual source
* - value is CommonConverted
* This cache is over all containers
* */
private Map<String, CommonConverted> sourceToCommonConverted = new HashMap<>();
/**
* A map from fqcn_slash to a list of converted sources
* one per non-duplicated source
*/
private Map<String, List<CommonConverted>> classname2multiSources = new TreeMap<>();
/************************************
* Reporting
************************************/
// private final List<Path> v2JCasFiles = new ArrayList<>(); // unused
// private final List<Path> v3JCasFiles = new ArrayList<>(); // unused
private final List<PathAndReason> nonJCasFiles = new ArrayList<>(); // path, reason
private final List<PathAndReason> failedMigration = new ArrayList<>(); // path, reason
private final List<PathAndReason> skippedBuiltins = new ArrayList<>(); // path, "built-in"
private final List<PathAndReason> deletedCheckModified = new ArrayList<>(); // path, deleted check string
private final List<String1AndString2> pathWorkaround = new ArrayList<>(); // original, workaround
private final List<String1AndString2> pearClassReplace = new ArrayList<>(); // pear, classname
private final List<String1AndString2> jarClassReplace = new ArrayList<>(); // jar, classname
private final List<PathAndReason> manualInspection = new ArrayList<>(); // path, reason
// private final List<PathAndPath> embeddedJars = new ArrayList<>(); // source, temp
private boolean isV2JCas; // false at start of migrate, set to true if a v2 class candidate is discovered
private boolean isConvert2v3; // true at start of migrate, set to false if conversion fails, left true if already a v3
private boolean isBuiltinJCas; // false at start of migrate, set to true if a built-in class is discovered
/************************************
* Context for visits
************************************/
/**
* if non-null, we're inside the ast for a likely JCas getter or setter method
*/
private MethodDeclaration get_set_method;
private String featName;
private boolean isGetter;
private boolean isArraySetter;
/**
* the range name part for _getXXXValue.. calls
*/
private Object rangeNamePart;
/**
* the range name part for _getXXXValue.. calls without converting Ref to Feature
*/
private String rangeNameV2Part;
/**
* temp place to insert static final int feature declarations
*/
private NodeList<BodyDeclaration<?>> fi_fields = new NodeList<>();
private Set<String> featNames = new HashSet<>();
private boolean hasV2Constructors;
private boolean hasV3Constructors;
private boolean error_decompiling = false;
private boolean badClassName;
private int itemCount;
/**
* set if getAndProcessCasndidatesInContainer encounters a class where it cannot do the compile
*/
private boolean unableToCompile;
final private StringBuilder psb = new StringBuilder();
public MigrateJCas() {
}
public static void main(String[] args) {
(new MigrateJCas()).run(args);
}
/***********************************
* Main
* @param args -
***********************************/
void run(String[] args) {
CommandLineParser clp = parseCommandArgs(args);
System.out.format("Output top directory: %s%n", outputDirectory);
// clear output dir
FileUtils.deleteRecursive(new File(outputDirectory));
isSource = sourcesRoots.length > 0;
boolean isOk;
if (isSource) {
isOk = processRootsCollection("source", sourcesRoots, clp);
} else {
if (javaCompiler == null) {
System.out.println("The migration tool cannot compile the migrated files, \n"
+ " because no Java compiler is available.\n"
+ " To make one available, run this tool using a Java JDK, not JRE");
}
isOk = processRootsCollection("classes", classesRoots, clp);
}
// if (individualClasses != null) {
// processCollection("individual classes: ", new Iterator<String>() {
// Iterator<String> it = Arrays.asList(individualClasses.split(File.pathSeparator)).iterator();
// public boolean hasNext() {return it.hasNext();}
// public String next() {
// return prepareIndividual(it.next());}
// });
// }
if (error_decompiling) {
isOk = false;
}
isOk = report() && isOk;
System.out.println("Migration finished " +
(isOk
? "with no unusual conditions."
: "with 1 or more unusual conditions that need manual checking."));
}
/**
* called for compiled input when a compiler is available and don't have name collision
* if the container is a PEAR or a Jar
* Updates a copy of the Pear or Jar
* @param container
*/
private void postProcessPearOrJar(Container container) {
Path outDir = Paths.get(outputDirectory,
container.isJar ? "jars" : "pears",
Integer.toString(container.id));
withIOX(() -> Files.createDirectories(outDir));
si(psb).append("Replacing .class files in copy of ").append(container.rootOrig);
flush(psb);
try {
// copy the pear or jar so we don't change the original
Path lastPartOfPath = container.rootOrig.getFileName();
if (null == lastPartOfPath) throw new RuntimeException("Internal Error");
Path pearOrJarCopy = Paths.get(outputDirectory,
container.isJar ? "jars" : "pears",
Integer.toString(container.id),
lastPartOfPath.toString());
Files.copy(container.rootOrig, pearOrJarCopy);
// put up a file system on the pear or jar
FileSystem pfs = FileSystems.newFileSystem(pearOrJarCopy, null);
// replace the .class files in this PEAR or Jar with corresponding v3 ones
indent[0] += 2;
String[] previousSkip = {""};
container.v3CompiledPathAndContainerItemPath.forEach(c_p -> {
if (Files.exists(c_p.v3CompiledPath)) {
withIOX(() -> Files.copy(c_p.v3CompiledPath, pfs.getPath(c_p.pathInContainer), StandardCopyOption.REPLACE_EXISTING));
reportPearOrJarClassReplace(pearOrJarCopy.toString(), c_p.v3CompiledPath.toString(), container);
} else {
String pstr = c_p.v3CompiledPath.toString();
String pstr2 = pstr;
if (previousSkip[0] != "") {
int cmn = findFirstCharDifferent(previousSkip[0], pstr);
pstr2 = cmn > 5
? ("..." + pstr.substring(cmn))
: pstr;
}
previousSkip[0] = pstr;
si(psb).append("Skipping replacing ").append(pstr2)
.append(" due to compile errors.");
flush(psb);
}
});
indent[0] -= 2;
// for (CommonConverted cc : container.convertedItems) {
// Map<Container, Path> v3ccs = cc.v3CompiledResultPaths;
// v3ccs.forEach((v3ccc, v3cc_path) ->
// {
// if (v3ccc == container) {
// String path_in_v3_classes = cc.v3CompiledResultPaths.get(container).toString();
//
// withIOX(() -> Files.copy(v3cc_path, pfs.getPath(path_in_v3_classes)));
// reportPearOrJarClassReplace(pearOrJarCopy.toString(), path_in_v3_classes, container);
// }
// });
// }
pfs.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Compile all the migrated JCas classes in this container, adjusting the classpath
* if the container is a Jar or Pear to include the Jar or PEAR.
*
* As a side effect, it saves in the container, a list of all the compiled things together
* with the path in container part, for use by a subsequent step to update copies of the jars/pears.
*
* @param container
* @return true if compiled 1 or more sources, false if nothing was compiled
*/
private boolean compileV3SourcesCommon2(Container container) {
String classesBaseDir = outDirConverted + "v3-classes/" + container.id;
// specify the classpath. For PEARs use a class loader that loads first.
String classpath = getCompileClassPath(container);
// // debug
// String[] cpa = classpath.split(File.pathSeparator);
// System.out.println("debug - compilation classpath");
// int j = 0;
// for (String s : cpa) System.out.println("debug classpath: " + (++j) + " " + s);
// get a list of compilation unit path strings to the converted/v3/nnn/path
Path containerRoot = null;
/**
* The Cu Path Strings for one container might have multiple instances of the class.
* These might be for identical or different sources.
* - This happens when a root has multiple paths to instances of the same class.
* - Multiple compiled-paths might be for the same classname
*
* For non-identical sources, the commonContainer instance "id" is spliced into the
* v3 migrated source path: see getBaseOutputPath, e.g. converted/v3/2/fqcn/slashed/name.java
*
* The compiler will complain if you feed it the same compilation unit classname twice, with
* different paths saying "duplicate class definition".
* - Fix: do compilation in batches, one for each different commonConvertedContainer id.
*/
Map<Integer, ArrayList<String>> cu_path_strings_by_ccId = new TreeMap<>(); // tree map to have nice order of keys
indent[0] += 2;
boolean isEmpty = true;
for (CommonConverted cc : container.convertedItems) {
if (cc.v3SourcePath == null) continue; // skip items that failed migration
isEmpty = false;
// relativePathInContainer = the whole path with the first part (up to the end of the container root) stripped off
Path itemPath = cc.getV2SourcePath(container);
if (null == containerRoot) {
// lazy setup on first call
// for Pears, must use the == filesystem, otherwise get
// ProviderMismatchException
containerRoot = (container.isJar || container.isPear)
? itemPath.getFileSystem().getPath("/")
: container.rootOrig;
}
Path relativePathInContainer = containerRoot.relativize(cc.getV2SourcePath(container));
container.v3CompiledPathAndContainerItemPath.add(
new V3CompiledPathAndContainerItemPath(
Paths.get(classesBaseDir, "a" + cc.id, relativePathInContainer.toString()),
relativePathInContainer.toString()));
ArrayList<String> items = cu_path_strings_by_ccId.computeIfAbsent(cc.id, x -> new ArrayList<>());
items.add(cc.v3SourcePath.toString());
}
if (isEmpty) {
si(psb).append("Skipping compiling for container ").append(container.id).append(" ").append(container.rootOrig);
si(psb).append(" because non of the v2 classes were migrated (might have been built-ins)");
flush(psb);
return false;
}
else {
si(psb).append("Compiling for container ").append(container.id).append(" ").append(container.rootOrig);
flush(psb);
}
// List<String> cu_path_strings = container.convertedItems.stream()
// .filter(cc -> cc.v3SourcePath != null)
// .peek(cc -> container.v3CompiledPathAndContainerItemPath.add(
// new V3CompiledPathAndContainerItemPath(
// Paths.get(classesBaseDir, cc.v3SourcePath.toString()),
// getPathInContainer(container, cc).toString())))
// .map(cc -> cc.v3SourcePath.toString())
// .collect(Collectors.toList());
boolean resultOk = true;
for (int ccId = 0;; ccId++) { // do each version of classes separately
List<String> cups = cu_path_strings_by_ccId.get(ccId);
if (cups == null) {
break;
}
StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, Charset.forName("UTF-8"));
Iterable<? extends JavaFileObject> compilationUnits =
fileManager.getJavaFileObjectsFromStrings(cups);
// //debug
// System.out.println("Debug: list of compilation unit strings for iteration " + i);
// int[] k = new int[] {0};
// cups.forEach(s -> System.out.println(Integer.toString(++(k[0])) + " " + s));
// System.out.println("debug end");
String classesBaseDirN = classesBaseDir + "/a" + ccId;
withIOX(() -> Files.createDirectories(Paths.get(classesBaseDirN)));
Iterable<String> options = Arrays.asList("-d", classesBaseDirN, "-classpath", classpath);
si(psb).append("Compiling for commonConverted version ").append(ccId)
.append(", ").append(cups.size()).append(" classes");
flush(psb);
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
/*********** Compile ***********/
resultOk = javaCompiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits).call() && resultOk;
/********************************/
indent[0] += 2;
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
JavaFileObject s = diagnostic.getSource();
si(psb).append(diagnostic.getKind());
int lineno = (int) diagnostic.getLineNumber();
if (lineno != Diagnostic.NOPOS) {
psb.append(" on line ").append(diagnostic.getLineNumber());
}
int pos = (int) diagnostic.getPosition();
if (pos != Diagnostic.NOPOS) {
psb.append(", position: ").append(diagnostic.getColumnNumber());
}
if (s != null) {
psb.append(" in ").append(s.toUri());
}
si(psb).append(" ").append(diagnostic.getMessage(null));
flush(psb);
}
withIOX( () -> fileManager.close());
indent[0] -= 2;
si(psb).append("Compilation finished").append(
resultOk ? " with no errors." : "with some errors.");
flush(psb);
}
indent[0] -= 2;
unableToCompile = !resultOk;
return true;
}
/**
* The classpath used to compile is (in precedence order)
* - the classpath for this migration app (first in order to pick up v3 support, overriding others)
* - any Pears, going up the parent chain, closest ones first
* - any Jars, going up the parent chain, closest ones last
* - passed in migrate classpath
* @return the classpath to use in compiling the jcasgen'd sources
*/
private String getCompileClassPath(Container container) {
// start with this (the v3migration tool) app's classpath to a cp string
URLClassLoader systemClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
URL[] urls = systemClassLoader.getURLs();
StringBuilder cp = new StringBuilder();
boolean firstTime = true;
for (URL url : urls) {
if (! firstTime) {
cp.append(File.pathSeparatorChar);
} else {
firstTime = false;
}
cp.append(url.getPath());
}
// pears up the classpath, closest first
Container c = container;
while (c != null) {
if (c.isPear) {
cp.append(File.pathSeparator).append(c.pearClasspath);
}
c = c.parent;
}
// add the migrateClasspath, expanded
if (null != migrateClasspath) {
cp.append(File.pathSeparator).append(Misc.expandClasspath(migrateClasspath));
}
// add the Jars, closest last
c = container;
List<String> ss = new ArrayList<>();
while (c != null) {
if (c.isJar) {
ss.add(c.root.toString());
}
c = c.parent;
}
Collections.reverse(ss);
ss.forEach(s -> cp.append(File.pathSeparator).append(s));
// System.out.println("debug: compile classpath = " + cp.toString());
return cp.toString();
}
/**
* iterate to process collections from all roots
* Called once, to process either sources or classes
* @return false if unable to compile, true otherwise
*/
private boolean processRootsCollection(String kind, Container[] roots, CommandLineParser clp) {
unableToCompile = false; // preinit
psb.setLength(0);
indent[0] = 0;
itemCount = 1;
for (Container rootContainer : roots) {
showWorkStart(rootContainer);
// adds candidates to root containers, and adds sub containers for Jars and Pears
getAndProcessCandidatesInContainer(rootContainer);
// for (Path path : rootContainer.candidates) {
//
// CommonConverted cc = getSource(path, rootContainer);
// migrate(cc, rootContainer, path);
//
// if ((i % 50) == 0) System.out.format("%4d%n ", Integer.valueOf(i));
// i++;
// }
}
si(psb).append("Total number of candidates processed: ").append(itemCount - 1);
flush(psb);
indent[0] = 0;
return !unableToCompile;
}
private void showWorkStart(Container rootContainer) {
si(psb).append("Migrating " + rootContainer.rootOrig.toString());
indent[0] += 2;
si(psb).append("Each character is one class");
si(psb).append(" . means normal class");
si(psb).append(" b means built in");
si(psb).append(" i means identical duplicate");
si(psb).append(" d means non-identical definition for the same JCas class");
si(psb).append(" nnn at the end of the line is the number of classes migrated");
flush(psb);
}
/**
* parse command line args
* @param args -
* @return the CommandLineParser instance
*/
private CommandLineParser parseCommandArgs(String[] args) {
CommandLineParser clp = createCmdLineParser();
try {
clp.parseCmdLine(args);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (!checkCmdLineSyntax(clp)) {
printUsage();
System.exit(2);
}
if (clp.isInArgsList(CLASS_FILE_ROOTS)) {
classesRoots = getRoots(clp, CLASS_FILE_ROOTS);
}
if (clp.isInArgsList(SOURCE_FILE_ROOTS)) {
sourcesRoots = getRoots(clp, SOURCE_FILE_ROOTS);
}
return clp;
}
private Container[] getRoots(CommandLineParser clp, String kind) {
String[] paths = clp.getParamArgument(kind).split("\\" + File.pathSeparator);
Container[] cs = new Container[paths.length];
int i = 0;
for (String path : paths) {
cs[i++] = new Container(null, Paths.get(path));
}
return cs;
}
/**
* @param p the path to the compiled or non-compiled source
* @param container the container
* @return the instance of the CommonConverted object,
* and update the container's convertedItems list if needed to include it
*/
private CommonConverted getSource(Path p, Container container) {
try {
byte[] localV2ByteCode = null;
CommonConverted cc;
String v2Source;
if (!isSource) {
localV2ByteCode = Files.readAllBytes(p);
// only use prev decompiled if same container
cc = container.origBytesToCommonConverted.get(localV2ByteCode);
if (null != cc) {
return cc;
}
// decompile side effect: sets fqcn
try {
v2Source = decompile(localV2ByteCode, container.pearClasspath);
} catch (RuntimeException e) {
badClassName = true;
e.printStackTrace();
v2Source = null;
}
if (badClassName) {
System.err.println("Candidate with bad Class Name is: " + p.toString());
return null;
}
final byte[] finalbc = localV2ByteCode;
cc = sourceToCommonConverted.computeIfAbsent(v2Source,
src -> new CommonConverted(src, finalbc, p, container, packageAndClassNameSlash));
// cc = new CommonConverted(v2Source, localV2ByteCode, p, container, packageAndClassNameSlash);
container.origBytesToCommonConverted.put(localV2ByteCode, cc);
} else {
v2Source = FileUtils.reader2String(Files.newBufferedReader(p));
cc = sourceToCommonConverted.get(v2Source);
if (null == cc) {
cc = new CommonConverted(v2Source, null, p, container, "unknown");
sourceToCommonConverted.put(v2Source, cc);
} else {
// add this new path + container to set of pathsAndContainers kept by this CommonConverted object
cc.containersAndV2Paths.add(new ContainerAndPath(p, container));
}
}
//Containers have list of CommonConverted, which, in turn
// have Set of ContainerAndPath elements.
// (the same JCas class might appear in two different paths in a container)
if (!container.convertedItems.contains(cc)) {
container.convertedItems.add(cc);
}
return cc;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Migrate one JCas definition, writes to Sysem.out 1 char to indicate progress.
*
* The source is either direct, or a decompiled version of a .class file (missing comments, etc.).
*
* This method only called if heuristics indicate this is a V2 JCas class definition.
*
* Skips the migration if already done.
* Skips if decompiling, and it failed.
*
* The goal is to preserve as much as possible of existing customization.
* The general approach is to parse the source into an AST, and use visitor methods.
* For getter/setter methods that are for features (heurstic), set up a context for inner visitors
* identifying the getter / setter.
* - reuse method declarator, return value casts, value expressions
* - remove feature checking statement, array bounds checking statement, if present.
* - replace the simpleCore (see Jg), replace the arrayCore
*
* For constructors, replace the 2-arg one that has arguments:
* addr and TOP_Type with the v3 one using TypeImpl, CasImpl.
*
* Add needed imports.
* Add for each feature the _FI_xxx static field declarator.
*
* Leave other top level things alone
* - additional constructors.
* - other methods not using jcasType refs
*
* @param source - the source, either directly from a .java file, or a decompiled .class file
*/
private void migrate(CommonConverted cc, Container container, Path path) {
if (null == cc) {
System.err.println("Skipping this component due to decompile failure: " + path.toString());
System.err.println(" in container: " + container);
isConvert2v3 = false;
error_decompiling = true;
return;
}
if (cc.v3Source != null) {
// next updates classname2multiSources for tracking non-identical defs
boolean identical = collectInfoForReports(cc);
assert identical;
psb.append("i");
flush(psb);
cc.containersAndV2Paths.add(new ContainerAndPath(path, container));
return;
}
assert cc.v2Source != null;
packageName = null;
className = null;
packageAndClassNameSlash = null;
cu = null;
String source = cc.v2Source;
isConvert2v3 = true; // preinit, set false if convert fails
isV2JCas = false; // preinit, set true by reportV2Class, called by visit to ClassOrInterfaceDeclaration,
// when it has v2 constructors, and the right type and type_index_id field declares
isBuiltinJCas = false;
featNames.clear();
fi_fields.clear();
try { // to reset the next 3 items
current_cc = cc;
current_container = container;
current_path = path;
// System.out.println("Migrating source before migration:\n");
// System.out.println(source);
// System.out.println("\n\n\n");
if (source.startsWith(ERROR_DECOMPILING)) {
System.err.println("Decompiling failed for class: " + cc.toString() + "\n got: " + Misc.elide(source, 300, false));
System.err.println("Please check the migrateClasspath");
if (null == migrateClasspath) {
System.err.println("classpath of this app is");
System.err.println(System.getProperty("java.class.path"));
} else {
System.err.println(" first part of migrateClasspath argument was: " + Misc.elide(migrateClasspath, 300, false));
System.err.println(" Value used was:");
URL[] urls = Misc.classpath2urls(migrateClasspath);
for (URL url : urls) {
System.err.println(" " + url.toString());
}
}
System.err.println("Skipping this component");
isConvert2v3 = false;
error_decompiling = true;
return;
}
StringReader sr = new StringReader(source);
try {
cu = JavaParser.parse(sr);
addImport("org.apache.uima.cas.impl.CASImpl");
addImport("org.apache.uima.cas.impl.TypeImpl");
addImport("org.apache.uima.cas.impl.TypeSystemImpl");
this.visit(cu, null); // side effect: sets the className, packageAndClassNameSlash, packageName
new removeEmptyStmts().visit(cu, null);
if (isConvert2v3) {
removeImport("org.apache.uima.jcas.cas.TOP_Type");
}
if (isConvert2v3 && fi_fields.size() > 0) {
NodeList<BodyDeclaration<?>> classMembers = cu.getTypes().get(0).getMembers();
int positionOfFirstConstructor = findConstructor(classMembers);
if (positionOfFirstConstructor < 0) {
throw new RuntimeException();
}
classMembers.addAll(positionOfFirstConstructor, fi_fields);
}
if (isSource) {
sourceToCommonConverted.put(source, cc);
}
boolean identicalFound = collectInfoForReports(cc);
assert ! identicalFound;
if (isV2JCas) {
writeV2Orig(cc, isConvert2v3);
}
if (isConvert2v3) {
cc.v3Source = new PrettyPrinter(printCu).print(cu);
writeV3(cc);
}
psb.append(isBuiltinJCas
? "b"
: (classname2multiSources.get(cc.fqcn_slash).size() == 1)
? "."
: "d"); // means non-identical duplicate
flush(psb);
} catch (IOException e) {
e.printStackTrace();
throw new UIMARuntimeException(e);
} catch (Exception e) {
System.out.println("debug: exception caught, source was\n" + source);
throw new UIMARuntimeException(e);
}
} finally {
current_cc = null;
current_container = null;
current_path = null;
}
}
/**
* Called when have already converted this exact source or
* when we just finished converting this source.
* Add this instance to the tracking information for multiple versions (identical or not) of a class
* @return true if this is an identical duplicate of one already done
*/
private boolean collectInfoForReports(CommonConverted cc) {
String fqcn_slash = cc.fqcn_slash;
// track, by fqcn, all duplicates (identical or not)
// // for a given fully qualified class name (slashified),
// // find the list of CommonConverteds - one per each different version
// // create it if null
List<CommonConverted> commonConverteds = classname2multiSources
.computeIfAbsent(fqcn_slash, k -> new ArrayList<CommonConverted>());
// search to see if this instance already in the set
// if so, add the path to the set of identicals
// For class sources case, we compare the decompiled version
boolean found = commonConverteds.contains(cc);
if (!found) {
commonConverteds.add(cc);
}
return found;
}
/******************
* Visitors
******************/
/**
* Capture the type name from all top-level types
* AnnotationDeclaration, Empty, and Enum
*/
@Override
public void visit(AnnotationDeclaration n, Object ignore) {
updateClassName(n);
super.visit(n, ignore);
}
// @Override
// public void visit(EmptyTypeDeclaration n, Object ignore) {
// updateClassName(n);
// super.visit(n, ignore);
// }
@Override
public void visit(EnumDeclaration n, Object ignore) {
updateClassName(n);
super.visit(n, ignore);
}
/**
* Check if the top level class looks like a JCas class, and report if not:
* has 0, 1, and 2 element constructors
* has static final field defs for type and typeIndexID
*
* Also check if V2 style: 2 arg constructor arg types
* Report if looks like V3 style due to args of 2 arg constructor
*
* if class doesn't extend anything, not a JCas class.
* if class is enum, not a JCas class
* @param n -
* @param ignore -
*/
@Override
public void visit(ClassOrInterfaceDeclaration n, Object ignore) {
// do checks to see if this is a JCas class; if not report skipped
Optional<Node> maybeParent = n.getParentNode();
if (maybeParent.isPresent()) {
Node parent = maybeParent.get();
if (parent instanceof CompilationUnit) {
updateClassName(n);
if (isBuiltinJCas) {
// is a built-in class, skip it
super.visit(n, ignore);
return;
}
NodeList<ClassOrInterfaceType> supers = n.getExtendedTypes();
if (supers == null || supers.size() == 0) {
reportNotJCasClass("class doesn't extend a superclass");
super.visit(n, ignore);
return;
}
NodeList<BodyDeclaration<?>> members = n.getMembers();
setHasJCasConstructors(members);
if (hasV2Constructors && hasTypeFields(members)) {
reportV2Class();
super.visit(n, ignore);
return;
}
if (hasV2Constructors) {
reportNotJCasClassMissingTypeFields();
return;
}
if (hasV3Constructors) {
reportV3Class();
return;
}
reportNotJCasClass("missing v2 constructors");
return;
}
}
super.visit(n, ignore);
return;
}
@Override
public void visit(PackageDeclaration n, Object ignored) {
packageName = n.getNameAsString();
super.visit(n, ignored);
}
/***************
* Constructors
* - modify the 2 arg constructor - changing the args and the body
* @param n - the constructor node
* @param ignored -
*/
@Override
public void visit(ConstructorDeclaration n, Object ignored) {
super.visit(n, ignored); // processes the params
if (!isConvert2v3) { // for enums, annotations
return;
}
List<Parameter> ps = n.getParameters();
if (ps.size() == 2 &&
getParmTypeName(ps, 0).equals("int") &&
getParmTypeName(ps, 1).equals("TOP_Type")) {
/** public Foo(TypeImpl type, CASImpl casImpl) {
* super(type, casImpl);
* readObject();
*/
setParameter(ps, 0, "TypeImpl", "type");
setParameter(ps, 1, "CASImpl", "casImpl");
// Body: change the 1st statement (must be super)
NodeList<Statement> stmts = n.getBody().getStatements();
if (!(stmts.get(0) instanceof ExplicitConstructorInvocationStmt)) {
recordBadConstructor("missing super call");
return;
}
NodeList<Expression> args = ((ExplicitConstructorInvocationStmt)(stmts.get(0))).getArguments();
args.set(0, new NameExpr("type"));
args.set(1, new NameExpr("casImpl"));
// leave the rest unchanged.
}
}
private final static Pattern refGetter = Pattern.compile("(ll_getRef(Array)?Value)|"
+ "(ll_getFSForRef)");
private final static Pattern word1 = Pattern.compile("\\A(\\w*)"); // word chars starting at beginning \\A means beginning
/*****************************
* Method Declaration Visitor
* Heuristic to determine if a feature getter or setter:
* - name: is 4 or more chars, starting with get or set, with 4th char uppercase
* is not "getTypeIndexID"
* - (optional - if comments are available:)
* getter for xxx, setter for xxx
* - for getter: has 0 or 1 arg (1 arg case for indexed getter, arg must be int type)
* - for setter: has 1 or 2 args
*
* Workaround for decompiler - getters which return FSs might be missing the cast to the return value type
*
*****************************/
@Override
public void visit(MethodDeclaration n, Object ignore) {
String name = n.getNameAsString();
isGetter = isArraySetter = false;
do { // to provide break exit
if (name.length() >= 4 &&
((isGetter = name.startsWith("get")) || name.startsWith("set")) &&
Character.isUpperCase(name.charAt(3)) &&
!name.equals("getTypeIndexID")) {
List<Parameter> ps = n.getParameters();
if (isGetter) {
if (ps.size() > 1) break;
} else { // is setter
if (ps.size() > 2 ||
ps.size() == 0) break;
if (ps.size() == 2) {
if (!getParmTypeName(ps, 0).equals("int")) break;
isArraySetter = true;
}
}
// get the range-part-name and convert to v3 range ("Ref" changes to "Feature")
String bodyString = n.getBody().get().toString(printWithoutComments);
int i = bodyString.indexOf("jcasType.ll_cas.ll_");
if (i < 0) break;
String s = bodyString.substring(i + "jcasType.ll_cas.ll_get".length()); // also for ...ll_set - same length!
if (s.startsWith("FSForRef(")) { // then it's the wrapper and the wrong instance.
i = s.indexOf("jcasType.ll_cas.ll_");
if (i < 0) {
reportUnrecognizedV2Code("Found \"jcasType.ll_cas.ll_[set or get]...FSForRef(\" but didn't find following \"jcasType.ll_cas_ll_\"\n" + n.toString());
break;
}
s = s.substring(i + "jcasType.ll_cas.ll_get".length());
}
i = s.indexOf("Value");
if (i < 0) {
reportUnrecognizedV2Code("Found \"jcasType.ll_cas.ll_[set or get]\" but didn't find following \"Value\"\n" + n.toString());
break; // give up
}
s = Character.toUpperCase(s.charAt(0)) + s.substring(1, i);
rangeNameV2Part = s;
rangeNamePart = s.equals("Ref") ? "Feature" : s;
// get feat name following ")jcasType).casFeatCode_xxxxx,
i = bodyString.indexOf("jcasType).casFeatCode_");
if (i == -1) {
reportUnrecognizedV2Code("Didn't find \"...jcasType).casFeatCode_\"\n" + n.toString());
break;
}
Matcher m = word1.matcher(bodyString.substring(i + "jcasType).casFeatCode_".length() ));
if (!m.find()) {
reportUnrecognizedV2Code("Found \"...jcasType).casFeatCode_\" but didn't find subsequent word\n" + n.toString());
break;
}
featName = m.group(1);
String fromMethod = Character.toLowerCase(name.charAt(3)) + name.substring(4);
if (!featName.equals(fromMethod)) {
// don't report if the only difference is the first letter captialization
if (!(Character.toLowerCase(featName.charAt(0)) + featName.substring(1)).equals(fromMethod)) {
reportMismatchedFeatureName(String.format("%-25s %s", featName, name));
}
}
NodeList<Expression> args = new NodeList<>();
args.add(new StringLiteralExpr(featName));
VariableDeclarator vd = new VariableDeclarator(
intType,
"_FI_" + featName,
new MethodCallExpr(new NameExpr("TypeSystemImpl"), new SimpleName("getAdjustedFeatureOffset"), args));
if (featNames.add(featName)) { // returns true if it was added, false if already in the set of featNames
fi_fields.add(new FieldDeclaration(public_static_final, vd));
}
/**
* add missing cast stmt for
* return stmts where the value being returned:
* - doesn't have a cast already
* - has the expression be a methodCallExpr with a name which looks like:
* ll_getRefValue or
* ll_getRefArrayValue
*/
if (isGetter && "Feature".equals(rangeNamePart)) {
for (Statement stmt : n.getBody().get().getStatements()) {
if (stmt instanceof ReturnStmt) {
Expression e = getUnenclosedExpr(((ReturnStmt)stmt).getExpression().get());
if ((e instanceof MethodCallExpr)) {
String methodName = ((MethodCallExpr)e).getNameAsString();
if (refGetter.matcher(methodName).matches()) { // ll_getRefValue or ll_getRefArrayValue
addCastExpr(stmt, n.getType());
}
}
}
}
}
get_set_method = n; // used as a flag during inner "visits" to signal
// we're inside a likely feature setter/getter
} // end of test for getter or setter method
} while (false); // do once, provide break exit
super.visit(n, ignore);
get_set_method = null; // after visiting, reset the get_set_method to null
}
/**
* Visitor for if stmts
* - removes feature missing test
*/
@Override
public void visit(IfStmt n, Object ignore) {
do {
// if (get_set_method == null) break; // sometimes, these occur outside of recogn. getters/setters
Expression c = n.getCondition(), e;
BinaryExpr be, be2;
List<Statement> stmts;
if ((c instanceof BinaryExpr) &&
((be = (BinaryExpr)c).getLeft() instanceof FieldAccessExpr) &&
((FieldAccessExpr)be.getLeft()).getNameAsString().equals("featOkTst")) {
// remove the feature missing if statement
// verify the remaining form
if (! (be.getRight() instanceof BinaryExpr)
|| ! ((be2 = (BinaryExpr)be.getRight()).getRight() instanceof NullLiteralExpr)
|| ! (be2.getLeft() instanceof FieldAccessExpr)
|| ! ((e = getExpressionFromStmt(n.getThenStmt())) instanceof MethodCallExpr)
|| ! (((MethodCallExpr)e).getNameAsString()).equals("throwFeatMissing")) {
reportDeletedCheckModified("The featOkTst was modified:\n" + n.toString() + '\n');
}
BlockStmt parent = (BlockStmt) n.getParentNode().get();
stmts = parent.getStatements();
stmts.set(stmts.indexOf(n), new EmptyStmt()); //dont remove
// otherwise iterators fail
// parent.getStmts().remove(n);
return;
}
} while (false);
super.visit(n, ignore);
}
/**
* visitor for method calls
*/
@Override
public void visit(MethodCallExpr n, Object ignore) {
Optional<Node> p1, p2, p3 = null;
Node updatedNode = null;
NodeList<Expression> args;
do {
if (get_set_method == null) break;
/** remove checkArraybounds statement **/
if (n.getNameAsString().equals("checkArrayBounds") &&
((p1 = n.getParentNode()).isPresent() && p1.get() instanceof ExpressionStmt) &&
((p2 = p1.get().getParentNode()).isPresent() && p2.get() instanceof BlockStmt) &&
((p3 = p2.get().getParentNode()).isPresent() && p3.get() == get_set_method)) {
NodeList<Statement> stmts = ((BlockStmt)p2.get()).getStatements();
stmts.set(stmts.indexOf(p1.get()), new EmptyStmt());
return;
}
// convert simpleCore expression ll_get/setRangeValue
boolean useGetter = isGetter || isArraySetter;
if (n.getNameAsString().startsWith("ll_" + (useGetter ? "get" : "set") + rangeNameV2Part + "Value")) {
args = n.getArguments();
if (args.size() != (useGetter ? 2 : 3)) break;
String suffix = useGetter ? "Nc" : rangeNamePart.equals("Feature") ? "NcWj" : "Nfc";
String methodName = "_" + (useGetter ? "get" : "set") + rangeNamePart + "Value" + suffix;
args.remove(0); // remove the old addr arg
// arg 0 converted when visiting args FieldAccessExpr
n.setScope(null);
n.setName(methodName);
}
// convert array sets/gets
String z = "ll_" + (isGetter ? "get" : "set");
String nname = n.getNameAsString();
if (nname.startsWith(z) &&
nname.endsWith("ArrayValue")) {
String s = nname.substring(z.length());
s = s.substring(0, s.length() - "Value".length()); // s = "ShortArray", etc.
if (s.equals("RefArray")) s = "FSArray";
if (s.equals("IntArray")) s = "IntegerArray";
EnclosedExpr ee = new EnclosedExpr(
new CastExpr(new ClassOrInterfaceType(s), n.getArguments().get(0)));
n.setScope(ee); // the getter for the array fs
n.setName(isGetter ? "get" : "set");
n.getArguments().remove(0);
}
/** remove ll_getFSForRef **/
/** remove ll_getFSRef **/
if (n.getNameAsString().equals("ll_getFSForRef") ||
n.getNameAsString().equals("ll_getFSRef")) {
updatedNode = replaceInParent(n, n.getArguments().get(0));
}
} while (false);
if (updatedNode != null) {
updatedNode.accept(this, null);
} else {
super.visit(n, null);
}
}
/**
* visitor for field access expressions
* - convert ((...type_Type)jcasType).casFeatCode_XXXX to _FI_xxx
* @param n -
* @param ignore -
*/
@Override
public void visit(FieldAccessExpr n, Object ignore) {
Expression e;
Optional<Expression> oe;
String nname = n.getNameAsString();
if (get_set_method != null) {
if (nname.startsWith("casFeatCode_") &&
((oe = n.getScope()).isPresent()) &&
((e = getUnenclosedExpr(oe.get())) instanceof CastExpr) &&
("jcasType".equals(getName(((CastExpr)e).getExpression())))) {
String featureName = nname.substring("casFeatCode_".length());
replaceInParent(n, new NameExpr("_FI_" + featureName)); // repl last in List<Expression> (args)
return;
} else if (nname.startsWith("casFeatCode_")) {
reportMigrateFailed("Found field casFeatCode_ ... without a previous cast expr using jcasType");
}
}
super.visit(n, ignore);
}
private class removeEmptyStmts extends VoidVisitorAdapter<Object> {
@Override
public void visit(BlockStmt n, Object ignore) {
Iterator<Statement> it = n.getStatements().iterator();
while (it.hasNext()) {
if (it.next() instanceof EmptyStmt) {
it.remove();
}
}
super.visit(n, ignore);
}
// @Override
// public void visit(MethodDeclaration n, Object ignore) {
// if (n.getNameAsString().equals("getModifiablePrimitiveNodes")) {
// System.out.println("debug");
// }
// super.visit(n, ignore);
// if (n.getNameAsString().equals("getModifiablePrimitiveNodes")) {
// System.out.println("debug");
// }
// }
}
/**
* converted files:
* java name, path (sorted by java name, v3 name only)
* not-converted:
* java name, path (sorted by java name)
* duplicates:
* java name, path (sorted by java name)
* @return true if it's likely everything converted OK.
*/
private boolean report() {
System.out.println("\n\nMigration Summary");
System.out.format("Output top directory: %s%n", outputDirectory);
System.out.format("Date/time: %tc%n", new Date());
pprintRoots("Sources", sourcesRoots);
pprintRoots("Classes", classesRoots);
boolean isOk2 = true;
try {
// these reports, if non-empty items, imply something needs manual checking, so reset isOk2
isOk2 = reportPaths("Workaround Directories", "workaroundDir.txt", pathWorkaround) && isOk2;
isOk2 = reportPaths("Reports of converted files where a deleted check was customized", "deletedCheckModified.txt", deletedCheckModified) && isOk2;
isOk2 = reportPaths("Reports of converted files needing manual inspection", "manualInspection.txt", manualInspection) && isOk2;
isOk2 = reportPaths("Reports of files which failed migration", "failed.txt", failedMigration) && isOk2;
isOk2 = reportPaths("Reports of non-JCas files", "NonJCasFiles.txt", nonJCasFiles) && isOk2;
isOk2 = reportPaths("Builtin JCas classes - skipped - need manual checking to see if they are modified",
"skippedBuiltins.txt", skippedBuiltins) && isOk2;
// these reports, if non-empty, do not imply OK issues
reportPaths("Reports of updated Jars", "jarFileUpdates.txt", jarClassReplace);
reportPaths("Reports of updated PEARs", "pearFileUpdates.txt", pearClassReplace);
// computeDuplicates();
// reportPaths("Report of duplicates - not identical", "nonIdenticalDuplicates.txt", nonIdenticalDuplicates);
// reportPaths("Report of duplicates - identical", "identicalDuplicates.txt", identicalDuplicates);
// isOk2 = reportDuplicates() && isOk2; // false if non-identical duplicates
return isOk2;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void pprintRoots(String kind, Container[] roots) {
if (roots.length > 0) {
try {
try (BufferedWriter bw = Files.newBufferedWriter(makePath(outDirLog + "ItemsProcessed"), StandardOpenOption.CREATE)) {
logPrintNl(kind + " Roots:", bw);
indent[0] += 2;
try {
for (Container container : roots) {
pprintContainer(container, bw);
}
logPrintNl("", bw);
} finally {
indent[0] -= 2;
}
}
} catch (IOException e) {
throw new UIMARuntimeException(e);
}
}
}
private void pprintContainer(Container container, BufferedWriter bw) throws IOException {
logPrintNl(container.toString(), bw);
if (container.subContainers.size() > 1) {
logPrintNl("", bw);
indent[0] += 2;
for (Container subc : container.subContainers) {
pprintContainer(subc, bw);
}
}
}
// private void computeDuplicates() {
// List<ClassnameAndPath> toCheck = new ArrayList<>(c2ps);
// toCheck.addAll(extendableBuiltins);
// sortReport2(toCheck);
// ClassnameAndPath prevP = new ClassnameAndPath(null, null);
// List<ClassnameAndPath> sameList = new ArrayList<>();
// boolean areAllEqual = true;
//
// for (ClassnameAndPath p : toCheck) {
// if (!p.getFirst().equals(prevP.getFirst())) {
//
// addToIdenticals(sameList, areAllEqual);
// sameList.clear();
// areAllEqual = true;
//
// prevP = p;
// continue;
// }
//
// // have 2nd or subsequent same class
// if (sameList.size() == 0) {
// sameList.add(prevP);
// }
// sameList.add(p);
// if (areAllEqual) {
// if (isFilesMiscompare(p.path, prevP.path)) {
// areAllEqual = false;
// }
// }
// }
//
// addToIdenticals(sameList, areAllEqual);
// }
// /**
// * Compare two java source or class files
// * @param p1
// * @param p2
// * @return
// */
// private boolean isFilesMiscompare(Path p1, Path p2) {
// String s1 = (p1);
// String s2 = (p2);
// return !s1.equals(s2);
// }
// private void addToIdenticals(List<ClassnameAndPath> sameList, boolean areAllEqual) {
// if (sameList.size() > 0) {
// if (areAllEqual) {
// identicalDuplicates.addAll(sameList);
// } else {
// nonIdenticalDuplicates.addAll(sameList);
// }
// }
// }
/**
*
* @param name
* @return a path made from name, with directories created
* @throws IOException
*/
private Path makePath(String name) throws IOException {
Path p = Paths.get(name);
Path parent = p.getParent(); // all the parts of the path up to the final segment
if (parent == null) {
return p;
}
try {
Files.createDirectories(parent);
} catch (FileAlreadyExistsException e) { // parent already exists but is not a directory!
// caused by running on Windows system which ignores "case"
// there's a file at /x/y/ named "z", but the path wants to be /x/y/Z/
// Workaround: change "z" to "z_c" c for capitalization issue
current_container.haveDifferentCapitalizedNamesCollidingOnWindows = true;
Path fn = parent.getFileName();
if (fn == null) {
throw new IllegalArgumentException();
}
String newDir = fn.toString() + "_c";
Path parent2 = parent.getParent();
Path p2 = parent2 == null ? Paths.get(newDir) : Paths.get(parent2.toString(), newDir);
try {
Files.createDirectories(p2);
} catch (FileAlreadyExistsException e2) { // parent already exists but is not a directory!
throw new RuntimeException(e2);
}
reportPathWorkaround(parent.toString(), p2.toString());
Path lastPartOfPath = p.getFileName();
if (null == lastPartOfPath) throw new RuntimeException();
return Paths.get(p2.toString(), lastPartOfPath.toString());
}
return p;
}
private void logPrint(String msg, Writer bw) throws IOException {
System.out.print(msg);
bw.write(msg);
}
private void logPrintNl(String msg, Writer bw) throws IOException {
logPrint(msg, bw);
logPrint(Misc.ls, bw);
}
/**
* prints "There were no xxx" if there are no items.
* prints a title, followed by a ================== underneath it
*
* prints a sorted report of two fields.
*
* @param title title of report
* @param fileName file name to save the report in (as well as print to sysout
* @param items the set of items to report on-
* @return true if items were empty
* @throws IOException -
*/
private <T, U> boolean reportPaths(String title, String fileName, List<? extends Report2<T, U>> items) throws IOException {
if (items.size() == 0) {
System.out.println("There were no " + title);
return true;
}
System.out.println("\n" + title);
for (int i = 0; i < title.length(); i++) System.out.print('=');
System.out.println("");
try (BufferedWriter bw = Files.newBufferedWriter(makePath(outDirLog + fileName), StandardOpenOption.CREATE)) {
List<Report2<T, U>> sorted = new ArrayList<>(items);
sortReport2(sorted);
int max = 0;
int nbrFirsts = 0;
Object prevFirst = null;
for (Report2<T, U> p : sorted) {
max = Math.max(max, p.getFirstLength());
Comparable<T> first = p.getFirst();
if (first != prevFirst) {
prevFirst = first;
nbrFirsts ++;
}
}
/**
* Two styles.
* Style 1: where nbrFirst <= 25% nbr: first on separate line, seconds indented
* Style 2: firsts and seconds on same line.
*/
int i = 1;
boolean style1 = nbrFirsts <= sorted.size() / 4;
prevFirst = null;
for (Report2<T, U> p : sorted) {
if (style1) {
if (prevFirst != p.getFirst()) {
prevFirst = p.getFirst();
logPrintNl(String.format("\n For: %s", p.getFirst()), bw);
}
logPrintNl(String.format(" %5d %s", Integer.valueOf(i), p.getSecond()), bw);
} else {
logPrintNl(String.format("%5d %-" +max+ "s %s", Integer.valueOf(i), p.getFirst(), p.getSecond()), bw);
}
i++;
}
System.out.println("");
} // end of try-with-resources
return false;
}
private boolean isZipFs(Object o) {
// Surprise! sometimes the o is not an instance of FileSystem but is the zipfs anyways
return o.getClass().getName().contains("zipfs"); // java 8 and 9
}
/**
* Sort the items on first, then second
* @param items
*/
private <T, U> void sortReport2(List<? extends Report2<T, U>> items) {
Collections.sort(items,
(o1, o2) -> {
int r = protectedCompare(o1.getFirst(), o2.getFirst());
if (r == 0) {
r = protectedCompare(o1.getSecond(), o2.getSecond());
}
return r;
});
}
/**
* protect against comparing zip fs with non-zip fs - these are not comparable to each other in IBM Java 8
* @return -
*/
private <T> int protectedCompare(Comparable<T> comparable, Comparable<T> comparable2) {
//debug
try {
if (isZipFs(comparable)) {
if (isZipFs(comparable2)) {
return comparable.compareTo((T) comparable2); // both zip
} else {
return 1;
}
} else {
if (isZipFs(comparable2)) {
return -1;
} else {
return comparable.compareTo((T) comparable2); // both not zip
}
}
} catch (ClassCastException e) {
//debug
System.out.format("Internal error: c1: %b c2: %b%n c1: %s%n c2: %s%n", isZipFs(comparable), isZipFs(comparable2), comparable.getClass().getName(), comparable2.getClass().getName());
throw e;
}
}
/**
* Called only for top level roots. Sub containers recurse getCandidates_processFile2.
*
* Walk the directory tree rooted at root
* - descend subdirectories
* - descend Jar file
* -- descend nested Jar files (!)
* by extracting these to a temp dir, and keeping a back reference to where they were extracted from.
*
* output the paths representing the classes to migrate:
* classes having a _Type partner
* excluding things other than .java or .classes, and excluding anything with "$" in the name
* - the path includes the "file system".
* @param root
* @throws IOException
*/
private void getAndProcessCandidatesInContainer(Container container) {
// current_paths2RootIds = top_paths2RootIds; // don't do lower, that's called within Jars etc.
try (Stream<Path> stream = Files.walk(container.root, FileVisitOption.FOLLOW_LINKS)) { // needed to release file handles
stream.forEachOrdered(
// only puts into the RootIds possible Fqcn (ending in either .class or .java)
p -> getCandidates_processFile2(p, container));
} catch (IOException e) {
throw new RuntimeException(e);
}
// walk from root container, remove items not JCas candidates
// prunes empty rootIds and subContainer nodes
removeNonJCas(container);
if (container.candidates.size() == 0) { // above call might remove all candidates
Container parent = container.parent;
if (parent != null) {
// System.out.println("No Candidates found in scanned container ending in " +
// container.rootOrig.getFileName().toString());
// // debug
// System.out.println("debug: " + container.rootOrig.toString());
parent.subContainers.remove(container);
}
return;
}
si(psb).append("Migrating JCas files ");
psb.append( container.isJar
? "in Jar: "
: container.isPear
? "in Pear: "
: "from root: ");
psb.append(container.rootOrig);
indent[0] += 2;
si(psb);
flush(psb);
try {
for (Path path : container.candidates) {
CommonConverted cc = getSource(path, container);
// migrate checks to see if already done, outputs a "." or some other char for the candidate
migrate(cc, container, path);
//defer any compilation to container level
if ((itemCount % 50) == 0) {
psb.append(" ").append(itemCount);
si(psb);
flush(psb);
}
itemCount++;
}
psb.append(" ").append(itemCount - 1);
flush(psb);
if (isSource) {
return; // done
}
if (!isSource &&
!container.haveDifferentCapitalizedNamesCollidingOnWindows &&
javaCompiler != null) {
boolean somethingCompiled = compileV3SourcesCommon2(container);
if (container.isPear || container.isJar) {
if (somethingCompiled) {
postProcessPearOrJar(container);
}
}
return;
}
unableToCompile = true;
return; // unable to do post processing or compiling
} finally {
indent[0] -= 2;
}
}
// removes from rootId-lists nonJCas candidates
// if non left, removes that root-id from the root-id lists
// recursion on subContainers.
// for each subContainer, if it ends up empty (no rootIds, no subContainers) removes it
private void removeNonJCas(Container container) {
Iterator<Path> it = container.candidates.iterator();
while (it.hasNext()) {
String candidate = it.next().toString();
// remove non JCas classes
// //debug
// System.out.println("debug, testing to remove: " + candidate);
// if (candidate.indexOf("Corrected") >= 0) {
// if (!container._Types.contains(candidate)) {
// System.out.println("debug dumping _Types map keys to see why ... Corrected.class not there");
// System.out.println("debug key is=" + candidate);
// System.out.println("keys are:");
// int i = 0;
// for (String k : container._Types) {
// if (i == 4) {
// i = 0;
// System.out.println("");
// }
// System.out.print(k + ", ");
// }
// } else {
// System.out.println("debug container._Types did contain " + candidate);
// }
// }
if (!container._Types.contains(candidate)) {
it.remove();
}
}
}
/**
* Called from Stream walker starting at a root or starting at an imbedded Jar or Pear.
*
* adds all the .java or .class files to the candidates, including _Type if not skipping the _Type check
*
* Handling embedded jar files
* - single level Jar (at the top level of the default file system)
* -- handle using an overlayed file system
* - embedded Jars within Jars:
* - not supported by Zip File System Provider (it only supports one level)
* - handle by extracting to a temp dir, and then using the Zip File System Provider
*
* For PEARs, check for and disallow nested PEARs; install the PEAR, set the pear classpath for
* recursive processing with the Pear.
*
* For Jar and PEAR files, use local variable + recursive call to update current_paths2RootIds map
* to new one for the Jar / Pear, and then process recursiveloy
*
* @param path the path to a .java or .class or .jar or .pear that was walked to
* @param pearClasspath - a string representing a path to the pear's classpath if there is one, or null
* @param container the container for the
* - rootIds (which have the JCas candidates) and
* - subContainers for imbedded Pears and Jars
*/
private void getCandidates_processFile2(Path path, Container container) {
String pathString = path.toString();
final boolean isPear = pathString.endsWith(".pear"); // path.endsWith does not mean this !!
final boolean isJar = pathString.endsWith(".jar");
if (isPear || isJar) {
Container subc = new Container(container, path);
getAndProcessCandidatesInContainer(subc);
return;
}
if (pathString.endsWith(isSource ? ".java" : ".class")) {
// Skip candidates except .java or .class
addToCandidates(path, container);
}
}
/**
* if _Type kind, add artifactId to set kept in current rootIdContainer
* If currently scanning within a PEAR,
* record 2-way map from unzipped path to internal path inside pear
* Used when doing pear reassembly.
*
* If currently scanning within a Jar or a PEAR,
* add unzipped path to list of all subparts for containing Jar or PEAR
* These paths are used as unique ids to things needing to be replaced in the Jar or PEAR,
* when doing re-assembly. For compiled classes migration, only, since source migration
* doesn't do re-assembly.
*
* @param path
* @param pearClassPath
*/
private void addToCandidates(Path path, Container container) {
String ps = path.toString();
if (ps.endsWith(isSource ? "_Type.java" : "_Type.class")) {
container._Types.add(isSource
? (ps.substring(0, ps.length() - 10) + ".java")
: (ps.substring(0, ps.length() - 11) + ".class"));
// if (container.isJar) {
// System.out.println("debug add container._Types " + Paths.get(ps.substring(0, ps.length() - 11)).toString() + ".class".toString() + " for Jar " + container.rootOrig.getFileName().toString());
// }
return;
}
if (ps.contains("$")) {
return; // don't add these kinds of things, they're not JCas classes
}
//debug
// if (container.isJar) {
// System.out.println("debug add candidate " + path.toString() + " for Jar " + container.rootOrig.getFileName().toString());
// }
container.candidates.add(path);
}
/**
* For Jars inside other Jars, we copy the Jar to a temp spot in the default file system
* Extracted Jar is marked delete-on-exit
*
* @param path embedded Jar to copy (only the last name is used, in constructing the temp dir)
* @return a temporary file in the local temp directory that is a copy of the Jar
* @throws IOException -
*/
private static Path getTempOutputPathForJar(Path path) throws IOException {
Path localTempDir = getTempDir();
if (path == null ) {
throw new IllegalArgumentException();
}
Path fn = path.getFileName();
if (fn == null) {
throw new IllegalArgumentException();
}
Path tempPath = Files.createTempFile(localTempDir, fn.toString(), "");
tempPath.toFile().deleteOnExit();
return tempPath;
}
private static Path getTempDir() throws IOException {
if (tempDir == null) {
tempDir = Files.createTempDirectory("migrateJCas");
tempDir.toFile().deleteOnExit();
}
return tempDir;
}
private static final CommandLineParser createCmdLineParser() {
CommandLineParser parser = new CommandLineParser();
parser.addParameter(SOURCE_FILE_ROOTS, true);
parser.addParameter(CLASS_FILE_ROOTS, true);
parser.addParameter(OUTPUT_DIRECTORY, true);
// parser.addParameter(SKIP_TYPE_CHECK, false);
parser.addParameter(MIGRATE_CLASSPATH, true);
// parser.addParameter(CLASSES, true);
return parser;
}
private final boolean checkCmdLineSyntax(CommandLineParser clp) {
if (clp.getRestArgs().length > 0) {
System.err.println("Error parsing CVD command line: unknown argument(s):");
String[] args = clp.getRestArgs();
for (int i = 0; i < args.length; i++) {
System.err.print(" ");
System.err.print(args[i]);
}
System.err.println();
return false;
}
if (clp.isInArgsList(SOURCE_FILE_ROOTS) && clp.isInArgsList(CLASS_FILE_ROOTS)) {
System.err.println("both sources file roots and classess file roots parameters specified; please specify just one.");
return false;
}
if (clp.isInArgsList(OUTPUT_DIRECTORY)) {
outputDirectory = Paths.get(clp.getParamArgument(OUTPUT_DIRECTORY)).toString();
if (!outputDirectory.endsWith("/")) {
outputDirectory = outputDirectory + "/";
}
} else {
try {
outputDirectory = Files.createTempDirectory("migrateJCasOutput").toString() + "/";
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
outDirConverted = outputDirectory + "converted/";
outDirSkipped = outputDirectory + "not-converted/";
outDirLog = outputDirectory + "logs/";
if (clp.isInArgsList(MIGRATE_CLASSPATH)) {
migrateClasspath = clp.getParamArgument(MIGRATE_CLASSPATH);
} else {
if (clp.isInArgsList(CLASS_FILE_ROOTS)) {
System.err.println("WARNING: classes file roots is specified, but the\n"
+ " migrateClasspath parameter is missing\n");
}
}
// if (clp.isInArgsList(CLASSES)) {
// individualClasses = clp.getParamArgument(CLASSES);
// }
return true;
}
// called to decompile a string of bytes.
// - first get the class name (fully qualified)
// and skip decompiling if already decompiled this class
// for this pearClasspath
// - this handles multiple class definitions, insuring
// only one decompile happens per pearClasspath (including null)
/**
* Caller does any caching to avoid this method.
*
* @param b bytecode to decompile
* @param pearClasspath to prepend to the classpath
* @return
*/
private String decompile(byte[] b, String pearClasspath) {
badClassName = false;
String classNameWithSlashes = Misc.classNameFromByteCode(b);
packageAndClassNameSlash = classNameWithSlashes;
ClassLoader cl = getClassLoader(pearClasspath);
UimaDecompiler ud = new UimaDecompiler(cl, null);
if (classNameWithSlashes == null || classNameWithSlashes.length() < 2) {
System.err.println("Failed to extract class name from binary code, "
+ "name found was \"" + ((classNameWithSlashes == null) ? "null" : classNameWithSlashes)
+ "\"\n byte array was:");
System.err.println(Misc.dumpByteArray(b, 2000));
badClassName = true;
}
return ud.decompileToString(classNameWithSlashes, b);
}
/**
* The classloader to use in decompiling, if it is provided, is one that delegates first
* to the parent. This may need fixing for PEARs
* @return classloader to use for migrate decompiling
*/
private ClassLoader getClassLoader(String pearClasspath) {
if (null == pearClasspath) {
if (null == cachedMigrateClassLoader) {
cachedMigrateClassLoader = (null == migrateClasspath)
? this.getClass().getClassLoader()
: new UIMAClassLoader(Misc.classpath2urls(migrateClasspath));
}
return cachedMigrateClassLoader;
} else {
try {
return new UIMAClassLoader((null == migrateClasspath)
? pearClasspath
: (pearClasspath + File.pathSeparator + migrateClasspath));
} catch (MalformedURLException e) {
throw new UIMARuntimeException(e);
}
}
}
private void addImport(String s) {
cu.getImports().add(new ImportDeclaration(new Name(s), false, false));
}
private void removeImport(String s) {
Iterator<ImportDeclaration> it = cu.getImports().iterator();
while (it.hasNext()) {
ImportDeclaration impDcl = it.next();
if (impDcl.getNameAsString().equals(s)) {
it.remove();
break;
}
}
}
/******************
* AST Utilities
******************/
private Node replaceInParent(Node n, Expression v) {
Optional<Node> maybeParent = n.getParentNode();
if (maybeParent.isPresent()) {
Node parent = n.getParentNode().get();
if (parent instanceof EnclosedExpr) {
((EnclosedExpr)parent).setInner(v);
} else if (parent instanceof MethodCallExpr) { // args in the arg list
List<Expression> args = ((MethodCallExpr)parent).getArguments();
args.set(args.indexOf(n), v);
v.setParentNode(parent);
} else if (parent instanceof ExpressionStmt) {
((ExpressionStmt)parent).setExpression(v);
} else if (parent instanceof CastExpr) {
((CastExpr)parent).setExpression(v);
} else if (parent instanceof ReturnStmt) {
((ReturnStmt)parent).setExpression(v);
} else if (parent instanceof AssignExpr) {
((AssignExpr)parent).setValue(v);
} else if (parent instanceof VariableDeclarator) {
((VariableDeclarator)parent).setInitializer(v);
} else if (parent instanceof ObjectCreationExpr) {
List<Expression> args = ((ObjectCreationExpr)parent).getArguments();
int i = args.indexOf(n);
if (i < 0) throw new RuntimeException();
args.set(i, v);
} else {
System.out.println(parent.getClass().getName());
throw new RuntimeException();
}
return v;
}
System.out.println("internal error replacing in parent: no parent for node: " + n.getClass().getName());
System.out.println(" node: " + n.toString());
System.out.println(" expression replacing: " + v.toString());
throw new RuntimeException();
}
/**
*
* @param p the parameter to modify
* @param t the name of class or interface
* @param name the name of the variable
*/
private void setParameter(List<Parameter> ps, int i, String t, String name) {
Parameter p = ps.get(i);
p.setType(new ClassOrInterfaceType(t));
p.setName(new SimpleName(name));
}
private int findConstructor(NodeList<BodyDeclaration<?>> classMembers) {
int i = 0;
for (BodyDeclaration<?> bd : classMembers) {
if (bd instanceof ConstructorDeclaration) {
return i;
}
i++;
}
return -1;
}
private boolean hasTypeFields(NodeList<BodyDeclaration<?>> members) {
boolean hasType = false;
boolean hasTypeId = false;
for (BodyDeclaration<?> bd : members) {
if (bd instanceof FieldDeclaration) {
FieldDeclaration f = (FieldDeclaration)bd;
EnumSet<Modifier> m = f.getModifiers();
if (m.contains(Modifier.PUBLIC) &&
m.contains(Modifier.STATIC) &&
m.contains(Modifier.FINAL)
// &&
// getTypeName(f.getType()).equals("int")
) {
List<VariableDeclarator> vds = f.getVariables();
for (VariableDeclarator vd : vds) {
if (vd.getType().equals(intType)) {
String n = vd.getNameAsString();
if (n.equals("type")) hasType = true;
if (n.equals("typeIndexID")) hasTypeId = true;
if (hasTypeId && hasType) {
return true;
}
}
}
}
}
} // end of for
return false;
}
/**
* Heuristic:
* JCas classes have 0, 1, and 2 arg constructors with particular arg types
* 0 -
* 1 - JCas
* 2 - int, TOP_Type (v2) or TypeImpl, CASImpl (v3)
*
* Additional 1 and 2 arg constructors are permitted.
*
* Sets fields hasV2Constructors, hasV3Constructors
* @param members
*/
private void setHasJCasConstructors(NodeList<BodyDeclaration<?>> members) {
boolean has0ArgConstructor = false;
boolean has1ArgJCasConstructor = false;
boolean has2ArgJCasConstructorV2 = false;
boolean has2ArgJCasConstructorV3 = false;
for (BodyDeclaration<?> bd : members) {
if (bd instanceof ConstructorDeclaration) {
List<Parameter> ps = ((ConstructorDeclaration)bd).getParameters();
if (ps.size() == 0) has0ArgConstructor = true;
if (ps.size() == 1 && getParmTypeName(ps, 0).equals("JCas")) {
has1ArgJCasConstructor = true;
}
if (ps.size() == 2) {
if (getParmTypeName(ps, 0).equals("int") &&
getParmTypeName(ps, 1).equals("TOP_Type")) {
has2ArgJCasConstructorV2 = true;
} else if (getParmTypeName(ps, 0).equals("TypeImpl") &&
getParmTypeName(ps, 1).equals("CASImpl")) {
has2ArgJCasConstructorV3 = true;
}
} // end of 2 arg constructor
} // end of is-constructor
} // end of for loop
hasV2Constructors = has0ArgConstructor && has1ArgJCasConstructor && has2ArgJCasConstructorV2;
hasV3Constructors = has0ArgConstructor && has1ArgJCasConstructor && has2ArgJCasConstructorV3;
}
private String getParmTypeName(List<Parameter> p, int i) {
return getTypeName(p.get(i).getType());
}
private String getTypeName(Type t) {
// if (t instanceof ReferenceType) {
// t = ((ReferenceType<?>)t).getType();
// }
if (t instanceof PrimitiveType) {
return ((PrimitiveType)t).toString();
}
if (t instanceof ClassOrInterfaceType) {
return ((ClassOrInterfaceType)t).getNameAsString();
}
Misc.internalError(); return null;
}
/**
* Get the name of a field
* @param e -
* @return the field name or null
*/
private String getName(Expression e) {
e = getUnenclosedExpr(e);
if (e instanceof NameExpr) {
return ((NameExpr)e).getNameAsString();
}
if (e instanceof FieldAccessExpr) {
return ((FieldAccessExpr)e).getNameAsString();
}
return null;
}
/**
* Called on Annotation Decl, Class/intfc decl, empty type decl, enum decl
* Does nothing unless at top level of compilation unit
*
* Otherwise, adds an entry to c2ps for the classname and package, plus full path
*
* @param n type being declared
*/
private void updateClassName(TypeDeclaration<?> n) {
Optional<Node> pnode = n.getParentNode();
Node node;
if (pnode.isPresent() &&
(node = pnode.get()) instanceof CompilationUnit) {
CompilationUnit cu2 = (CompilationUnit) node;
className = cu2.getType(0).getNameAsString();
String packageAndClassName =
(className.contains("."))
? className
: packageName + '.' + className;
packageAndClassNameSlash = packageAndClassName.replace('.', '/');
// assert current_cc.fqcn_slash == null; // for decompiling, already set
assert (current_cc.fqcn_slash != null) ? current_cc.fqcn_slash.equals(packageAndClassNameSlash) : true;
current_cc.fqcn_slash = packageAndClassNameSlash;
TypeImpl ti = TypeSystemImpl.staticTsi.getType(Misc.javaClassName2UimaTypeName(packageAndClassName));
if (null != ti) {
// // is a built-in type
// ClassnameAndPath p = new ClassnameAndPath(
// packageAndClassNameSlash,
// current_cc.,
// current_cc.pearClasspath);
skippedBuiltins.add(new PathAndReason(current_path, "built-in"));
isBuiltinJCas = true;
isConvert2v3 = false;
return;
}
return;
}
return;
}
private Expression getExpressionFromStmt(Statement stmt) {
stmt = getStmtFromStmt(stmt);
if (stmt instanceof ExpressionStmt) {
return getUnenclosedExpr(((ExpressionStmt)stmt).getExpression());
}
return null;
}
private Expression getUnenclosedExpr(Expression e) {
while (e instanceof EnclosedExpr) {
e = ((EnclosedExpr)e).getInner().get();
}
return e;
}
/**
* Unwrap (possibly nested) 1 statement blocks
* @param stmt -
* @return unwrapped (non- block) statement
*/
private Statement getStmtFromStmt(Statement stmt) {
while (stmt instanceof BlockStmt) {
NodeList<Statement> stmts = ((BlockStmt) stmt).getStatements();
if (stmts.size() == 1) {
stmt = stmts.get(0);
continue;
}
return null;
}
return stmt;
}
private void addCastExpr(Statement stmt, Type castType) {
ReturnStmt rstmt = (ReturnStmt) stmt;
Optional<Expression> o_expr = rstmt.getExpression();
Expression expr = o_expr.isPresent() ? o_expr.get() : null;
CastExpr ce = new CastExpr(castType, expr);
rstmt.setExpression(ce); // removes the parent link from expr
if (expr != null) {
expr.setParentNode(ce); // restore it
}
}
/********************
* Recording results
********************/
private void recordBadConstructor(String msg) {
reportMigrateFailed("Constructor is incorrect, " + msg);
}
// private void reportParseException() {
// reportMigrateFailed("Unparsable Java");
// }
private void migrationFailed(String reason) {
failedMigration.add(new PathAndReason(current_path, reason));
isConvert2v3 = false;
}
private void reportMigrateFailed(String m) {
System.out.format("Skipping this file due to error: %s, path: %s%n", m, current_path);
migrationFailed(m);
}
private void reportV2Class() {
// v2JCasFiles.add(current_path);
isV2JCas = true;
}
private void reportV3Class() {
// v3JCasFiles.add(current_path);
isConvert2v3 = true;
}
private void reportNotJCasClass(String reason) {
nonJCasFiles.add(new PathAndReason(current_path, reason));
isConvert2v3 = false;
}
private void reportNotJCasClassMissingTypeFields() {
reportNotJCasClass("missing required type and/or typeIndexID static fields");
}
private void reportDeletedCheckModified(String m) {
deletedCheckModified.add(new PathAndReason(current_path, m));
}
private void reportMismatchedFeatureName(String m) {
manualInspection.add(new PathAndReason(current_path, "This getter/setter name doesn't match internal feature name: " + m));
}
private void reportUnrecognizedV2Code(String m) {
migrationFailed("V2 code not recognized:\n" + m);
}
private void reportPathWorkaround(String orig, String modified) {
pathWorkaround.add(new String1AndString2(orig, modified));
}
private void reportPearOrJarClassReplace(String pearOrJar, String classname, Container kind) { // pears or jars
if (kind.isPear) {
pearClassReplace.add(new String1AndString2(pearOrJar, classname));
} else {
jarClassReplace.add(new String1AndString2(pearOrJar, classname));
}
}
/***********************************************/
/**
* Output directory for source and migrated files
* Consisting of converted/skipped, v2/v3, a+cc.id, slashified classname
* @param cc -
* @param isV2 -
* @param wasConverted -
* @return converted/skipped, v2/v3, a+cc.id, slashified classname
*/
private String getBaseOutputPath(CommonConverted cc, boolean isV2, boolean wasConverted) {
StringBuilder sb = new StringBuilder();
sb.append(wasConverted ? outDirConverted : outDirSkipped);
sb.append(isV2 ? "v2/" : "v3/");
sb.append("a").append(cc.getId()).append('/');
sb.append(cc.fqcn_slash).append(".java");
return sb.toString();
}
private void writeV2Orig(CommonConverted cc, boolean wasConverted) throws IOException {
String base = getBaseOutputPath(cc, true, wasConverted); // adds numeric suffix if dupls
FileUtils.writeToFile(makePath(base), cc.v2Source);
}
private void writeV3(CommonConverted cc) throws IOException {
String base = getBaseOutputPath(cc, false, true);
cc.v3SourcePath = makePath(base);
String data = fixImplementsBug(cc.v3Source);
FileUtils.writeToFile(cc.v3SourcePath, data);
}
private void printUsage() {
System.out.println(
"Usage: java org.apache.uima.migratev3.jcas.MigrateJCas \n"
+ " [-sourcesRoots <One-or-more-directories-or-jars-separated-by-Path-separator>]\n"
+ " [-classesRoots <One-or-more-directories-or-jars-or-pears-separated-by-Path-separator>]\n"
+ " [-outputDirectory a-writable-directory-path (optional)\n"
+ " if omitted, a temporary directory is used\n"
+ " [-migrateClasspath a-class-path to use in decompiling, when -classesRoots is specified\n"
+ " also used when compiling the migrated classes.\n"
+ " NOTE: either -sourcesRoots or -classesRoots is required, but only one may be specified.\n"
+ " NOTE: classesRoots are scanned for JCas classes, which are then decompiled, and the results processed like sourcesRoots\n"
);
}
private static final Pattern implementsEmpty = Pattern.compile("implements \\{");
private String fixImplementsBug(String data) {
return implementsEmpty.matcher(data).replaceAll("{");
}
/*********************************************************************
* Reporting classes
*********************************************************************/
private static abstract class Report2<T, U> {
public abstract Comparable<T> getFirst(); // Eclipse on linux complained if not public, was OK on windows
public abstract Comparable<U> getSecond();
abstract int getFirstLength();
}
private static class PathAndReason extends Report2<Path, String> {
Path path;
String reason;
PathAndReason(Path path, String reason) {
this.path = path;
this.reason = reason;
}
@Override
public Comparable<Path> getFirst() { return path; }
@Override
public Comparable<String> getSecond() { return reason; }
@Override
int getFirstLength() { return path.toString().length(); }
}
private static class String1AndString2 extends Report2<String, String> {
String s1;
String s2;
String1AndString2(String s1, String s2) {
this.s1 = s1;
this.s2 = s2;
}
@Override
public Comparable<String> getFirst() { return s1; }
@Override
public Comparable<String> getSecond() { return s2; }
@Override
int getFirstLength() { return s1.toString().length(); }
}
private static void withIOX(Runnable_withException r) {
try {
r.run();
} catch (Exception e) {
throw new UIMARuntimeException(e);
}
}
private int findFirstCharDifferent(String s1, String s2) {
int s1l = s1.length();
int s2l = s2.length();
for (int i = 0;;i++) {
if (i == s1l || i == s2l) {
return i;
}
if (s1.charAt(i) != s2.charAt(i)) {
return i;
}
}
}
// private String drop_Type(String s) {
// return s.substring(0, isSource ? "_Type.java".length()
// : "_Type.class".length()) +
// (isSource ? ".java" : ".class");
// }
///*****************
//* Root-id
//*****************/
//private static int nextRootId = 1;
//
///***********************************************************************
//* Root-id - this is the path part up to the start of the package name.
//* - it is relative to container
//* - has the collection of artifacts that might be candidates, having this rootId
//* - has the collection of _Type things having this rootId
//* - "null" path is OK - means package name starts immediately
//* There is no Root-id for path ending in Jar or PEAR - these created containers instead
//***********************************************************************/
//private static class RootId {
// final int id = nextRootId++;
// /**
// * The path relative to the the container (if any) (= Jar or Pear)
// * - for Pears, the path is as if it was not installed, but within the PEAR file
// */
// final Path path;
//
// /** The container holding this RootId */
// final Container container;
// /**
// * For this rootId, all of the fully qualified classnames that are migration eligible.
// * - not all might be migrated, if upon further inspection they are not JCas class files.
// */
// final Set<Fqcn> fqcns = new HashSet<>();
// final Set<String> fqcns_ignore_case = new HashSet<>();
// boolean haveDifferentCapitalizedNamesCollidingOnWindows = false;
//
// RootId(Path path, Container container) {
// this.path = path;
// this.container = container;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return "RootId [id="
// + id
// + ", path="
// + path
// + ", container="
// + container.id
// + ", fqcns="
// + Misc.ppList(Misc.setAsList(fqcns))
// + ", fqcns_Type="
// + Misc.ppList(Misc.setAsList(fqcns_Type))
// + "]";
// }
//
// void add(Fqcn fqcn) {
// boolean wasNotPresent = fqcns.add(fqcn);
// boolean lc = fqcns_ignore_case.add(fqcn.fqcn_dots.toLowerCase());
// if (!lc && wasNotPresent) {
// haveDifferentCapitalizedNamesCollidingOnWindows = true;
// }
// }
//
// boolean hasMatching_Type(Fqcn fqcn) {
//
// }
//}
///**
//* Called from Stream walker starting at a root or starting at an imbedded Jar or Pear.
//*
//* adds all the .java or .class files to the candidates, including _Type if not skipping the _Type check
//* Handling embedded jar files
//* - single level Jar (at the top level of the default file system)
//* -- handle using an overlayed file system
//* - embedded Jars within Jars:
//* - not supported by Zip File System Provider (it only supports one level)
//* - handle by extracting to a temp dir, and then using the Zip File System Provider
//* @param path the path to a .java or .class or .jar or .pear
//* @param pearClasspath - a string representing a path to the pear's classpath if there is one, or null
//*/
//private void getCandidates_processFile(Path path, String pearClasspath) {
//// if (path.toString().contains("commons-httpclient-3.1.jar"))
//// System.out.println("Debug: " + path.toString());
//// System.out.println("debug processing " + path);
// try {
//// URI pathUri = path.toUri();
// String pathString = path.toString();
// final boolean isPear = pathString.endsWith(".pear"); // path.endsWith does not mean this !!
// final boolean isJar = pathString.endsWith(".jar");
//
// if (isJar || isPear) {
// if (!path.getFileSystem().equals(FileSystems.getDefault())) {
// // embedded Pear or Jar: extract to temp
// Path out = getTempOutputPathForJar(path);
// Files.copy(path, out, StandardCopyOption.REPLACE_EXISTING);
//// embeddedJars.add(new PathAndPath(path, out));
// path = out; // path points to pear or jar
// }
//
// Path start;
// final String localPearClasspath;
// if (isPear) {
// if (pearClasspath != null) {
// throw new UIMARuntimeException("Nested PEAR files not supported");
// }
//
//// pear_current = new PearOrJar(path);
//// pears.add(pear_current);
// // add pear classpath info
// File pearInstallDir = Files.createTempDirectory(getTempDir(), "installedPear").toFile();
// PackageBrowser ip = PackageInstaller.installPackage(pearInstallDir, path.toFile(), false);
// localPearClasspath = ip.buildComponentClassPath();
// String[] children = pearInstallDir.list();
// if (children == null || children.length != 1) {
// Misc.internalError();
// }
// pearResolveStart = Paths.get(pearInstallDir.getAbsolutePath(), children[0]);
//
// start = pearInstallDir.toPath();
// } else {
// if (isJar) {
// PearOrJar jarInfo = new PearOrJar(path);
// pear_or_jar_current_stack.push(jarInfo);
// jars.add(jarInfo);
// }
//
// localPearClasspath = pearClasspath;
// FileSystem jfs = FileSystems.newFileSystem(Paths.get(path.toUri()), null);
// start = jfs.getPath("/");
// }
//
// try (Stream<Path> stream = Files.walk(start)) { // needed to release file handles
// stream.forEachOrdered(
// p -> getCandidates_processFile(p, localPearClasspath));
// }
// if (isJar) {
// pear_or_jar_current_stack.pop();
// }
// if (isPear) {
// pear_current = null;
// }
// } else {
// // is not a .jar or .pear file. add .java or .class files to initial candidate set
// // will be filtered additionally later
//// System.out.println("debug path ends with java or class " + pathString.endsWith(isSource ? ".java" : ".class") + " " + pathString);
// if (pathString.endsWith(isSource ? ".java" : ".class")) {
// candidates.add(new Candidate(path, pearClasspath));
// if (!isSource && null != pear_current) {
// // inside a pear, which has been unzipped into pearInstallDir;
// path2InsidePearOrJarPath.put(path.toString(), pearResolveStart.relativize(path).toString());
// pear_current.pathsToCandidateFiles.add(path.toString());
// }
//
// if (!isSource && pear_or_jar_current_stack.size() > 0) {
// // inside a jar, not contained in a pear
// pear_or_jar_current_stack.getFirst().pathsToCandidateFiles.add(path.toString());
// }
// }
// }
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//}
//private void postProcessPearsOrJars(String kind, List<PearOrJar> pearsOrJars, List<String1AndString2> classReplace) { // pears or jars
//try {
// Path outDir = Paths.get(outputDirectory, kind);
// FileUtils.deleteRecursive(outDir.toFile());
// Files.createDirectories(outDir);
//} catch (IOException e) {
// throw new RuntimeException(e);
//}
//
//// pearsOrJars may have entries with 0 candidate paths. This happens when we scan them
//// but find nothing to convert.
//// eliminate these.
//
//Iterator<PearOrJar> it = pearsOrJars.iterator();
//while (it.hasNext()) {
// PearOrJar poj = it.next();
// if (poj.pathsToCandidateFiles.size() == 0) {
// it.remove();
// } else {
//// //debug
//// if (poj.pathToPearOrJar.toString().contains("commons-httpclient-3.1")) {
//// System.err.println("debug found converted things inside commons-httpclient");;
//// for (String x : poj.pathsToCandidateFiles) {
//// System.err.println(x);
//// }
//// System.err.println("");
//// }
// }
//}
//
//it = pearsOrJars.iterator();
//while (it.hasNext()) {
// PearOrJar poj = it.next();
// if (poj.pathsToCandidateFiles.size() == 0) {
// System.err.print("debug failed to remove unconverted Jar");
// }
//}
//
//if (pearsOrJars.size() == 0) {
// System.out.format("No .class files were replaced in %s.%n", kind);
//} else {
// System.out.format("replacing .class files in %,d %s%n", pearsOrJars.size(), kind);
// for (PearOrJar p : pearsOrJars) {
// pearOrJarPostProcessing(p, kind);
// }
// try {
// reportPaths("Reports of updated " + kind, kind + "FileUpdates.txt", classReplace);
//
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//}
//
//}
///**
//* When running the compiler to compile v3 sources, we need a classpath that at a minimum
//* includes uimaj-core. The strategy is to use the invoker of this tool's classpath as
//* specified from the application class loader
//* @return true if no errors
//*/
//private boolean compileV3SourcesCommon(List<ClassnameAndPath> items, String msg, String pearClasspath) {
//
// if (items.size() == 0) {
// return true;
// }
// System.out.format("Compiling %,d classes %s -- This may take a while!%n", c2ps.size(), msg);
// StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, Charset.forName("UTF-8"));
//
// List<String> cus = items.stream()
// .map(c -> outDirConverted + "v3/" + c.classname + ".java")
// .collect(Collectors.toList());
//
// Iterable<String> compilationUnitStrings = cus;
//
// Iterable<? extends JavaFileObject> compilationUnits =
// fileManager.getJavaFileObjectsFromStrings(compilationUnitStrings);
//
// // specify where the output classes go
// String classesBaseDir = outDirConverted + "v3-classes";
// try {
// Files.createDirectories(Paths.get(classesBaseDir));
// } catch (IOException e) {
// throw new UIMARuntimeException(e);
// }
// // specify the classpath
// String classpath = getCompileClassPath(pearClasspath);
// Iterable<String> options = Arrays.asList("-d", classesBaseDir,
// "-classpath", classpath);
// return javaCompiler.getTask(null, fileManager, null, options, null, compilationUnits).call();
//}
///**
//* Called after class is migrated
//* Given a path to a class (source or class file),
//* return the URL to the class as found in the classpath.
//* This returns the "first" one found in the classpath, in the case of duplicates.
//* @param path
//* @return the location of the class in the class path
//*/
//private URL getPathForClass(Path path) {
// return (null == packageAndClassNameSlash)
// ? null
// : migrateClassLoader.getResource(packageAndClassNameSlash + ".class");
//}
//private void getBaseOutputPath() {
//String s = packageAndClassNameSlash;
//int i = 0;
//while (!usedPackageAndClassNames.add(s)) {
// i = i + 1;
// s = packageAndClassNameSlash + "_dupid_" + i;
//}
//packageAndClassNameSlash_i = i;
//}
//private String prepareIndividual(String classname) {
//candidate = new Candidate(Paths.get(classname)); // a pseudo path
//packageName = null;
//className = null;
//packageAndClassNameSlash = null;
//cu = null;
//return decompile(classname); // always look up in classpath
// // to decompile individual source - put in sourcesRoots
//}
//if (!isSource) { // skip this recording if source
//if (null != pear_current) {
// // inside a pear, which has been unzipped into a temporary pearInstallDir;
// // we don't want that temporary dir to be part of the path.
// path2InsidePearOrJarPath.put(path.toString(), pearResolveStart.relativize(path).toString());
// pear_current.pathsToCandidateFiles.add(path.toString());
//}
//
//if (!isSource && pear_or_jar_current_stack.size() > 0) {
// // inside a jar, not contained in a pear
// pear_or_jar_current_stack.getFirst().pathsToCandidateFiles.add(path.toString());
//}
//}
//}
///**
//* For a given candidate, use its path:
//* switch the ...java to ..._Type.java, or ...class to ..._Type.class
//* look thru all the candidates
//* @param cand
//* @param start
//* @return
//*/
//private boolean has_Type(Candidate cand, int start) {
// if (start >= candidates.size()) {
// return false;
// }
//
// String sc = cand.p.toString();
// String sc_minus_suffix = sc.substring(0, sc.length() - ( isSource ? ".java".length() : ".class".length()));
// String sc_Type = sc_minus_suffix + ( isSource ? "_Type.java" : "_Type.class");
// // a string which sorts beyond the candidate + a suffix of "_"
// String s_end = sc_minus_suffix + (char) (((int)'_') + 1);
// for (Candidate c : candidates.subList(start, candidates.size())) {
// String s = c.p.toString();
// if (s_end.compareTo(s) < 0) {
// return false; // not found, we're already beyond where it would be found
// }
// if (s.equals(sc_Type)) {
// return true;
// }
// }
// return false;
//}
//private final static Comparator<Candidate> pathComparator = new Comparator<Candidate>() {
//@Override
//public int compare(Candidate o1, Candidate o2) {
// return o1.p.toString().compareTo(o2.p.toString());
//}
//};
//// there may be several same-name roots not quite right
//// xxx_Type$1.class
//
//private void addIfPreviousIsSameName(List<Path> c, int i) {
//if (i == 0) return;
//String _Type = candidates.get(i).toString();
////String prev = r.get(i-1).getPath();
//String prefix = _Type.substring(0, _Type.length() - ("_Type." + (isSource ? "java" : "class")).length());
//i--;
//while (i >= 0) {
// String s = candidates.get(i).toString();
// if ( ! s.startsWith(prefix)) {
// break;
// }
// if (s.substring(prefix.length()).equals((isSource ? ".java" : ".class"))) {
// c.add(candidates.get(i));
// break;
// }
// i--;
//}
//}
//
//for (int i = 0; i < pearOrJar.pathsToCandidateFiles.size(); i++) {
// String candidatePath = pearOrJar.pathsToCandidateFiles.get(i);
// String path_in_v3_classes = isPear
// ? getPath_in_v3_classes(candidatePath)
// : candidatePath;
//
// Path src = Paths.get(outputDirectory, "converted/v3-classes", path_in_v3_classes
// + (isPear ? ".class" : ""));
// Path tgt = pfs.getPath(
// "/",
// isPear
// ? path2InsidePearOrJarPath.get(candidatePath) // needs to be bin/org/... etc
// : candidatePath); // needs to be org/... etc
// if (Files.exists(src)) {
// Files.copy(src, tgt, StandardCopyOption.REPLACE_EXISTING);
// reportPearOrJarClassReplace(pearOrJarCopy.toString(), path_in_v3_classes, kind);
// }
//}
///** for compiled mode, do recompiling and reassembly of Jars and Pears */
//
//private boolean compileAndReassemble(CommonConverted cc, Container container, Path path) {
// boolean noErrors = true;
// if (javaCompiler != null) {
// if (container.haveDifferentCapitalizedNamesCollidingOnWindows) {
// System.out.println("Skipping compiling / reassembly because class " + container.toString() + " has multiple names differing only in capitalization, please resolve first.");
// } else {
//
//
// noErrors = compileV3PearSources(container, path);
// noErrors = noErrors && compileV3NonPearSources(container, path);
//
// postProcessPearsOrJars("jars" , jars , jarClassReplace);
// postProcessPearsOrJars("pears", pears, pearClassReplace);
//
////
//// try {
//// Path pearOutDir = Paths.get(outputDirectory, "pears");
//// FileUtils.deleteRecursive(pearOutDir.toFile());
//// Files.createDirectories(pearOutDir);
//// } catch (IOException e) {
//// throw new RuntimeException(e);
//// }
////
//// System.out.format("replacing .class files in %,d PEARs%n", pears.size());
//// for (PearOrJar p : pears) {
//// pearOrJarPostProcessing(p);
//// }
//// try {
//// reportPaths("Reports of updated Pears", "pearFileUpdates.txt", pearClassReplace);
//// } catch (IOException e) {
//// throw new RuntimeException(e);
//// }
// }
// }
//
// return noErrors;
//}
///**
//* @return true if no errors
//*/
//private boolean compileV3PearSources() {
// boolean noError = true;
// Map<String, List<ClassnameAndPath>> p2c = c2ps.stream()
// .filter(c -> c.pearClasspath != null)
// .collect(Collectors.groupingBy(c -> c.pearClasspath));
//
// List<Entry<String, List<ClassnameAndPath>>> ea = p2c.entrySet().stream()
// .sorted(Comparator.comparing(Entry::getKey)) //(e1, e2) -> e1.getKey().compareTo(e2.getKey())
// .collect(Collectors.toList());
//
// for (Entry<String, List<ClassnameAndPath>> e : ea) {
// noError = noError && compileV3SourcesCommon(e.getValue(), "for Pear " + e.getKey(), e.getKey() );
// }
// return noError;
//}
//
///**
//* @return true if no errors
//*/
//private boolean compileV3NonPearSources() {
//
// List<ClassnameAndPath> cnps = c2ps.stream()
// .filter(c -> c.pearClasspath == null)
// .collect(Collectors.toList());
//
// return compileV3SourcesCommon(cnps, "(non PEAR)", null);
//}
///**
//* @param pathInPear a complete path to a class inside an (installed) pear
//* @return the part starting after the top node of the install dir
//*/
//private String getPath_in_v3_classes(String pathInPear) {
// return path2classname.get(pathInPear);
//}
//private boolean reportDuplicates() throws IOException {
//List<List<CommonConverted>> nonIdenticals = new ArrayList<>();
//List<CommonConverted> onlyIdenticals = new ArrayList<>();
//
//classname2multiSources.forEach(
// (classname, ccs) -> {
// if (ccs.size() > 1) {
// nonIdenticals.add(ccs);
// } else {
// CommonConverted cc = ccs.get(0);
// if (cc.containersAndV2Paths.size() > 1)
// onlyIdenticals.add(cc); // the same item in multiple containers and/or paths
// }
// }
// );
//
//if (nonIdenticals.size() == 0) {
// if (onlyIdenticals.size() == 0) {
// System.out.println("There were no duplicates found.");
// } else {
// // report identical duplicates
// try (BufferedWriter bw = Files.newBufferedWriter(makePath(outDirLog + "identical_duplicates.txt"), StandardOpenOption.CREATE)) {
// logPrintNl("Report of Identical duplicates:", bw);
// for (CommonConverted cc : onlyIdenticals) {
// int i = 0;
// logPrintNl("Class: " + cc.fqcn_slash, bw);
// for (ContainerAndPath cp : cc.containersAndV2Paths) {
// logPrintNl(" " + (++i) + " " + cp, bw);
// }
// logPrintNl("", bw);
// }
// }
// }
// return true;
//}
//
//// non-identicals, print out all of them
//try (BufferedWriter bw = Files.newBufferedWriter(makePath(outDirLog + "nonIdentical_duplicates.txt"), StandardOpenOption.CREATE)) {
// logPrintNl("Report of non-identical duplicates", bw);
// for (List<CommonConverted> nonIdentical : nonIdenticals) {
// String fqcn = nonIdentical.get(0).fqcn_slash;
// logPrintNl(" classname: " + fqcn, bw);
// int i = 1;
// // for each cc, and within each cc, for each containerAndPath
// for (CommonConverted cc : nonIdentical) {
//// logPrintNl(" version " + i, bw);
// assert fqcn.equals(cc.fqcn_slash);
// int j = 1;
// boolean isSame = cc.containersAndV2Paths.size() > 1;
// boolean isFirstTime = true;
// for (ContainerAndPath cp : cc.containersAndV2Paths) {
// String first = isSame && isFirstTime
// ? " same: "
// : isSame
// ? " "
// : " ";
// isFirstTime = false;
// logPrintNl(first + i + "." + (j++) + " " + cp, bw);
// }
// indent[0] -= 6;
//// logPrintNl("", bw);
// i++;
// }
//// logPrintNl("", bw);
// }
//}
//return false;
//}
}
| uimaj-v3migration-jcas/src/main/java/org/apache/uima/migratev3/jcas/MigrateJCas.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.uima.migratev3.jcas;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import org.apache.uima.UIMARuntimeException;
import org.apache.uima.cas.impl.TypeImpl;
import org.apache.uima.cas.impl.TypeSystemImpl;
import org.apache.uima.cas.impl.UimaDecompiler;
import org.apache.uima.internal.util.CommandLineParser;
import org.apache.uima.internal.util.Misc;
import org.apache.uima.internal.util.UIMAClassLoader;
import org.apache.uima.internal.util.function.Runnable_withException;
import org.apache.uima.pear.tools.PackageBrowser;
import org.apache.uima.pear.tools.PackageInstaller;
import org.apache.uima.util.FileUtils;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.PackageDeclaration;
import com.github.javaparser.ast.body.AnnotationDeclaration;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.ConstructorDeclaration;
import com.github.javaparser.ast.body.EnumDeclaration;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.body.TypeDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.AssignExpr;
import com.github.javaparser.ast.expr.BinaryExpr;
import com.github.javaparser.ast.expr.CastExpr;
import com.github.javaparser.ast.expr.EnclosedExpr;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.FieldAccessExpr;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.ast.expr.Name;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.expr.NullLiteralExpr;
import com.github.javaparser.ast.expr.ObjectCreationExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.expr.StringLiteralExpr;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.EmptyStmt;
import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt;
import com.github.javaparser.ast.stmt.ExpressionStmt;
import com.github.javaparser.ast.stmt.IfStmt;
import com.github.javaparser.ast.stmt.ReturnStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.PrimitiveType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import com.github.javaparser.printer.PrettyPrinter;
import com.github.javaparser.printer.PrettyPrinterConfiguration;
/**
* <p>A driver that scans given roots for source and/or class Java files that contain JCas classes
*
* <ul><li>identifies which ones appear to be JCas classes (heuristic)
* <ul><li>of these, identifies which ones appear to be v2
* <ul><li>converts these to v3</li></ul></li></ul>
*
* <li>also can receive a list of individual class names</li>
* </ul>
*
* <p>Creates summary and detailed reports of its actions.
*
* <p>Files representing JCas classes to convert are discovered by walking file system
* directories from various roots, specified as input. The tool operates in 1 of two exclusive
* "modes": migrating from sources (e.g., .java files) and migrating using compiled classes.
*
* <p>Compiled classes are decompiled and then migrated. This decompilation step usually
* requires a java classpath, which is supplied using the -migrateClasspath parameter.
* Exception: migrating PEAR files, which contain their own specification for a classpath.
*
* <p>The same JCas class may be encountered multiple
* times while walking the directory tree from the roots,
* with the same or different definition. All of these definitions are migrated.
*
* <p>Copies of the original and the converted files are put into the output file tree.
*
* <p>Directory structure, starting at -outputDirectory (which if not specified, is a new temp directory).
* The "a0", "a1" represent non-identical alternative definitions for the same class.
* <pre>
* converted/
* v2/ these are the decompiled or "found" source files
* a0/x/y/z/javapath/.../Classname.java root-id + fully qualified java class + package as slashified name
* /Classname2.java etc.
* a1/x/y/z/javapath/.../Classname.java if there are different root-ids
* ...
* v3/
* a0/x/y/z/javapath/.../Classname.java fully qualified java class + package as slashified name
* /Classname2.java etc.
* a1/x/y/z/javapath/.../Classname.java if there are different root-ids
* ...
*
* v3-classes - the compiled form if from classes and a java compiler was available
* The first directory is the id of the Jar or PEAR container.
* The second directory is the alternative.
*
* 23/a0/fully/slashified/package/class-name.class << parallel structure as v3/
*
* jars/ - copies of the original JARs with the converted JCas classes
* The first directory is the id of the Jar or PEAR container
* 7/jar-file-name-last-part.jar
* 12/jar-file-name-last-part.jar
* 14/ etc.
*
* pears - copies of the original PEARs with the converted JCas classes, if there were no duplicates
* 8/pear-file-name-last-art.pear
* 9/ etc.
*
* not-converted/ (skipped)
* logs/
* jar-map.txt list of index to paths
* pear-map.txt list of index to paths
* processed.txt
* duplicates.txt
* builtinsNotExtended.txt
* failed.txt
* skippedBuiltins.txt
* nonJCasFiles.txt
* woraroundDir.txt
* deletedCheckModified.txt
* manualInspection.txt
* pearFileUpdates.txt
* jarFileUpdates.txt
* ...
* </pre>
*
* <p>Operates in one of two modes:
* <pre>
* Mode 1: Given classes-roots and/or individual class names, and a migrateClasspath,
* scans the classes-routes looking for classes candidates
* - determines the class name,
* - decompiles that
* - migrates that decompiled source.
*
* if a Java compiler (JDK) is available,
* - compiles the results
* - does reassembly for Jars and PEARs, replacing the JCas classes.
*
* Mode 2: Given sources-roots
* scans the sources-routes looking for candidates
* - migrates that decompiled source.
* </pre>
*
* <p>Note: Each run clears the output directory before starting the migration.
*
* <p>Note: classpath may be specified using -migrateClassPath or as the class path used to run this tool.
*/
public class MigrateJCas extends VoidVisitorAdapter<Object> {
/* *****************************************************
* Internals
*
* Unique IDs of v2 and v3 artifacts:
* RootId + classname
*
* RootIdContainers (Set<RootId>) hold all discovered rootIds, at each Jar/Pear nesting level
* including outer level (no Jar/Pear).
* These are kept in a push-down stack
*
*
* Processing roots collection: done for source or class
* - iterate, for all roots
* -- processCollection for candidates rooted at that root
* --- candidate is .java or .class, with path, with pearClasspath string
* ---- migrate called on each candidate
* ----- check to see if already done, and if so, skip.
* ------ means: same byte or source code associated with same fqcn
*
* Root-ids: created for each unique pathpart in front of fully-qualified class name
* created for each unique path to Jar or PEAR
*
* Caching to speed up duplicate processing:
* - decompiling: if the byte[] is already done, use other value (if augmented migrateClasspath is the same)
* - source-migrating: if the source strings are the same.
*
* Multiple sources for single class:
* classname2multiSources: TreeMap from fqcn to CommonConverted (string or bytes)
* CommonConverted: supports multiple paths having identical string/bytes.
*
* Compiling: driven from c2ps array of fqcn, path
* - may have multiple entries for same fqcn, with different paths,
* -- only if different values for the impl
* - set when visiting top-level compilation unit non-built-in type
*
*/
/** manange the indention of printing routines */
private static final int[] indent = new int[1];
private static StringBuilder si(StringBuilder sb) { return Misc.indent(sb, indent); }
private static StringBuilder flush(StringBuilder sb) {
System.out.print(sb);
sb.setLength(0);
return sb;
}
private static final Integer INTEGER0 = Integer.valueOf(0);
private static int nextContainerId = 0;
/******************************************************************
* Container - exists in tree structure, has super, sub containers
* -- subcontainers: has path to it
* - holds set of rootIds in that container
* - topmost one has null parent, and null pathToJarOrPear
******************************************************************/
private static class Container {
final int id = nextContainerId++;
final Container parent; // null if at top level
/** root to scan from.
* Pears: is the loc in temp space of installed pear
* Jars: is the file system mounted on the Jar
* -- for inner Jars, the Jar is copied out into temp space. */
Path root;
final Path rootOrig; // for Jars and Pears, the original path ending in jar or pear
final Set<Container> subContainers = new HashSet<>();
final List<Path> candidates = new ArrayList<>();
final List<CommonConverted> convertedItems = new ArrayList<>();
final List<V3CompiledPathAndContainerItemPath> v3CompiledPathAndContainerItemPath = new ArrayList<>();
final boolean isPear;
final boolean isJar;
/** can't use Path as the type, because the equals for Path is object == */
final Set<String> _Types = new HashSet<>(); // has the non_Type path only if the _Type is found
boolean haveDifferentCapitalizedNamesCollidingOnWindows = false;
String pearClasspath; // not final - set by subroutine after defaulting
/** Cache of already done compiled classes, to avoid redoing them
* Kept by container, because the classpath could change the decompile */
private Map<byte[], CommonConverted> origBytesToCommonConverted = new HashMap<>();
Container(Container parent, Path root) {
this.parent = parent;
if (parent != null) {
parent.subContainers.add(this);
this.pearClasspath = parent.pearClasspath; // default, when expanding Jars.
}
this.rootOrig = root;
String s = root.toString().toLowerCase();
isJar = s.endsWith(".jar");
isPear = s.endsWith(".pear");
this.root = isPear
? installPear()
: isJar
? prepareJar()
: root;
// // debug
// if (!isPear && isJar) {
// System.out.println("debug prepare jar: " + this);
// }
}
/**
* Called when a new container is created
* @param container
* @param path
* @return install directory
*/
private Path installPear() {
try {
File pearInstallDir = Files.createTempDirectory(getTempDir(), "installedPear").toFile();
PackageBrowser ip = PackageInstaller.installPackage(pearInstallDir, rootOrig.toFile(), false);
String newClasspath = ip.buildComponentClassPath();
String parentClasspath = parent.pearClasspath;
this.pearClasspath = (null == parentClasspath || 0 == parentClasspath.length())
? newClasspath
: newClasspath + File.pathSeparator + parentClasspath;
return Paths.get(pearInstallDir.toURI());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* copies embedded Jar to temp position in default file system if embedded.
* @return overlayed zip file system
*/
private Path prepareJar() {
try {
Path theJar = rootOrig;
if (!theJar.getFileSystem().equals(FileSystems.getDefault())) {
// embedded Jar: copy the Jar (intact) to a temp spot so it's no longer embedded
theJar = getTempOutputPathForJar(theJar);
Files.copy(rootOrig, theJar, StandardCopyOption.REPLACE_EXISTING);
}
FileSystem jfs = FileSystems.newFileSystem(theJar, null);
return jfs.getPath("/");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
si(sb); // initial nl and indentation
sb.append(isJar ? "Jar " : isPear ? "PEAR " : "");
sb.append("container [id=").append(id)
.append(", parent.id=").append((null == parent) ? "null" : parent.id)
.append(", root or pathToJarOrPear=").append(rootOrig).append(',');
indent[0] += 2;
try {
si(sb); // new line + indent
sb.append("subContainers=");
Misc.addElementsToStringBuilder(indent, sb, Misc.setAsList(subContainers), 100, (sbx, i) -> sbx.append(i.id)).append(',');
si(sb).append("paths migrated="); // new line + indent
Misc.addElementsToStringBuilder(indent, sb, candidates, 100, StringBuilder::append).append(',');
// si(sb).append("v3CompilePath="); // new line + indent
// Misc.addElementsToStringBuilder(indent, sb, v3CompiledPathAndContainerItemPath, 100, StringBuilder::append);
} finally {
indent[0] -=2;
si(sb).append(']');
}
return sb.toString();
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return 31 * id;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Container other = (Container) obj;
if (id != other.id)
return false;
return true;
}
}
private static class ContainerAndPath {
final Path path;
final Container container;
ContainerAndPath(Path path, Container container) {
this.path = path;
this.container = container;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ContainerAndPath [path=").append(path).append(", container=").append(container.id).append("]");
return sb.toString();
}
}
/**
* a pair of the v3CompiledPath, and the Container origRoot up to the start of the package and class name
* for the item being compiled.
* - Note: if a Jar has the same compiled class at multiple nesting levels, each one will have
* an instance of this class
*/
private static class V3CompiledPathAndContainerItemPath {
final Path v3CompiledPath;
final String pathInContainer;
public V3CompiledPathAndContainerItemPath(Path v3CompiledPath, String pathInContainer) {
this.v3CompiledPath = v3CompiledPath;
this.pathInContainer = pathInContainer;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
si(sb).append("v3CompiledPathAndContainerPartPath [");
indent[0] += 2;
try {
si(sb).append("v3CompiledPath=").append(v3CompiledPath);
si(sb).append("pathInContainer=").append(pathInContainer);
} finally {
indent[0] -= 2;
si(sb).append("]");
}
return sb.toString();
}
}
private static final JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
/****************************************************************
* Command line parameters
****************************************************************/
private static final String SOURCE_FILE_ROOTS = "-sourcesRoots";
private static final String CLASS_FILE_ROOTS = "-classesRoots";
private static final String OUTPUT_DIRECTORY = "-outputDirectory";
// private static final String SKIP_TYPE_CHECK = "-skipTypeCheck";
private static final String MIGRATE_CLASSPATH = "-migrateClasspath";
// private static final String CLASSES = "-classes"; // individual classes to migrate, get from supplied classpath
private static final Type intType = PrimitiveType.intType();
private static final EnumSet<Modifier> public_static_final =
EnumSet.of(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL);
private static final PrettyPrinterConfiguration printWithoutComments =
new PrettyPrinterConfiguration();
static { printWithoutComments.setPrintComments(false); }
private static final PrettyPrinterConfiguration printCu =
new PrettyPrinterConfiguration();
static { printCu.setIndent(" "); }
private static final String ERROR_DECOMPILING = "!!! ERROR:";
static private boolean isSource = false;
static private Path tempDir = null;
/***************************************************************************************************/
private String packageName; // with dots?
private String className; // (omitting package)
private String packageAndClassNameSlash;
// next 3 set at start of migrate for item being migrated
private CommonConverted current_cc;
private Path current_path;
private Container current_container;
/** includes trailing / */
private String outputDirectory;
/** includes trailing / */
private String outDirConverted;
/** includes trailing / */
private String outDirSkipped;
/** includes trailing / */
private String outDirLog;
private Container[] sourcesRoots = new Container[0]; // only one of these has 1 or more Container instances
private Container[] classesRoots = new Container[0];
private CompilationUnit cu;
// save this value in the class instance to avoid recomputing it
private ClassLoader cachedMigrateClassLoader = null;
private String migrateClasspath = null;
// private String individualClasses = null; // to decompile
/**
* CommonConverted next id, by fqcn
* key: fqcn_slashes value: next id
*/
private Map<String, Integer> nextCcId = new HashMap<>();
/**
* Common info about a particular source-code instance of a class
* Used to avoid duplicate work for the same JCas definition
* Used to track identical and non-identical duplicate defs
*
* When processing from sourcesRoots:
* use map: origSourceToCommonConverted key = source string
* if found, skip conversion, use previous converted result.
*
* When processing from classesRoots:
* use map: origBytesToCommonConverted key = byte[], kept by container in container
* if found, use previous converted results
*/
private class CommonConverted {
/**
* starts at 0, incr for each new instance for a particular fqcn_slash
* can't be assigned until fqcn known
*/
int id = -1; // temp value
final String v2Source; // remembered original source
final byte[] v2ByteCode; // remembered original bytes
/** all paths + their containers having the same converted result
* Need container because might change classpath for compiling
* - path is to v2 source or compiled class*/
final Set<ContainerAndPath> containersAndV2Paths = new HashSet<>();
String v3Source; // if converted, the result
/** converted/v3/id-of-cc/pkg/name/classname.java */
Path v3SourcePath; // path to converted source or null
String fqcn_slash; // full name of the class e.g. java/util/Foo. unknown for sources at first
CommonConverted(String origSource, byte[] v2ByteCode, Path path, Container container, String fqcn_slash) {
this.v2Source = origSource;
this.v2ByteCode = v2ByteCode;
containersAndV2Paths.add(new ContainerAndPath(path, container));
this.fqcn_slash = fqcn_slash;
}
Path getV2SourcePath(Container container) {
for (ContainerAndPath cp : containersAndV2Paths) {
if (cp.container == container) {
return cp.path;
}
}
throw new RuntimeException("internalError");
}
int getId() {
if (id < 0) {
Integer nextId = nextCcId.computeIfAbsent(fqcn_slash, s -> INTEGER0);
nextCcId.put(fqcn_slash, nextId + 1);
this.id = nextId;
}
return id;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return v2Source == null ? 0 : v2Source.hashCode();
}
/* equal if the v2source is equal
*/
@Override
public boolean equals(Object obj) {
return obj instanceof CommonConverted &&
v2Source != null &&
v2Source.equals(((CommonConverted)obj).v2Source);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
int maxLen = 10;
si(sb).append("CommonConverted [v2Source=").append(Misc.elide(v2Source, 100));
indent[0] += 2;
try {
si(sb).append("v2ByteCode=");
sb.append(v2ByteCode != null
? Arrays.toString(Arrays.copyOf(v2ByteCode, Math.min(v2ByteCode.length, maxLen))) :
"null").append(',');
si(sb).append("containersAndPaths=")
.append(containersAndV2Paths != null
? Misc.ppList(indent, Misc.setAsList(containersAndV2Paths), maxLen, StringBuilder::append)
: "null").append(',');
si(sb).append("v3SourcePath=").append(v3SourcePath).append(',');
si(sb).append("fqcn_slash=").append(fqcn_slash).append("]").append(Misc.ls);
} finally {
indent[0] -= 2;
}
return sb.toString();
}
}
/** Cache of already converted source classes, to avoid redoing them;
* - key is the actual source
* - value is CommonConverted
* This cache is over all containers
* */
private Map<String, CommonConverted> sourceToCommonConverted = new HashMap<>();
/**
* A map from fqcn_slash to a list of converted sources
* one per non-duplicated source
*/
private Map<String, List<CommonConverted>> classname2multiSources = new TreeMap<>();
/************************************
* Reporting
************************************/
// private final List<Path> v2JCasFiles = new ArrayList<>(); // unused
// private final List<Path> v3JCasFiles = new ArrayList<>(); // unused
private final List<PathAndReason> nonJCasFiles = new ArrayList<>(); // path, reason
private final List<PathAndReason> failedMigration = new ArrayList<>(); // path, reason
private final List<PathAndReason> skippedBuiltins = new ArrayList<>(); // path, "built-in"
private final List<PathAndReason> deletedCheckModified = new ArrayList<>(); // path, deleted check string
private final List<String1AndString2> pathWorkaround = new ArrayList<>(); // original, workaround
private final List<String1AndString2> pearClassReplace = new ArrayList<>(); // pear, classname
private final List<String1AndString2> jarClassReplace = new ArrayList<>(); // jar, classname
private final List<PathAndReason> manualInspection = new ArrayList<>(); // path, reason
// private final List<PathAndPath> embeddedJars = new ArrayList<>(); // source, temp
private boolean isV2JCas; // false at start of migrate, set to true if a v2 class candidate is discovered
private boolean isConvert2v3; // true at start of migrate, set to false if conversion fails, left true if already a v3
private boolean isBuiltinJCas; // false at start of migrate, set to true if a built-in class is discovered
/************************************
* Context for visits
************************************/
/**
* if non-null, we're inside the ast for a likely JCas getter or setter method
*/
private MethodDeclaration get_set_method;
private String featName;
private boolean isGetter;
private boolean isArraySetter;
/**
* the range name part for _getXXXValue.. calls
*/
private Object rangeNamePart;
/**
* the range name part for _getXXXValue.. calls without converting Ref to Feature
*/
private String rangeNameV2Part;
/**
* temp place to insert static final int feature declarations
*/
private NodeList<BodyDeclaration<?>> fi_fields = new NodeList<>();
private Set<String> featNames = new HashSet<>();
private boolean hasV2Constructors;
private boolean hasV3Constructors;
private boolean error_decompiling = false;
private boolean badClassName;
private int itemCount;
/**
* set if getAndProcessCasndidatesInContainer encounters a class where it cannot do the compile
*/
private boolean unableToCompile;
final private StringBuilder psb = new StringBuilder();
public MigrateJCas() {
}
public static void main(String[] args) {
(new MigrateJCas()).run(args);
}
/***********************************
* Main
* @param args -
***********************************/
void run(String[] args) {
CommandLineParser clp = parseCommandArgs(args);
System.out.format("Output top directory: %s%n", outputDirectory);
// clear output dir
FileUtils.deleteRecursive(new File(outputDirectory));
isSource = sourcesRoots.length > 0;
boolean isOk;
if (isSource) {
isOk = processRootsCollection("source", sourcesRoots, clp);
} else {
if (javaCompiler == null) {
System.out.println("The migration tool cannot compile the migrated files, \n"
+ " because no Java compiler is available.\n"
+ " To make one available, run this tool using a Java JDK, not JRE");
}
isOk = processRootsCollection("classes", classesRoots, clp);
}
// if (individualClasses != null) {
// processCollection("individual classes: ", new Iterator<String>() {
// Iterator<String> it = Arrays.asList(individualClasses.split(File.pathSeparator)).iterator();
// public boolean hasNext() {return it.hasNext();}
// public String next() {
// return prepareIndividual(it.next());}
// });
// }
if (error_decompiling) {
isOk = false;
}
isOk = report() && isOk;
System.out.println("Migration finished " +
(isOk
? "with no unusual conditions."
: "with 1 or more unusual conditions that need manual checking."));
}
/**
* called for compiled input when a compiler is available and don't have name collision
* if the container is a PEAR or a Jar
* Updates a copy of the Pear or Jar
* @param container
*/
private void postProcessPearOrJar(Container container) {
Path outDir = Paths.get(outputDirectory,
container.isJar ? "jars" : "pears",
Integer.toString(container.id));
withIOX(() -> Files.createDirectories(outDir));
si(psb).append("Replacing .class files in copy of ").append(container.rootOrig);
flush(psb);
try {
// copy the pear or jar so we don't change the original
Path lastPartOfPath = container.rootOrig.getFileName();
if (null == lastPartOfPath) throw new RuntimeException("Internal Error");
Path pearOrJarCopy = Paths.get(outputDirectory,
container.isJar ? "jars" : "pears",
Integer.toString(container.id),
lastPartOfPath.toString());
Files.copy(container.rootOrig, pearOrJarCopy);
// put up a file system on the pear or jar
FileSystem pfs = FileSystems.newFileSystem(pearOrJarCopy, null);
// replace the .class files in this PEAR or Jar with corresponding v3 ones
indent[0] += 2;
String[] previousSkip = {""};
container.v3CompiledPathAndContainerItemPath.forEach(c_p -> {
if (Files.exists(c_p.v3CompiledPath)) {
withIOX(() -> Files.copy(c_p.v3CompiledPath, pfs.getPath(c_p.pathInContainer), StandardCopyOption.REPLACE_EXISTING));
reportPearOrJarClassReplace(pearOrJarCopy.toString(), c_p.v3CompiledPath.toString(), container);
} else {
String pstr = c_p.v3CompiledPath.toString();
String pstr2 = pstr;
if (previousSkip[0] != "") {
int cmn = findFirstCharDifferent(previousSkip[0], pstr);
pstr2 = cmn > 5
? ("..." + pstr.substring(cmn))
: pstr;
}
previousSkip[0] = pstr;
si(psb).append("Skipping replacing ").append(pstr2)
.append(" due to compile errors.");
flush(psb);
}
});
indent[0] -= 2;
// for (CommonConverted cc : container.convertedItems) {
// Map<Container, Path> v3ccs = cc.v3CompiledResultPaths;
// v3ccs.forEach((v3ccc, v3cc_path) ->
// {
// if (v3ccc == container) {
// String path_in_v3_classes = cc.v3CompiledResultPaths.get(container).toString();
//
// withIOX(() -> Files.copy(v3cc_path, pfs.getPath(path_in_v3_classes)));
// reportPearOrJarClassReplace(pearOrJarCopy.toString(), path_in_v3_classes, container);
// }
// });
// }
pfs.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Compile all the migrated JCas classes in this container, adjusting the classpath
* if the container is a Jar or Pear to include the Jar or PEAR.
*
* As a side effect, it saves in the container, a list of all the compiled things together
* with the path in container part, for use by a subsequent step to update copies of the jars/pears.
*
* @param container
* @return true if compiled 1 or more sources, false if nothing was compiled
*/
private boolean compileV3SourcesCommon2(Container container) {
String classesBaseDir = outDirConverted + "v3-classes/" + container.id;
// specify the classpath. For PEARs use a class loader that loads first.
String classpath = getCompileClassPath(container);
// // debug
// String[] cpa = classpath.split(File.pathSeparator);
// System.out.println("debug - compilation classpath");
// int j = 0;
// for (String s : cpa) System.out.println("debug classpath: " + (++j) + " " + s);
// get a list of compilation unit path strings to the converted/v3/nnn/path
Path containerRoot = null;
/**
* The Cu Path Strings for one container might have multiple instances of the class.
* These might be for identical or different sources.
* - This happens when a root has multiple paths to instances of the same class.
* - Multiple compiled-paths might be for the same classname
*
* For non-identical sources, the commonContainer instance "id" is spliced into the
* v3 migrated source path: see getBaseOutputPath, e.g. converted/v3/2/fqcn/slashed/name.java
*
* The compiler will complain if you feed it the same compilation unit classname twice, with
* different paths saying "duplicate class definition".
* - Fix: do compilation in batches, one for each different commonConvertedContainer id.
*/
Map<Integer, ArrayList<String>> cu_path_strings_by_ccId = new TreeMap<>(); // tree map to have nice order of keys
indent[0] += 2;
boolean isEmpty = true;
for (CommonConverted cc : container.convertedItems) {
if (cc.v3SourcePath == null) continue; // skip items that failed migration
isEmpty = false;
// relativePathInContainer = the whole path with the first part (up to the end of the container root) stripped off
Path itemPath = cc.getV2SourcePath(container);
if (null == containerRoot) {
// lazy setup on first call
// for Pears, must use the == filesystem, otherwise get
// ProviderMismatchException
containerRoot = (container.isJar || container.isPear)
? itemPath.getFileSystem().getPath("/")
: container.rootOrig;
}
Path relativePathInContainer = containerRoot.relativize(cc.getV2SourcePath(container));
container.v3CompiledPathAndContainerItemPath.add(
new V3CompiledPathAndContainerItemPath(
Paths.get(classesBaseDir, "a" + cc.id, relativePathInContainer.toString()),
relativePathInContainer.toString()));
ArrayList<String> items = cu_path_strings_by_ccId.computeIfAbsent(cc.id, x -> new ArrayList<>());
items.add(cc.v3SourcePath.toString());
}
if (isEmpty) {
si(psb).append("Skipping compiling for container ").append(container.id).append(" ").append(container.rootOrig);
si(psb).append(" because non of the v2 classes were migrated (might have been built-ins)");
flush(psb);
return false;
}
else {
si(psb).append("Compiling for container ").append(container.id).append(" ").append(container.rootOrig);
flush(psb);
}
// List<String> cu_path_strings = container.convertedItems.stream()
// .filter(cc -> cc.v3SourcePath != null)
// .peek(cc -> container.v3CompiledPathAndContainerItemPath.add(
// new V3CompiledPathAndContainerItemPath(
// Paths.get(classesBaseDir, cc.v3SourcePath.toString()),
// getPathInContainer(container, cc).toString())))
// .map(cc -> cc.v3SourcePath.toString())
// .collect(Collectors.toList());
boolean resultOk = true;
for (int ccId = 0;; ccId++) { // do each version of classes separately
List<String> cups = cu_path_strings_by_ccId.get(ccId);
if (cups == null) {
break;
}
StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, Charset.forName("UTF-8"));
Iterable<? extends JavaFileObject> compilationUnits =
fileManager.getJavaFileObjectsFromStrings(cups);
// //debug
// System.out.println("Debug: list of compilation unit strings for iteration " + i);
// int[] k = new int[] {0};
// cups.forEach(s -> System.out.println(Integer.toString(++(k[0])) + " " + s));
// System.out.println("debug end");
String classesBaseDirN = classesBaseDir + "/a" + ccId;
withIOX(() -> Files.createDirectories(Paths.get(classesBaseDirN)));
Iterable<String> options = Arrays.asList("-d", classesBaseDirN, "-classpath", classpath);
si(psb).append("Compiling for commonConverted version ").append(ccId)
.append(", ").append(cups.size()).append(" classes");
flush(psb);
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
/*********** Compile ***********/
resultOk = javaCompiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits).call() && resultOk;
/********************************/
indent[0] += 2;
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
JavaFileObject s = diagnostic.getSource();
si(psb).append(diagnostic.getKind());
int lineno = (int) diagnostic.getLineNumber();
if (lineno != Diagnostic.NOPOS) {
psb.append(" on line ").append(diagnostic.getLineNumber());
}
int pos = (int) diagnostic.getPosition();
if (pos != Diagnostic.NOPOS) {
psb.append(", position: ").append(diagnostic.getColumnNumber());
}
if (s != null) {
psb.append(" in ").append(s.toUri());
}
si(psb).append(" ").append(diagnostic.getMessage(null));
flush(psb);
}
withIOX( () -> fileManager.close());
indent[0] -= 2;
si(psb).append("Compilation finished").append(
resultOk ? " with no errors." : "with some errors.");
flush(psb);
}
indent[0] -= 2;
unableToCompile = !resultOk;
return true;
}
/**
* The classpath used to compile is (in precedence order)
* - the classpath for this migration app (first in order to pick up v3 support, overriding others)
* - any Pears, going up the parent chain, closest ones first
* - any Jars, going up the parent chain, closest ones last
* - passed in migrate classpath
* @return the classpath to use in compiling the jcasgen'd sources
*/
private String getCompileClassPath(Container container) {
// start with this (the v3migration tool) app's classpath to a cp string
URLClassLoader systemClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
URL[] urls = systemClassLoader.getURLs();
StringBuilder cp = new StringBuilder();
boolean firstTime = true;
for (URL url : urls) {
if (! firstTime) {
cp.append(File.pathSeparatorChar);
} else {
firstTime = false;
}
cp.append(url.getPath());
}
// pears up the classpath, closest first
Container c = container;
while (c != null) {
if (c.isPear) {
cp.append(File.pathSeparator).append(c.pearClasspath);
}
c = c.parent;
}
// add the migrateClasspath, expanded
if (null != migrateClasspath) {
cp.append(File.pathSeparator).append(Misc.expandClasspath(migrateClasspath));
}
// add the Jars, closest last
c = container;
List<String> ss = new ArrayList<>();
while (c != null) {
if (c.isJar) {
ss.add(c.root.toString());
}
c = c.parent;
}
Collections.reverse(ss);
ss.forEach(s -> cp.append(File.pathSeparator).append(s));
// System.out.println("debug: compile classpath = " + cp.toString());
return cp.toString();
}
/**
* iterate to process collections from all roots
* Called once, to process either sources or classes
* @return false if unable to compile, true otherwise
*/
private boolean processRootsCollection(String kind, Container[] roots, CommandLineParser clp) {
unableToCompile = false; // preinit
psb.setLength(0);
indent[0] = 0;
itemCount = 1;
for (Container rootContainer : roots) {
showWorkStart(rootContainer);
// adds candidates to root containers, and adds sub containers for Jars and Pears
getAndProcessCandidatesInContainer(rootContainer);
// for (Path path : rootContainer.candidates) {
//
// CommonConverted cc = getSource(path, rootContainer);
// migrate(cc, rootContainer, path);
//
// if ((i % 50) == 0) System.out.format("%4d%n ", Integer.valueOf(i));
// i++;
// }
}
si(psb).append("Total number of candidates processed: ").append(itemCount - 1);
flush(psb);
indent[0] = 0;
return !unableToCompile;
}
private void showWorkStart(Container rootContainer) {
si(psb).append("Migrating " + rootContainer.rootOrig.toString());
indent[0] += 2;
si(psb).append("Each character is one class");
si(psb).append(" . means normal class");
si(psb).append(" b means built in");
si(psb).append(" i means identical duplicate");
si(psb).append(" d means non-identical definition for the same JCas class");
si(psb).append(" nnn at the end of the line is the number of classes migrated");
flush(psb);
}
/**
* parse command line args
* @param args -
* @return the CommandLineParser instance
*/
private CommandLineParser parseCommandArgs(String[] args) {
CommandLineParser clp = createCmdLineParser();
try {
clp.parseCmdLine(args);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (!checkCmdLineSyntax(clp)) {
printUsage();
System.exit(2);
}
if (clp.isInArgsList(CLASS_FILE_ROOTS)) {
classesRoots = getRoots(clp, CLASS_FILE_ROOTS);
}
if (clp.isInArgsList(SOURCE_FILE_ROOTS)) {
sourcesRoots = getRoots(clp, SOURCE_FILE_ROOTS);
}
return clp;
}
private Container[] getRoots(CommandLineParser clp, String kind) {
String[] paths = clp.getParamArgument(kind).split("\\" + File.pathSeparator);
Container[] cs = new Container[paths.length];
int i = 0;
for (String path : paths) {
cs[i++] = new Container(null, Paths.get(path));
}
return cs;
}
/**
* @param p the path to the compiled or non-compiled source
* @param container the container
* @return the instance of the CommonConverted object,
* and update the container's convertedItems list if needed to include it
*/
private CommonConverted getSource(Path p, Container container) {
try {
byte[] localV2ByteCode = null;
CommonConverted cc;
String v2Source;
if (!isSource) {
localV2ByteCode = Files.readAllBytes(p);
// only use prev decompiled if same container
cc = container.origBytesToCommonConverted.get(localV2ByteCode);
if (null != cc) {
return cc;
}
// decompile side effect: sets fqcn
try {
v2Source = decompile(localV2ByteCode, container.pearClasspath);
} catch (RuntimeException e) {
badClassName = true;
e.printStackTrace();
v2Source = null;
}
if (badClassName) {
System.err.println("Candidate with bad Class Name is: " + p.toString());
return null;
}
final byte[] finalbc = localV2ByteCode;
cc = sourceToCommonConverted.computeIfAbsent(v2Source,
src -> new CommonConverted(src, finalbc, p, container, packageAndClassNameSlash));
// cc = new CommonConverted(v2Source, localV2ByteCode, p, container, packageAndClassNameSlash);
container.origBytesToCommonConverted.put(localV2ByteCode, cc);
} else {
v2Source = FileUtils.reader2String(Files.newBufferedReader(p));
cc = sourceToCommonConverted.get(v2Source);
if (null == cc) {
cc = new CommonConverted(v2Source, null, p, container, "unknown");
sourceToCommonConverted.put(v2Source, cc);
} else {
// add this new path + container to set of pathsAndContainers kept by this CommonConverted object
cc.containersAndV2Paths.add(new ContainerAndPath(p, container));
}
}
//Containers have list of CommonConverted, which, in turn
// have Set of ContainerAndPath elements.
// (the same JCas class might appear in two different paths in a container)
if (!container.convertedItems.contains(cc)) {
container.convertedItems.add(cc);
}
return cc;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Migrate one JCas definition, writes to Sysem.out 1 char to indicate progress.
*
* The source is either direct, or a decompiled version of a .class file (missing comments, etc.).
*
* This method only called if heuristics indicate this is a V2 JCas class definition.
*
* Skips the migration if already done.
* Skips if decompiling, and it failed.
*
* The goal is to preserve as much as possible of existing customization.
* The general approach is to parse the source into an AST, and use visitor methods.
* For getter/setter methods that are for features (heurstic), set up a context for inner visitors
* identifying the getter / setter.
* - reuse method declarator, return value casts, value expressions
* - remove feature checking statement, array bounds checking statement, if present.
* - replace the simpleCore (see Jg), replace the arrayCore
*
* For constructors, replace the 2-arg one that has arguments:
* addr and TOP_Type with the v3 one using TypeImpl, CasImpl.
*
* Add needed imports.
* Add for each feature the _FI_xxx static field declarator.
*
* Leave other top level things alone
* - additional constructors.
* - other methods not using jcasType refs
*
* @param source - the source, either directly from a .java file, or a decompiled .class file
*/
private void migrate(CommonConverted cc, Container container, Path path) {
if (null == cc) {
System.err.println("Skipping this component due to decompile failure: " + path.toString());
System.err.println(" in container: " + container);
isConvert2v3 = false;
error_decompiling = true;
return;
}
if (cc.v3Source != null) {
// next updates classname2multiSources for tracking non-identical defs
boolean identical = collectInfoForReports(cc);
assert identical;
psb.append("i");
flush(psb);
cc.containersAndV2Paths.add(new ContainerAndPath(path, container));
return;
}
assert cc.v2Source != null;
packageName = null;
className = null;
packageAndClassNameSlash = null;
cu = null;
String source = cc.v2Source;
isConvert2v3 = true; // preinit, set false if convert fails
isV2JCas = false; // preinit, set true by reportV2Class, called by visit to ClassOrInterfaceDeclaration,
// when it has v2 constructors, and the right type and type_index_id field declares
isBuiltinJCas = false;
featNames.clear();
fi_fields.clear();
try { // to reset the next 3 items
current_cc = cc;
current_container = container;
current_path = path;
// System.out.println("Migrating source before migration:\n");
// System.out.println(source);
// System.out.println("\n\n\n");
if (source.startsWith(ERROR_DECOMPILING)) {
System.err.println("Decompiling failed for class: " + cc.toString() + "\n got: " + Misc.elide(source, 300, false));
System.err.println("Please check the migrateClasspath");
if (null == migrateClasspath) {
System.err.println("classpath of this app is");
System.err.println(System.getProperty("java.class.path"));
} else {
System.err.println(" first part of migrateClasspath argument was: " + Misc.elide(migrateClasspath, 300, false));
System.err.println(" Value used was:");
URL[] urls = Misc.classpath2urls(migrateClasspath);
for (URL url : urls) {
System.err.println(" " + url.toString());
}
}
System.err.println("Skipping this component");
isConvert2v3 = false;
error_decompiling = true;
return;
}
StringReader sr = new StringReader(source);
try {
cu = JavaParser.parse(sr);
addImport("org.apache.uima.cas.impl.CASImpl");
addImport("org.apache.uima.cas.impl.TypeImpl");
addImport("org.apache.uima.cas.impl.TypeSystemImpl");
this.visit(cu, null); // side effect: sets the className, packageAndClassNameSlash, packageName
new removeEmptyStmts().visit(cu, null);
if (isConvert2v3) {
removeImport("org.apache.uima.jcas.cas.TOP_Type");
}
if (isConvert2v3 && fi_fields.size() > 0) {
NodeList<BodyDeclaration<?>> classMembers = cu.getTypes().get(0).getMembers();
int positionOfFirstConstructor = findConstructor(classMembers);
if (positionOfFirstConstructor < 0) {
throw new RuntimeException();
}
classMembers.addAll(positionOfFirstConstructor, fi_fields);
}
if (isSource) {
sourceToCommonConverted.put(source, cc);
}
boolean identicalFound = collectInfoForReports(cc);
assert ! identicalFound;
if (isV2JCas) {
writeV2Orig(cc, isConvert2v3);
}
if (isConvert2v3) {
cc.v3Source = new PrettyPrinter(printCu).print(cu);
writeV3(cc);
}
psb.append(isBuiltinJCas
? "b"
: (classname2multiSources.get(cc.fqcn_slash).size() == 1)
? "."
: "d"); // means non-identical duplicate
flush(psb);
} catch (IOException e) {
e.printStackTrace();
throw new UIMARuntimeException(e);
} catch (Exception e) {
System.out.println("debug: exception caught, source was\n" + source);
throw new UIMARuntimeException(e);
}
} finally {
current_cc = null;
current_container = null;
current_path = null;
}
}
/**
* Called when have already converted this exact source or
* when we just finished converting this source.
* Add this instance to the tracking information for multiple versions (identical or not) of a class
* @return true if this is an identical duplicate of one already done
*/
private boolean collectInfoForReports(CommonConverted cc) {
String fqcn_slash = cc.fqcn_slash;
// track, by fqcn, all duplicates (identical or not)
// // for a given fully qualified class name (slashified),
// // find the list of CommonConverteds - one per each different version
// // create it if null
List<CommonConverted> commonConverteds = classname2multiSources
.computeIfAbsent(fqcn_slash, k -> new ArrayList<CommonConverted>());
// search to see if this instance already in the set
// if so, add the path to the set of identicals
// For class sources case, we compare the decompiled version
boolean found = commonConverteds.contains(cc);
if (!found) {
commonConverteds.add(cc);
}
return found;
}
/******************
* Visitors
******************/
/**
* Capture the type name from all top-level types
* AnnotationDeclaration, Empty, and Enum
*/
@Override
public void visit(AnnotationDeclaration n, Object ignore) {
updateClassName(n);
super.visit(n, ignore);
}
// @Override
// public void visit(EmptyTypeDeclaration n, Object ignore) {
// updateClassName(n);
// super.visit(n, ignore);
// }
@Override
public void visit(EnumDeclaration n, Object ignore) {
updateClassName(n);
super.visit(n, ignore);
}
/**
* Check if the top level class looks like a JCas class, and report if not:
* has 0, 1, and 2 element constructors
* has static final field defs for type and typeIndexID
*
* Also check if V2 style: 2 arg constructor arg types
* Report if looks like V3 style due to args of 2 arg constructor
*
* if class doesn't extend anything, not a JCas class.
* if class is enum, not a JCas class
* @param n -
* @param ignore -
*/
@Override
public void visit(ClassOrInterfaceDeclaration n, Object ignore) {
// do checks to see if this is a JCas class; if not report skipped
Optional<Node> maybeParent = n.getParentNode();
if (maybeParent.isPresent()) {
Node parent = maybeParent.get();
if (parent instanceof CompilationUnit) {
updateClassName(n);
if (isBuiltinJCas) {
// is a built-in class, skip it
super.visit(n, ignore);
return;
}
NodeList<ClassOrInterfaceType> supers = n.getExtendedTypes();
if (supers == null || supers.size() == 0) {
reportNotJCasClass("class doesn't extend a superclass");
super.visit(n, ignore);
return;
}
NodeList<BodyDeclaration<?>> members = n.getMembers();
setHasJCasConstructors(members);
if (hasV2Constructors && hasTypeFields(members)) {
reportV2Class();
super.visit(n, ignore);
return;
}
if (hasV2Constructors) {
reportNotJCasClassMissingTypeFields();
return;
}
if (hasV3Constructors) {
reportV3Class();
return;
}
reportNotJCasClass("missing v2 constructors");
return;
}
}
super.visit(n, ignore);
return;
}
@Override
public void visit(PackageDeclaration n, Object ignored) {
packageName = n.getNameAsString();
super.visit(n, ignored);
}
/***************
* Constructors
* - modify the 2 arg constructor - changing the args and the body
* @param n - the constructor node
* @param ignored -
*/
@Override
public void visit(ConstructorDeclaration n, Object ignored) {
super.visit(n, ignored); // processes the params
if (!isConvert2v3) { // for enums, annotations
return;
}
List<Parameter> ps = n.getParameters();
if (ps.size() == 2 &&
getParmTypeName(ps, 0).equals("int") &&
getParmTypeName(ps, 1).equals("TOP_Type")) {
/** public Foo(TypeImpl type, CASImpl casImpl) {
* super(type, casImpl);
* readObject();
*/
setParameter(ps, 0, "TypeImpl", "type");
setParameter(ps, 1, "CASImpl", "casImpl");
// Body: change the 1st statement (must be super)
NodeList<Statement> stmts = n.getBody().getStatements();
if (!(stmts.get(0) instanceof ExplicitConstructorInvocationStmt)) {
recordBadConstructor("missing super call");
return;
}
NodeList<Expression> args = ((ExplicitConstructorInvocationStmt)(stmts.get(0))).getArguments();
args.set(0, new NameExpr("type"));
args.set(1, new NameExpr("casImpl"));
// leave the rest unchanged.
}
}
private final static Pattern refGetter = Pattern.compile("(ll_getRef(Array)?Value)|"
+ "(ll_getFSForRef)");
private final static Pattern word1 = Pattern.compile("\\A(\\w*)"); // word chars starting at beginning \\A means beginning
/*****************************
* Method Declaration Visitor
* Heuristic to determine if a feature getter or setter:
* - name: is 4 or more chars, starting with get or set, with 4th char uppercase
* is not "getTypeIndexID"
* - (optional - if comments are available:)
* getter for xxx, setter for xxx
* - for getter: has 0 or 1 arg (1 arg case for indexed getter, arg must be int type)
* - for setter: has 1 or 2 args
*
* Workaround for decompiler - getters which return FSs might be missing the cast to the return value type
*
*****************************/
@Override
public void visit(MethodDeclaration n, Object ignore) {
String name = n.getNameAsString();
isGetter = isArraySetter = false;
do { // to provide break exit
if (name.length() >= 4 &&
((isGetter = name.startsWith("get")) || name.startsWith("set")) &&
Character.isUpperCase(name.charAt(3)) &&
!name.equals("getTypeIndexID")) {
List<Parameter> ps = n.getParameters();
if (isGetter) {
if (ps.size() > 1) break;
} else { // is setter
if (ps.size() > 2 ||
ps.size() == 0) break;
if (ps.size() == 2) {
if (!getParmTypeName(ps, 0).equals("int")) break;
isArraySetter = true;
}
}
// get the range-part-name and convert to v3 range ("Ref" changes to "Feature")
String bodyString = n.getBody().get().toString(printWithoutComments);
int i = bodyString.indexOf("jcasType.ll_cas.ll_");
if (i < 0) break;
String s = bodyString.substring(i + "jcasType.ll_cas.ll_get".length()); // also for ...ll_set - same length!
if (s.startsWith("FSForRef(")) { // then it's the wrapper and the wrong instance.
i = s.indexOf("jcasType.ll_cas.ll_");
if (i < 0) {
reportUnrecognizedV2Code("Found \"jcasType.ll_cas.ll_[set or get]...FSForRef(\" but didn't find following \"jcasType.ll_cas_ll_\"\n" + n.toString());
break;
}
s = s.substring(i + "jcasType.ll_cas.ll_get".length());
}
i = s.indexOf("Value");
if (i < 0) {
reportUnrecognizedV2Code("Found \"jcasType.ll_cas.ll_[set or get]\" but didn't find following \"Value\"\n" + n.toString());
break; // give up
}
s = Character.toUpperCase(s.charAt(0)) + s.substring(1, i);
rangeNameV2Part = s;
rangeNamePart = s.equals("Ref") ? "Feature" : s;
// get feat name following ")jcasType).casFeatCode_xxxxx,
i = bodyString.indexOf("jcasType).casFeatCode_");
if (i == -1) {
reportUnrecognizedV2Code("Didn't find \"...jcasType).casFeatCode_\"\n" + n.toString());
break;
}
Matcher m = word1.matcher(bodyString.substring(i + "jcasType).casFeatCode_".length() ));
if (!m.find()) {
reportUnrecognizedV2Code("Found \"...jcasType).casFeatCode_\" but didn't find subsequent word\n" + n.toString());
break;
}
featName = m.group(1);
String fromMethod = Character.toLowerCase(name.charAt(3)) + name.substring(4);
if (!featName.equals(fromMethod)) {
// don't report if the only difference is the first letter captialization
if (!(Character.toLowerCase(featName.charAt(0)) + featName.substring(1)).equals(fromMethod)) {
reportMismatchedFeatureName(String.format("%-25s %s", featName, name));
}
}
NodeList<Expression> args = new NodeList<>();
args.add(new StringLiteralExpr(featName));
VariableDeclarator vd = new VariableDeclarator(
intType,
"_FI_" + featName,
new MethodCallExpr(new NameExpr("TypeSystemImpl"), new SimpleName("getAdjustedFeatureOffset"), args));
if (featNames.add(featName)) { // returns true if it was added, false if already in the set of featNames
fi_fields.add(new FieldDeclaration(public_static_final, vd));
}
/**
* add missing cast stmt for
* return stmts where the value being returned:
* - doesn't have a cast already
* - has the expression be a methodCallExpr with a name which looks like:
* ll_getRefValue or
* ll_getRefArrayValue
*/
if (isGetter && "Feature".equals(rangeNamePart)) {
for (Statement stmt : n.getBody().get().getStatements()) {
if (stmt instanceof ReturnStmt) {
Expression e = getUnenclosedExpr(((ReturnStmt)stmt).getExpression().get());
if ((e instanceof MethodCallExpr)) {
String methodName = ((MethodCallExpr)e).getNameAsString();
if (refGetter.matcher(methodName).matches()) { // ll_getRefValue or ll_getRefArrayValue
addCastExpr(stmt, n.getType());
}
}
}
}
}
get_set_method = n; // used as a flag during inner "visits" to signal
// we're inside a likely feature setter/getter
} // end of test for getter or setter method
} while (false); // do once, provide break exit
super.visit(n, ignore);
get_set_method = null; // after visiting, reset the get_set_method to null
}
/**
* Visitor for if stmts
* - removes feature missing test
*/
@Override
public void visit(IfStmt n, Object ignore) {
do {
// if (get_set_method == null) break; // sometimes, these occur outside of recogn. getters/setters
Expression c = n.getCondition(), e;
BinaryExpr be, be2;
List<Statement> stmts;
if ((c instanceof BinaryExpr) &&
((be = (BinaryExpr)c).getLeft() instanceof FieldAccessExpr) &&
((FieldAccessExpr)be.getLeft()).getNameAsString().equals("featOkTst")) {
// remove the feature missing if statement
// verify the remaining form
if (! (be.getRight() instanceof BinaryExpr)
|| ! ((be2 = (BinaryExpr)be.getRight()).getRight() instanceof NullLiteralExpr)
|| ! (be2.getLeft() instanceof FieldAccessExpr)
|| ! ((e = getExpressionFromStmt(n.getThenStmt())) instanceof MethodCallExpr)
|| ! (((MethodCallExpr)e).getNameAsString()).equals("throwFeatMissing")) {
reportDeletedCheckModified("The featOkTst was modified:\n" + n.toString() + '\n');
}
BlockStmt parent = (BlockStmt) n.getParentNode().get();
stmts = parent.getStatements();
stmts.set(stmts.indexOf(n), new EmptyStmt()); //dont remove
// otherwise iterators fail
// parent.getStmts().remove(n);
return;
}
} while (false);
super.visit(n, ignore);
}
/**
* visitor for method calls
*/
@Override
public void visit(MethodCallExpr n, Object ignore) {
Optional<Node> p1, p2, p3 = null;
Node updatedNode = null;
NodeList<Expression> args;
do {
if (get_set_method == null) break;
/** remove checkArraybounds statement **/
if (n.getNameAsString().equals("checkArrayBounds") &&
((p1 = n.getParentNode()).isPresent() && p1.get() instanceof ExpressionStmt) &&
((p2 = p1.get().getParentNode()).isPresent() && p2.get() instanceof BlockStmt) &&
((p3 = p2.get().getParentNode()).isPresent() && p3.get() == get_set_method)) {
NodeList<Statement> stmts = ((BlockStmt)p2.get()).getStatements();
stmts.set(stmts.indexOf(p1.get()), new EmptyStmt());
return;
}
// convert simpleCore expression ll_get/setRangeValue
boolean useGetter = isGetter || isArraySetter;
if (n.getNameAsString().startsWith("ll_" + (useGetter ? "get" : "set") + rangeNameV2Part + "Value")) {
args = n.getArguments();
if (args.size() != (useGetter ? 2 : 3)) break;
String suffix = useGetter ? "Nc" : rangeNamePart.equals("Feature") ? "NcWj" : "Nfc";
String methodName = "_" + (useGetter ? "get" : "set") + rangeNamePart + "Value" + suffix;
args.remove(0); // remove the old addr arg
// arg 0 converted when visiting args FieldAccessExpr
n.setScope(null);
n.setName(methodName);
}
// convert array sets/gets
String z = "ll_" + (isGetter ? "get" : "set");
String nname = n.getNameAsString();
if (nname.startsWith(z) &&
nname.endsWith("ArrayValue")) {
String s = nname.substring(z.length());
s = s.substring(0, s.length() - "Value".length()); // s = "ShortArray", etc.
if (s.equals("RefArray")) s = "FSArray";
if (s.equals("IntArray")) s = "IntegerArray";
EnclosedExpr ee = new EnclosedExpr(
new CastExpr(new ClassOrInterfaceType(s), n.getArguments().get(0)));
n.setScope(ee); // the getter for the array fs
n.setName(isGetter ? "get" : "set");
n.getArguments().remove(0);
}
/** remove ll_getFSForRef **/
/** remove ll_getFSRef **/
if (n.getNameAsString().equals("ll_getFSForRef") ||
n.getNameAsString().equals("ll_getFSRef")) {
updatedNode = replaceInParent(n, n.getArguments().get(0));
}
} while (false);
if (updatedNode != null) {
updatedNode.accept(this, null);
} else {
super.visit(n, null);
}
}
/**
* visitor for field access expressions
* - convert ((...type_Type)jcasType).casFeatCode_XXXX to _FI_xxx
* @param n -
* @param ignore -
*/
@Override
public void visit(FieldAccessExpr n, Object ignore) {
Expression e;
Optional<Expression> oe;
String nname = n.getNameAsString();
if (get_set_method != null) {
if (nname.startsWith("casFeatCode_") &&
((oe = n.getScope()).isPresent()) &&
((e = getUnenclosedExpr(oe.get())) instanceof CastExpr) &&
("jcasType".equals(getName(((CastExpr)e).getExpression())))) {
String featureName = nname.substring("casFeatCode_".length());
replaceInParent(n, new NameExpr("_FI_" + featureName)); // repl last in List<Expression> (args)
return;
} else if (nname.startsWith("casFeatCode_")) {
reportMigrateFailed("Found field casFeatCode_ ... without a previous cast expr using jcasType");
}
}
super.visit(n, ignore);
}
private class removeEmptyStmts extends VoidVisitorAdapter<Object> {
@Override
public void visit(BlockStmt n, Object ignore) {
Iterator<Statement> it = n.getStatements().iterator();
while (it.hasNext()) {
if (it.next() instanceof EmptyStmt) {
it.remove();
}
}
super.visit(n, ignore);
}
// @Override
// public void visit(MethodDeclaration n, Object ignore) {
// if (n.getNameAsString().equals("getModifiablePrimitiveNodes")) {
// System.out.println("debug");
// }
// super.visit(n, ignore);
// if (n.getNameAsString().equals("getModifiablePrimitiveNodes")) {
// System.out.println("debug");
// }
// }
}
/**
* converted files:
* java name, path (sorted by java name, v3 name only)
* not-converted:
* java name, path (sorted by java name)
* duplicates:
* java name, path (sorted by java name)
* @return true if it's likely everything converted OK.
*/
private boolean report() {
System.out.println("\n\nMigration Summary");
System.out.format("Output top directory: %s%n", outputDirectory);
System.out.format("Date/time: %tc%n", new Date());
pprintRoots("Sources", sourcesRoots);
pprintRoots("Classes", classesRoots);
boolean isOk2 = true;
try {
// these reports, if non-empty items, imply something needs manual checking, so reset isOk2
isOk2 = reportPaths("Workaround Directories", "workaroundDir.txt", pathWorkaround) && isOk2;
isOk2 = reportPaths("Reports of converted files where a deleted check was customized", "deletedCheckModified.txt", deletedCheckModified) && isOk2;
isOk2 = reportPaths("Reports of converted files needing manual inspection", "manualInspection.txt", manualInspection) && isOk2;
isOk2 = reportPaths("Reports of files which failed migration", "failed.txt", failedMigration) && isOk2;
isOk2 = reportPaths("Reports of non-JCas files", "NonJCasFiles.txt", nonJCasFiles) && isOk2;
isOk2 = reportPaths("Builtin JCas classes - skipped - need manual checking to see if they are modified",
"skippedBuiltins.txt", skippedBuiltins) && isOk2;
// these reports, if non-empty, do not imply OK issues
reportPaths("Reports of updated Jars", "jarFileUpdates.txt", jarClassReplace);
reportPaths("Reports of updated PEARs", "pearFileUpdates.txt", pearClassReplace);
// computeDuplicates();
// reportPaths("Report of duplicates - not identical", "nonIdenticalDuplicates.txt", nonIdenticalDuplicates);
// reportPaths("Report of duplicates - identical", "identicalDuplicates.txt", identicalDuplicates);
// isOk2 = reportDuplicates() && isOk2; // false if non-identical duplicates
return isOk2;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void pprintRoots(String kind, Container[] roots) {
if (roots.length > 0) {
try {
try (BufferedWriter bw = Files.newBufferedWriter(makePath(outDirLog + "ItemsProcessed"), StandardOpenOption.CREATE)) {
logPrintNl(kind + " Roots:", bw);
indent[0] += 2;
try {
for (Container container : roots) {
pprintContainer(container, bw);
}
logPrintNl("", bw);
} finally {
indent[0] -= 2;
}
}
} catch (IOException e) {
throw new UIMARuntimeException(e);
}
}
}
private void pprintContainer(Container container, BufferedWriter bw) throws IOException {
logPrintNl(container.toString(), bw);
if (container.subContainers.size() > 1) {
logPrintNl("", bw);
indent[0] += 2;
for (Container subc : container.subContainers) {
pprintContainer(subc, bw);
}
}
}
// private void computeDuplicates() {
// List<ClassnameAndPath> toCheck = new ArrayList<>(c2ps);
// toCheck.addAll(extendableBuiltins);
// sortReport2(toCheck);
// ClassnameAndPath prevP = new ClassnameAndPath(null, null);
// List<ClassnameAndPath> sameList = new ArrayList<>();
// boolean areAllEqual = true;
//
// for (ClassnameAndPath p : toCheck) {
// if (!p.getFirst().equals(prevP.getFirst())) {
//
// addToIdenticals(sameList, areAllEqual);
// sameList.clear();
// areAllEqual = true;
//
// prevP = p;
// continue;
// }
//
// // have 2nd or subsequent same class
// if (sameList.size() == 0) {
// sameList.add(prevP);
// }
// sameList.add(p);
// if (areAllEqual) {
// if (isFilesMiscompare(p.path, prevP.path)) {
// areAllEqual = false;
// }
// }
// }
//
// addToIdenticals(sameList, areAllEqual);
// }
// /**
// * Compare two java source or class files
// * @param p1
// * @param p2
// * @return
// */
// private boolean isFilesMiscompare(Path p1, Path p2) {
// String s1 = (p1);
// String s2 = (p2);
// return !s1.equals(s2);
// }
// private void addToIdenticals(List<ClassnameAndPath> sameList, boolean areAllEqual) {
// if (sameList.size() > 0) {
// if (areAllEqual) {
// identicalDuplicates.addAll(sameList);
// } else {
// nonIdenticalDuplicates.addAll(sameList);
// }
// }
// }
/**
*
* @param name
* @return a path made from name, with directories created
* @throws IOException
*/
private Path makePath(String name) throws IOException {
Path p = Paths.get(name);
Path parent = p.getParent(); // all the parts of the path up to the final segment
if (parent == null) {
return p;
}
try {
Files.createDirectories(parent);
} catch (FileAlreadyExistsException e) { // parent already exists but is not a directory!
// caused by running on Windows system which ignores "case"
// there's a file at /x/y/ named "z", but the path wants to be /x/y/Z/
// Workaround: change "z" to "z_c" c for capitalization issue
current_container.haveDifferentCapitalizedNamesCollidingOnWindows = true;
Path fn = parent.getFileName();
if (fn == null) {
throw new IllegalArgumentException();
}
String newDir = fn.toString() + "_c";
Path parent2 = parent.getParent();
Path p2 = parent2 == null ? Paths.get(newDir) : Paths.get(parent2.toString(), newDir);
try {
Files.createDirectories(p2);
} catch (FileAlreadyExistsException e2) { // parent already exists but is not a directory!
throw new RuntimeException(e2);
}
reportPathWorkaround(parent.toString(), p2.toString());
Path lastPartOfPath = p.getFileName();
if (null == lastPartOfPath) throw new RuntimeException();
return Paths.get(p2.toString(), lastPartOfPath.toString());
}
return p;
}
private void logPrint(String msg, Writer bw) throws IOException {
System.out.print(msg);
bw.write(msg);
}
private void logPrintNl(String msg, Writer bw) throws IOException {
logPrint(msg, bw);
logPrint(Misc.ls, bw);
}
/**
* prints "There were no xxx" if there are no items.
* prints a title, followed by a ================== underneath it
*
* prints a sorted report of two fields.
*
* @param title title of report
* @param fileName file name to save the report in (as well as print to sysout
* @param items the set of items to report on-
* @return true if items were empty
* @throws IOException -
*/
private <T, U> boolean reportPaths(String title, String fileName, List<? extends Report2<T, U>> items) throws IOException {
if (items.size() == 0) {
System.out.println("There were no " + title);
return true;
}
System.out.println("\n" + title);
for (int i = 0; i < title.length(); i++) System.out.print('=');
System.out.println("");
try (BufferedWriter bw = Files.newBufferedWriter(makePath(outDirLog + fileName), StandardOpenOption.CREATE)) {
List<Report2<T, U>> sorted = new ArrayList<>(items);
sortReport2(sorted);
int max = 0;
int nbrFirsts = 0;
Object prevFirst = null;
for (Report2<T, U> p : sorted) {
max = Math.max(max, p.getFirstLength());
Comparable<T> first = p.getFirst();
if (first != prevFirst) {
prevFirst = first;
nbrFirsts ++;
}
}
/**
* Two styles.
* Style 1: where nbrFirst <= 25% nbr: first on separate line, seconds indented
* Style 2: firsts and seconds on same line.
*/
int i = 1;
boolean style1 = nbrFirsts <= sorted.size() / 4;
prevFirst = null;
for (Report2<T, U> p : sorted) {
if (style1) {
if (prevFirst != p.getFirst()) {
prevFirst = p.getFirst();
logPrintNl(String.format("\n For: %s", p.getFirst()), bw);
}
logPrintNl(String.format(" %5d %s", Integer.valueOf(i), p.getSecond()), bw);
} else {
logPrintNl(String.format("%5d %-" +max+ "s %s", Integer.valueOf(i), p.getFirst(), p.getSecond()), bw);
}
i++;
}
System.out.println("");
} // end of try-with-resources
return false;
}
private boolean isZipFs(Object o) {
// Surprise! sometimes the o is not an instance of FileSystem but is the zipfs anyways
return o.getClass().getName().contains("zipfs"); // java 8 and 9
}
/**
* Sort the items on first, then second
* @param items
*/
private <T, U> void sortReport2(List<? extends Report2<T, U>> items) {
Collections.sort(items,
(o1, o2) -> {
int r = protectedCompare(o1.getFirst(), o2.getFirst());
if (r == 0) {
r = protectedCompare(o1.getSecond(), o2.getSecond());
}
return r;
});
}
/**
* protect against comparing zip fs with non-zip fs - these are not comparable to each other in IBM Java 8
* @return -
*/
private <T> int protectedCompare(Comparable<T> comparable, Comparable<T> comparable2) {
//debug
try {
if (isZipFs(comparable)) {
if (isZipFs(comparable2)) {
return comparable.compareTo((T) comparable2); // both zip
} else {
return 1;
}
} else {
if (isZipFs(comparable2)) {
return -1;
} else {
return comparable.compareTo((T) comparable2); // both not zip
}
}
} catch (ClassCastException e) {
//debug
System.out.format("Internal error: c1: %b c2: %b%n c1: %s%n c2: %s%n", isZipFs(comparable), isZipFs(comparable2), comparable.getClass().getName(), comparable2.getClass().getName());
throw e;
}
}
/**
* Called only for top level roots. Sub containers recurse getCandidates_processFile2.
*
* Walk the directory tree rooted at root
* - descend subdirectories
* - descend Jar file
* -- descend nested Jar files (!)
* by extracting these to a temp dir, and keeping a back reference to where they were extracted from.
*
* output the paths representing the classes to migrate:
* classes having a _Type partner
* excluding things other than .java or .classes, and excluding anything with "$" in the name
* - the path includes the "file system".
* @param root
* @throws IOException
*/
private void getAndProcessCandidatesInContainer(Container container) {
// current_paths2RootIds = top_paths2RootIds; // don't do lower, that's called within Jars etc.
try (Stream<Path> stream = Files.walk(container.root, FileVisitOption.FOLLOW_LINKS)) { // needed to release file handles
stream.forEachOrdered(
// only puts into the RootIds possible Fqcn (ending in either .class or .java)
p -> getCandidates_processFile2(p, container));
} catch (IOException e) {
throw new RuntimeException(e);
}
// walk from root container, remove items not JCas candidates
// prunes empty rootIds and subContainer nodes
removeNonJCas(container);
if (container.candidates.size() == 0) { // above call might remove all candidates
Container parent = container.parent;
if (parent != null) {
// System.out.println("No Candidates found in scanned container ending in " +
// container.rootOrig.getFileName().toString());
// // debug
// System.out.println("debug: " + container.rootOrig.toString());
parent.subContainers.remove(container);
}
return;
}
si(psb).append("Migrating JCas files ");
psb.append( container.isJar
? "in Jar: "
: container.isPear
? "in Pear: "
: "from root: ");
psb.append(container.rootOrig);
indent[0] += 2;
si(psb);
flush(psb);
try {
for (Path path : container.candidates) {
CommonConverted cc = getSource(path, container);
// migrate checks to see if already done, outputs a "." or some other char for the candidate
migrate(cc, container, path);
//defer any compilation to container level
if ((itemCount % 50) == 0) {
psb.append(" ").append(itemCount);
si(psb);
flush(psb);
}
itemCount++;
}
psb.append(" ").append(itemCount - 1);
flush(psb);
if (isSource) {
return; // done
}
if (!isSource &&
!container.haveDifferentCapitalizedNamesCollidingOnWindows &&
javaCompiler != null) {
boolean somethingCompiled = compileV3SourcesCommon2(container);
if (container.isPear || container.isJar) {
if (somethingCompiled) {
postProcessPearOrJar(container);
}
}
return;
}
unableToCompile = true;
return; // unable to do post processing or compiling
} finally {
indent[0] -= 2;
}
}
// removes from rootId-lists nonJCas candidates
// if non left, removes that root-id from the root-id lists
// recursion on subContainers.
// for each subContainer, if it ends up empty (no rootIds, no subContainers) removes it
private void removeNonJCas(Container container) {
Iterator<Path> it = container.candidates.iterator();
while (it.hasNext()) {
String candidate = it.next().toString();
// remove non JCas classes
// //debug
// System.out.println("debug, testing to remove: " + candidate);
// if (candidate.indexOf("Corrected") >= 0) {
// if (!container._Types.contains(candidate)) {
// System.out.println("debug dumping _Types map keys to see why ... Corrected.class not there");
// System.out.println("debug key is=" + candidate);
// System.out.println("keys are:");
// int i = 0;
// for (String k : container._Types) {
// if (i == 4) {
// i = 0;
// System.out.println("");
// }
// System.out.print(k + ", ");
// }
// } else {
// System.out.println("debug container._Types did contain " + candidate);
// }
// }
if (!container._Types.contains(candidate)) {
it.remove();
}
}
}
/**
* Called from Stream walker starting at a root or starting at an imbedded Jar or Pear.
*
* adds all the .java or .class files to the candidates, including _Type if not skipping the _Type check
*
* Handling embedded jar files
* - single level Jar (at the top level of the default file system)
* -- handle using an overlayed file system
* - embedded Jars within Jars:
* - not supported by Zip File System Provider (it only supports one level)
* - handle by extracting to a temp dir, and then using the Zip File System Provider
*
* For PEARs, check for and disallow nested PEARs; install the PEAR, set the pear classpath for
* recursive processing with the Pear.
*
* For Jar and PEAR files, use local variable + recursive call to update current_paths2RootIds map
* to new one for the Jar / Pear, and then process recursiveloy
*
* @param path the path to a .java or .class or .jar or .pear that was walked to
* @param pearClasspath - a string representing a path to the pear's classpath if there is one, or null
* @param container the container for the
* - rootIds (which have the JCas candidates) and
* - subContainers for imbedded Pears and Jars
*/
private void getCandidates_processFile2(Path path, Container container) {
String pathString = path.toString();
final boolean isPear = pathString.endsWith(".pear"); // path.endsWith does not mean this !!
final boolean isJar = pathString.endsWith(".jar");
if (isPear || isJar) {
Container subc = new Container(container, path);
getAndProcessCandidatesInContainer(subc);
return;
}
if (pathString.endsWith(isSource ? ".java" : ".class")) {
// Skip candidates except .java or .class
addToCandidates(path, container);
}
}
/**
* if _Type kind, add artifactId to set kept in current rootIdContainer
* If currently scanning within a PEAR,
* record 2-way map from unzipped path to internal path inside pear
* Used when doing pear reassembly.
*
* If currently scanning within a Jar or a PEAR,
* add unzipped path to list of all subparts for containing Jar or PEAR
* These paths are used as unique ids to things needing to be replaced in the Jar or PEAR,
* when doing re-assembly. For compiled classes migration, only, since source migration
* doesn't do re-assembly.
*
* @param path
* @param pearClassPath
*/
private void addToCandidates(Path path, Container container) {
String ps = path.toString();
if (ps.endsWith(isSource ? "_Type.java" : "_Type.class")) {
container._Types.add(isSource
? (ps.substring(0, ps.length() - 10) + ".java")
: (ps.substring(0, ps.length() - 11) + ".class"));
// if (container.isJar) {
// System.out.println("debug add container._Types " + Paths.get(ps.substring(0, ps.length() - 11)).toString() + ".class".toString() + " for Jar " + container.rootOrig.getFileName().toString());
// }
return;
}
if (ps.contains("$")) {
return; // don't add these kinds of things, they're not JCas classes
}
//debug
// if (container.isJar) {
// System.out.println("debug add candidate " + path.toString() + " for Jar " + container.rootOrig.getFileName().toString());
// }
container.candidates.add(path);
}
/**
* For Jars inside other Jars, we copy the Jar to a temp spot in the default file system
* Extracted Jar is marked delete-on-exit
*
* @param path embedded Jar to copy (only the last name is used, in constructing the temp dir)
* @return a temporary file in the local temp directory that is a copy of the Jar
* @throws IOException -
*/
private static Path getTempOutputPathForJar(Path path) throws IOException {
Path localTempDir = getTempDir();
if (path == null ) {
throw new IllegalArgumentException();
}
Path fn = path.getFileName();
if (fn == null) {
throw new IllegalArgumentException();
}
Path tempPath = Files.createTempFile(localTempDir, fn.toString(), "");
tempPath.toFile().deleteOnExit();
return tempPath;
}
private static Path getTempDir() throws IOException {
if (tempDir == null) {
tempDir = Files.createTempDirectory("migrateJCas");
tempDir.toFile().deleteOnExit();
}
return tempDir;
}
private static final CommandLineParser createCmdLineParser() {
CommandLineParser parser = new CommandLineParser();
parser.addParameter(SOURCE_FILE_ROOTS, true);
parser.addParameter(CLASS_FILE_ROOTS, true);
parser.addParameter(OUTPUT_DIRECTORY, true);
// parser.addParameter(SKIP_TYPE_CHECK, false);
parser.addParameter(MIGRATE_CLASSPATH, true);
// parser.addParameter(CLASSES, true);
return parser;
}
private final boolean checkCmdLineSyntax(CommandLineParser clp) {
if (clp.getRestArgs().length > 0) {
System.err.println("Error parsing CVD command line: unknown argument(s):");
String[] args = clp.getRestArgs();
for (int i = 0; i < args.length; i++) {
System.err.print(" ");
System.err.print(args[i]);
}
System.err.println();
return false;
}
if (clp.isInArgsList(SOURCE_FILE_ROOTS) && clp.isInArgsList(CLASS_FILE_ROOTS)) {
System.err.println("both sources file roots and classess file roots parameters specified; please specify just one.");
return false;
}
if (clp.isInArgsList(OUTPUT_DIRECTORY)) {
outputDirectory = Paths.get(clp.getParamArgument(OUTPUT_DIRECTORY)).toString();
if (!outputDirectory.endsWith("/")) {
outputDirectory = outputDirectory + "/";
}
} else {
try {
outputDirectory = Files.createTempDirectory("migrateJCasOutput").toString() + "/";
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
outDirConverted = outputDirectory + "converted/";
outDirSkipped = outputDirectory + "not-converted/";
outDirLog = outputDirectory + "logs/";
if (clp.isInArgsList(MIGRATE_CLASSPATH)) {
migrateClasspath = clp.getParamArgument(MIGRATE_CLASSPATH);
} else {
if (clp.isInArgsList(CLASS_FILE_ROOTS)) {
System.err.println("WARNING: classes file roots is specified, but the\n"
+ " migrateClasspath parameter is missing\n");
}
}
// if (clp.isInArgsList(CLASSES)) {
// individualClasses = clp.getParamArgument(CLASSES);
// }
return true;
}
// called to decompile a string of bytes.
// - first get the class name (fully qualified)
// and skip decompiling if already decompiled this class
// for this pearClasspath
// - this handles multiple class definitions, insuring
// only one decompile happens per pearClasspath (including null)
/**
* Caller does any caching to avoid this method.
*
* @param b bytecode to decompile
* @param pearClasspath to prepend to the classpath
* @return
*/
private String decompile(byte[] b, String pearClasspath) {
badClassName = false;
String classNameWithSlashes = Misc.classNameFromByteCode(b);
packageAndClassNameSlash = classNameWithSlashes;
ClassLoader cl = getClassLoader(pearClasspath);
UimaDecompiler ud = new UimaDecompiler(cl, null);
if (classNameWithSlashes == null || classNameWithSlashes.length() < 2) {
System.err.println("Failed to extract class name from binary code, "
+ "name found was \"" + ((classNameWithSlashes == null) ? "null" : classNameWithSlashes)
+ "\"\n byte array was:");
System.err.println(Misc.dumpByteArray(b, 2000));
badClassName = true;
}
return ud.decompileToString(classNameWithSlashes, b);
}
/**
* The classloader to use in decompiling, if it is provided, is one that delegates first
* to the parent. This may need fixing for PEARs
* @return classloader to use for migrate decompiling
*/
private ClassLoader getClassLoader(String pearClasspath) {
if (null == pearClasspath) {
if (null == cachedMigrateClassLoader) {
cachedMigrateClassLoader = (null == migrateClasspath)
? this.getClass().getClassLoader()
: new UIMAClassLoader(Misc.classpath2urls(migrateClasspath));
}
return cachedMigrateClassLoader;
} else {
try {
return new UIMAClassLoader((null == migrateClasspath)
? pearClasspath
: (pearClasspath + File.pathSeparator + migrateClasspath));
} catch (MalformedURLException e) {
throw new UIMARuntimeException(e);
}
}
}
private void addImport(String s) {
cu.getImports().add(new ImportDeclaration(new Name(s), false, false));
}
private void removeImport(String s) {
Iterator<ImportDeclaration> it = cu.getImports().iterator();
while (it.hasNext()) {
ImportDeclaration impDcl = it.next();
if (impDcl.getNameAsString().equals(s)) {
it.remove();
break;
}
}
}
/******************
* AST Utilities
******************/
private Node replaceInParent(Node n, Expression v) {
Optional<Node> maybeParent = n.getParentNode();
if (maybeParent.isPresent()) {
Node parent = n.getParentNode().get();
if (parent instanceof EnclosedExpr) {
((EnclosedExpr)parent).setInner(v);
} else if (parent instanceof MethodCallExpr) { // args in the arg list
List<Expression> args = ((MethodCallExpr)parent).getArguments();
args.set(args.indexOf(n), v);
v.setParentNode(parent);
} else if (parent instanceof ExpressionStmt) {
((ExpressionStmt)parent).setExpression(v);
} else if (parent instanceof CastExpr) {
((CastExpr)parent).setExpression(v);
} else if (parent instanceof ReturnStmt) {
((ReturnStmt)parent).setExpression(v);
} else if (parent instanceof AssignExpr) {
((AssignExpr)parent).setValue(v);
} else if (parent instanceof VariableDeclarator) {
((VariableDeclarator)parent).setInitializer(v);
} else if (parent instanceof ObjectCreationExpr) {
List<Expression> args = ((ObjectCreationExpr)parent).getArguments();
int i = args.indexOf(n);
if (i < 0) throw new RuntimeException();
args.set(i, v);
} else {
System.out.println(parent.getClass().getName());
throw new RuntimeException();
}
return v;
}
System.out.println("internal error replacing in parent: no parent for node: " + n.getClass().getName());
System.out.println(" node: " + n.toString());
System.out.println(" expression replacing: " + v.toString());
throw new RuntimeException();
}
/**
*
* @param p the parameter to modify
* @param t the name of class or interface
* @param name the name of the variable
*/
private void setParameter(List<Parameter> ps, int i, String t, String name) {
Parameter p = ps.get(i);
p.setType(new ClassOrInterfaceType(t));
p.setName(new SimpleName(name));
}
private int findConstructor(NodeList<BodyDeclaration<?>> classMembers) {
int i = 0;
for (BodyDeclaration<?> bd : classMembers) {
if (bd instanceof ConstructorDeclaration) {
return i;
}
i++;
}
return -1;
}
private boolean hasTypeFields(NodeList<BodyDeclaration<?>> members) {
boolean hasType = false;
boolean hasTypeId = false;
for (BodyDeclaration<?> bd : members) {
if (bd instanceof FieldDeclaration) {
FieldDeclaration f = (FieldDeclaration)bd;
EnumSet<Modifier> m = f.getModifiers();
if (m.contains(Modifier.PUBLIC) &&
m.contains(Modifier.STATIC) &&
m.contains(Modifier.FINAL)
// &&
// getTypeName(f.getType()).equals("int")
) {
List<VariableDeclarator> vds = f.getVariables();
for (VariableDeclarator vd : vds) {
if (vd.getType().equals(intType)) {
String n = vd.getNameAsString();
if (n.equals("type")) hasType = true;
if (n.equals("typeIndexID")) hasTypeId = true;
if (hasTypeId && hasType) {
return true;
}
}
}
}
}
} // end of for
return false;
}
/**
* Heuristic:
* JCas classes have 0, 1, and 2 arg constructors with particular arg types
* 0 -
* 1 - JCas
* 2 - int, TOP_Type (v2) or TypeImpl, CASImpl (v3)
*
* Additional 1 and 2 arg constructors are permitted.
*
* Sets fields hasV2Constructors, hasV3Constructors
* @param members
*/
private void setHasJCasConstructors(NodeList<BodyDeclaration<?>> members) {
boolean has0ArgConstructor = false;
boolean has1ArgJCasConstructor = false;
boolean has2ArgJCasConstructorV2 = false;
boolean has2ArgJCasConstructorV3 = false;
for (BodyDeclaration<?> bd : members) {
if (bd instanceof ConstructorDeclaration) {
List<Parameter> ps = ((ConstructorDeclaration)bd).getParameters();
if (ps.size() == 0) has0ArgConstructor = true;
if (ps.size() == 1 && getParmTypeName(ps, 0).equals("JCas")) {
has1ArgJCasConstructor = true;
}
if (ps.size() == 2) {
if (getParmTypeName(ps, 0).equals("int") &&
getParmTypeName(ps, 1).equals("TOP_Type")) {
has2ArgJCasConstructorV2 = true;
} else if (getParmTypeName(ps, 0).equals("TypeImpl") &&
getParmTypeName(ps, 1).equals("CASImpl")) {
has2ArgJCasConstructorV3 = true;
}
} // end of 2 arg constructor
} // end of is-constructor
} // end of for loop
hasV2Constructors = has0ArgConstructor && has1ArgJCasConstructor && has2ArgJCasConstructorV2;
hasV3Constructors = has0ArgConstructor && has1ArgJCasConstructor && has2ArgJCasConstructorV3;
}
private String getParmTypeName(List<Parameter> p, int i) {
return getTypeName(p.get(i).getType());
}
private String getTypeName(Type t) {
// if (t instanceof ReferenceType) {
// t = ((ReferenceType<?>)t).getType();
// }
if (t instanceof PrimitiveType) {
return ((PrimitiveType)t).toString();
}
if (t instanceof ClassOrInterfaceType) {
return ((ClassOrInterfaceType)t).getNameAsString();
}
Misc.internalError(); return null;
}
/**
* Get the name of a field
* @param e -
* @return the field name or null
*/
private String getName(Expression e) {
e = getUnenclosedExpr(e);
if (e instanceof NameExpr) {
return ((NameExpr)e).getNameAsString();
}
if (e instanceof FieldAccessExpr) {
return ((FieldAccessExpr)e).getNameAsString();
}
return null;
}
/**
* Called on Annotation Decl, Class/intfc decl, empty type decl, enum decl
* Does nothing unless at top level of compilation unit
*
* Otherwise, adds an entry to c2ps for the classname and package, plus full path
*
* @param n type being declared
*/
private void updateClassName(TypeDeclaration<?> n) {
Optional<Node> pnode = n.getParentNode();
Node node;
if (pnode.isPresent() &&
(node = pnode.get()) instanceof CompilationUnit) {
CompilationUnit cu2 = (CompilationUnit) node;
className = cu2.getType(0).getNameAsString();
String packageAndClassName =
(className.contains("."))
? className
: packageName + '.' + className;
packageAndClassNameSlash = packageAndClassName.replace('.', '/');
// assert current_cc.fqcn_slash == null; // for decompiling, already set
assert (current_cc.fqcn_slash != null) ? current_cc.fqcn_slash.equals(packageAndClassNameSlash) : true;
current_cc.fqcn_slash = packageAndClassNameSlash;
TypeImpl ti = TypeSystemImpl.staticTsi.getType(Misc.javaClassName2UimaTypeName(packageAndClassName));
if (null != ti) {
// // is a built-in type
// ClassnameAndPath p = new ClassnameAndPath(
// packageAndClassNameSlash,
// current_cc.,
// current_cc.pearClasspath);
skippedBuiltins.add(new PathAndReason(current_path, "built-in"));
isBuiltinJCas = true;
isConvert2v3 = false;
return;
}
return;
}
return;
}
private Expression getExpressionFromStmt(Statement stmt) {
stmt = getStmtFromStmt(stmt);
if (stmt instanceof ExpressionStmt) {
return getUnenclosedExpr(((ExpressionStmt)stmt).getExpression());
}
return null;
}
private Expression getUnenclosedExpr(Expression e) {
while (e instanceof EnclosedExpr) {
e = ((EnclosedExpr)e).getInner().get();
}
return e;
}
/**
* Unwrap (possibly nested) 1 statement blocks
* @param stmt -
* @return unwrapped (non- block) statement
*/
private Statement getStmtFromStmt(Statement stmt) {
while (stmt instanceof BlockStmt) {
NodeList<Statement> stmts = ((BlockStmt) stmt).getStatements();
if (stmts.size() == 1) {
stmt = stmts.get(0);
continue;
}
return null;
}
return stmt;
}
private void addCastExpr(Statement stmt, Type castType) {
ReturnStmt rstmt = (ReturnStmt) stmt;
Optional<Expression> o_expr = rstmt.getExpression();
Expression expr = o_expr.isPresent() ? o_expr.get() : null;
CastExpr ce = new CastExpr(castType, expr);
rstmt.setExpression(ce); // removes the parent link from expr
if (expr != null) {
expr.setParentNode(ce); // restore it
}
}
/********************
* Recording results
********************/
private void recordBadConstructor(String msg) {
reportMigrateFailed("Constructor is incorrect, " + msg);
}
// private void reportParseException() {
// reportMigrateFailed("Unparsable Java");
// }
private void migrationFailed(String reason) {
failedMigration.add(new PathAndReason(current_path, reason));
isConvert2v3 = false;
}
private void reportMigrateFailed(String m) {
System.out.format("Skipping this file due to error: %s, path: %s%n", m, current_path);
migrationFailed(m);
}
private void reportV2Class() {
// v2JCasFiles.add(current_path);
isV2JCas = true;
}
private void reportV3Class() {
// v3JCasFiles.add(current_path);
isConvert2v3 = true;
}
private void reportNotJCasClass(String reason) {
nonJCasFiles.add(new PathAndReason(current_path, reason));
isConvert2v3 = false;
}
private void reportNotJCasClassMissingTypeFields() {
reportNotJCasClass("missing required type and/or typeIndexID static fields");
}
private void reportDeletedCheckModified(String m) {
deletedCheckModified.add(new PathAndReason(current_path, m));
}
private void reportMismatchedFeatureName(String m) {
manualInspection.add(new PathAndReason(current_path, "This getter/setter name doesn't match internal feature name: " + m));
}
private void reportUnrecognizedV2Code(String m) {
migrationFailed("V2 code not recognized:\n" + m);
}
private void reportPathWorkaround(String orig, String modified) {
pathWorkaround.add(new String1AndString2(orig, modified));
}
private void reportPearOrJarClassReplace(String pearOrJar, String classname, Container kind) { // pears or jars
if (kind.isPear) {
pearClassReplace.add(new String1AndString2(pearOrJar, classname));
} else {
jarClassReplace.add(new String1AndString2(pearOrJar, classname));
}
}
/***********************************************/
/**
* Output directory for source and migrated files
* Consisting of converted/skipped, v2/v3, a+cc.id, slashified classname
* @param cc -
* @param isV2 -
* @param wasConverted -
* @return converted/skipped, v2/v3, a+cc.id, slashified classname
*/
private String getBaseOutputPath(CommonConverted cc, boolean isV2, boolean wasConverted) {
StringBuilder sb = new StringBuilder();
sb.append(wasConverted ? outDirConverted : outDirSkipped);
sb.append(isV2 ? "v2/" : "v3/");
sb.append("a").append(cc.getId()).append('/');
sb.append(cc.fqcn_slash).append(".java");
return sb.toString();
}
private void writeV2Orig(CommonConverted cc, boolean wasConverted) throws IOException {
String base = getBaseOutputPath(cc, true, wasConverted); // adds numeric suffix if dupls
FileUtils.writeToFile(makePath(base), cc.v2Source);
}
private void writeV3(CommonConverted cc) throws IOException {
String base = getBaseOutputPath(cc, false, true);
cc.v3SourcePath = makePath(base);
String data = fixImplementsBug(cc.v3Source);
FileUtils.writeToFile(cc.v3SourcePath, data);
}
private void printUsage() {
System.out.println(
"Usage: java org.apache.uima.migratev3.jcas.MigrateJCas \n"
+ " [-sourcesRoots <One-or-more-directories-or-jars-separated-by-Path-separator>]\n"
+ " [-classesRoots <One-or-more-directories-or-jars-or-pears-separated-by-Path-separator>]\n"
+ " [-outputDirectory a-writable-directory-path (optional)\n"
+ " if omitted, a temporary directory is used\n"
+ " [-migrateClasspath a-class-path to use in decompiling, when -classesRoots is specified\n"
+ " also used when compiling the migrated classes.\n"
+ " NOTE: either -sourcesRoots or -classesRoots is required, but only one may be specified.\n"
+ " NOTE: classesRoots are scanned for JCas classes, which are then decompiled, and the results processed like sourcesRoots\n"
);
}
private static final Pattern implementsEmpty = Pattern.compile("implements \\{");
private String fixImplementsBug(String data) {
return implementsEmpty.matcher(data).replaceAll("{");
}
/*********************************************************************
* Reporting classes
*********************************************************************/
private static abstract class Report2<T, U> {
public abstract Comparable<T> getFirst(); // Eclipse on linux complained if not public, was OK on windows
public abstract Comparable<U> getSecond();
abstract int getFirstLength();
}
private static class PathAndReason extends Report2<Path, String> {
Path path;
String reason;
PathAndReason(Path path, String reason) {
this.path = path;
this.reason = reason;
}
@Override
public Comparable<Path> getFirst() { return path; }
@Override
public Comparable<String> getSecond() { return reason; }
@Override
int getFirstLength() { return path.toString().length(); }
}
private static class String1AndString2 extends Report2<String, String> {
String s1;
String s2;
String1AndString2(String s1, String s2) {
this.s1 = s1;
this.s2 = s2;
}
@Override
public Comparable<String> getFirst() { return s1; }
@Override
public Comparable<String> getSecond() { return s2; }
@Override
int getFirstLength() { return s1.toString().length(); }
}
private static void withIOX(Runnable_withException r) {
try {
r.run();
} catch (Exception e) {
throw new UIMARuntimeException(e);
}
}
private int findFirstCharDifferent(String s1, String s2) {
int s1l = s1.length();
int s2l = s2.length();
for (int i = 0;;i++) {
if (i == s1l || i == s2l) {
return i;
}
if (s1.charAt(i) != s2.charAt(i)) {
return i;
}
}
}
// private String drop_Type(String s) {
// return s.substring(0, isSource ? "_Type.java".length()
// : "_Type.class".length()) +
// (isSource ? ".java" : ".class");
// }
///*****************
//* Root-id
//*****************/
//private static int nextRootId = 1;
//
///***********************************************************************
//* Root-id - this is the path part up to the start of the package name.
//* - it is relative to container
//* - has the collection of artifacts that might be candidates, having this rootId
//* - has the collection of _Type things having this rootId
//* - "null" path is OK - means package name starts immediately
//* There is no Root-id for path ending in Jar or PEAR - these created containers instead
//***********************************************************************/
//private static class RootId {
// final int id = nextRootId++;
// /**
// * The path relative to the the container (if any) (= Jar or Pear)
// * - for Pears, the path is as if it was not installed, but within the PEAR file
// */
// final Path path;
//
// /** The container holding this RootId */
// final Container container;
// /**
// * For this rootId, all of the fully qualified classnames that are migration eligible.
// * - not all might be migrated, if upon further inspection they are not JCas class files.
// */
// final Set<Fqcn> fqcns = new HashSet<>();
// final Set<String> fqcns_ignore_case = new HashSet<>();
// boolean haveDifferentCapitalizedNamesCollidingOnWindows = false;
//
// RootId(Path path, Container container) {
// this.path = path;
// this.container = container;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return "RootId [id="
// + id
// + ", path="
// + path
// + ", container="
// + container.id
// + ", fqcns="
// + Misc.ppList(Misc.setAsList(fqcns))
// + ", fqcns_Type="
// + Misc.ppList(Misc.setAsList(fqcns_Type))
// + "]";
// }
//
// void add(Fqcn fqcn) {
// boolean wasNotPresent = fqcns.add(fqcn);
// boolean lc = fqcns_ignore_case.add(fqcn.fqcn_dots.toLowerCase());
// if (!lc && wasNotPresent) {
// haveDifferentCapitalizedNamesCollidingOnWindows = true;
// }
// }
//
// boolean hasMatching_Type(Fqcn fqcn) {
//
// }
//}
///**
//* Called from Stream walker starting at a root or starting at an imbedded Jar or Pear.
//*
//* adds all the .java or .class files to the candidates, including _Type if not skipping the _Type check
//* Handling embedded jar files
//* - single level Jar (at the top level of the default file system)
//* -- handle using an overlayed file system
//* - embedded Jars within Jars:
//* - not supported by Zip File System Provider (it only supports one level)
//* - handle by extracting to a temp dir, and then using the Zip File System Provider
//* @param path the path to a .java or .class or .jar or .pear
//* @param pearClasspath - a string representing a path to the pear's classpath if there is one, or null
//*/
//private void getCandidates_processFile(Path path, String pearClasspath) {
//// if (path.toString().contains("commons-httpclient-3.1.jar"))
//// System.out.println("Debug: " + path.toString());
//// System.out.println("debug processing " + path);
// try {
//// URI pathUri = path.toUri();
// String pathString = path.toString();
// final boolean isPear = pathString.endsWith(".pear"); // path.endsWith does not mean this !!
// final boolean isJar = pathString.endsWith(".jar");
//
// if (isJar || isPear) {
// if (!path.getFileSystem().equals(FileSystems.getDefault())) {
// // embedded Pear or Jar: extract to temp
// Path out = getTempOutputPathForJar(path);
// Files.copy(path, out, StandardCopyOption.REPLACE_EXISTING);
//// embeddedJars.add(new PathAndPath(path, out));
// path = out; // path points to pear or jar
// }
//
// Path start;
// final String localPearClasspath;
// if (isPear) {
// if (pearClasspath != null) {
// throw new UIMARuntimeException("Nested PEAR files not supported");
// }
//
//// pear_current = new PearOrJar(path);
//// pears.add(pear_current);
// // add pear classpath info
// File pearInstallDir = Files.createTempDirectory(getTempDir(), "installedPear").toFile();
// PackageBrowser ip = PackageInstaller.installPackage(pearInstallDir, path.toFile(), false);
// localPearClasspath = ip.buildComponentClassPath();
// String[] children = pearInstallDir.list();
// if (children == null || children.length != 1) {
// Misc.internalError();
// }
// pearResolveStart = Paths.get(pearInstallDir.getAbsolutePath(), children[0]);
//
// start = pearInstallDir.toPath();
// } else {
// if (isJar) {
// PearOrJar jarInfo = new PearOrJar(path);
// pear_or_jar_current_stack.push(jarInfo);
// jars.add(jarInfo);
// }
//
// localPearClasspath = pearClasspath;
// FileSystem jfs = FileSystems.newFileSystem(Paths.get(path.toUri()), null);
// start = jfs.getPath("/");
// }
//
// try (Stream<Path> stream = Files.walk(start)) { // needed to release file handles
// stream.forEachOrdered(
// p -> getCandidates_processFile(p, localPearClasspath));
// }
// if (isJar) {
// pear_or_jar_current_stack.pop();
// }
// if (isPear) {
// pear_current = null;
// }
// } else {
// // is not a .jar or .pear file. add .java or .class files to initial candidate set
// // will be filtered additionally later
//// System.out.println("debug path ends with java or class " + pathString.endsWith(isSource ? ".java" : ".class") + " " + pathString);
// if (pathString.endsWith(isSource ? ".java" : ".class")) {
// candidates.add(new Candidate(path, pearClasspath));
// if (!isSource && null != pear_current) {
// // inside a pear, which has been unzipped into pearInstallDir;
// path2InsidePearOrJarPath.put(path.toString(), pearResolveStart.relativize(path).toString());
// pear_current.pathsToCandidateFiles.add(path.toString());
// }
//
// if (!isSource && pear_or_jar_current_stack.size() > 0) {
// // inside a jar, not contained in a pear
// pear_or_jar_current_stack.getFirst().pathsToCandidateFiles.add(path.toString());
// }
// }
// }
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//}
//private void postProcessPearsOrJars(String kind, List<PearOrJar> pearsOrJars, List<String1AndString2> classReplace) { // pears or jars
//try {
// Path outDir = Paths.get(outputDirectory, kind);
// FileUtils.deleteRecursive(outDir.toFile());
// Files.createDirectories(outDir);
//} catch (IOException e) {
// throw new RuntimeException(e);
//}
//
//// pearsOrJars may have entries with 0 candidate paths. This happens when we scan them
//// but find nothing to convert.
//// eliminate these.
//
//Iterator<PearOrJar> it = pearsOrJars.iterator();
//while (it.hasNext()) {
// PearOrJar poj = it.next();
// if (poj.pathsToCandidateFiles.size() == 0) {
// it.remove();
// } else {
//// //debug
//// if (poj.pathToPearOrJar.toString().contains("commons-httpclient-3.1")) {
//// System.err.println("debug found converted things inside commons-httpclient");;
//// for (String x : poj.pathsToCandidateFiles) {
//// System.err.println(x);
//// }
//// System.err.println("");
//// }
// }
//}
//
//it = pearsOrJars.iterator();
//while (it.hasNext()) {
// PearOrJar poj = it.next();
// if (poj.pathsToCandidateFiles.size() == 0) {
// System.err.print("debug failed to remove unconverted Jar");
// }
//}
//
//if (pearsOrJars.size() == 0) {
// System.out.format("No .class files were replaced in %s.%n", kind);
//} else {
// System.out.format("replacing .class files in %,d %s%n", pearsOrJars.size(), kind);
// for (PearOrJar p : pearsOrJars) {
// pearOrJarPostProcessing(p, kind);
// }
// try {
// reportPaths("Reports of updated " + kind, kind + "FileUpdates.txt", classReplace);
//
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//}
//
//}
///**
//* When running the compiler to compile v3 sources, we need a classpath that at a minimum
//* includes uimaj-core. The strategy is to use the invoker of this tool's classpath as
//* specified from the application class loader
//* @return true if no errors
//*/
//private boolean compileV3SourcesCommon(List<ClassnameAndPath> items, String msg, String pearClasspath) {
//
// if (items.size() == 0) {
// return true;
// }
// System.out.format("Compiling %,d classes %s -- This may take a while!%n", c2ps.size(), msg);
// StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, Charset.forName("UTF-8"));
//
// List<String> cus = items.stream()
// .map(c -> outDirConverted + "v3/" + c.classname + ".java")
// .collect(Collectors.toList());
//
// Iterable<String> compilationUnitStrings = cus;
//
// Iterable<? extends JavaFileObject> compilationUnits =
// fileManager.getJavaFileObjectsFromStrings(compilationUnitStrings);
//
// // specify where the output classes go
// String classesBaseDir = outDirConverted + "v3-classes";
// try {
// Files.createDirectories(Paths.get(classesBaseDir));
// } catch (IOException e) {
// throw new UIMARuntimeException(e);
// }
// // specify the classpath
// String classpath = getCompileClassPath(pearClasspath);
// Iterable<String> options = Arrays.asList("-d", classesBaseDir,
// "-classpath", classpath);
// return javaCompiler.getTask(null, fileManager, null, options, null, compilationUnits).call();
//}
///**
//* Called after class is migrated
//* Given a path to a class (source or class file),
//* return the URL to the class as found in the classpath.
//* This returns the "first" one found in the classpath, in the case of duplicates.
//* @param path
//* @return the location of the class in the class path
//*/
//private URL getPathForClass(Path path) {
// return (null == packageAndClassNameSlash)
// ? null
// : migrateClassLoader.getResource(packageAndClassNameSlash + ".class");
//}
//private void getBaseOutputPath() {
//String s = packageAndClassNameSlash;
//int i = 0;
//while (!usedPackageAndClassNames.add(s)) {
// i = i + 1;
// s = packageAndClassNameSlash + "_dupid_" + i;
//}
//packageAndClassNameSlash_i = i;
//}
//private String prepareIndividual(String classname) {
//candidate = new Candidate(Paths.get(classname)); // a pseudo path
//packageName = null;
//className = null;
//packageAndClassNameSlash = null;
//cu = null;
//return decompile(classname); // always look up in classpath
// // to decompile individual source - put in sourcesRoots
//}
//if (!isSource) { // skip this recording if source
//if (null != pear_current) {
// // inside a pear, which has been unzipped into a temporary pearInstallDir;
// // we don't want that temporary dir to be part of the path.
// path2InsidePearOrJarPath.put(path.toString(), pearResolveStart.relativize(path).toString());
// pear_current.pathsToCandidateFiles.add(path.toString());
//}
//
//if (!isSource && pear_or_jar_current_stack.size() > 0) {
// // inside a jar, not contained in a pear
// pear_or_jar_current_stack.getFirst().pathsToCandidateFiles.add(path.toString());
//}
//}
//}
///**
//* For a given candidate, use its path:
//* switch the ...java to ..._Type.java, or ...class to ..._Type.class
//* look thru all the candidates
//* @param cand
//* @param start
//* @return
//*/
//private boolean has_Type(Candidate cand, int start) {
// if (start >= candidates.size()) {
// return false;
// }
//
// String sc = cand.p.toString();
// String sc_minus_suffix = sc.substring(0, sc.length() - ( isSource ? ".java".length() : ".class".length()));
// String sc_Type = sc_minus_suffix + ( isSource ? "_Type.java" : "_Type.class");
// // a string which sorts beyond the candidate + a suffix of "_"
// String s_end = sc_minus_suffix + (char) (((int)'_') + 1);
// for (Candidate c : candidates.subList(start, candidates.size())) {
// String s = c.p.toString();
// if (s_end.compareTo(s) < 0) {
// return false; // not found, we're already beyond where it would be found
// }
// if (s.equals(sc_Type)) {
// return true;
// }
// }
// return false;
//}
//private final static Comparator<Candidate> pathComparator = new Comparator<Candidate>() {
//@Override
//public int compare(Candidate o1, Candidate o2) {
// return o1.p.toString().compareTo(o2.p.toString());
//}
//};
//// there may be several same-name roots not quite right
//// xxx_Type$1.class
//
//private void addIfPreviousIsSameName(List<Path> c, int i) {
//if (i == 0) return;
//String _Type = candidates.get(i).toString();
////String prev = r.get(i-1).getPath();
//String prefix = _Type.substring(0, _Type.length() - ("_Type." + (isSource ? "java" : "class")).length());
//i--;
//while (i >= 0) {
// String s = candidates.get(i).toString();
// if ( ! s.startsWith(prefix)) {
// break;
// }
// if (s.substring(prefix.length()).equals((isSource ? ".java" : ".class"))) {
// c.add(candidates.get(i));
// break;
// }
// i--;
//}
//}
//
//for (int i = 0; i < pearOrJar.pathsToCandidateFiles.size(); i++) {
// String candidatePath = pearOrJar.pathsToCandidateFiles.get(i);
// String path_in_v3_classes = isPear
// ? getPath_in_v3_classes(candidatePath)
// : candidatePath;
//
// Path src = Paths.get(outputDirectory, "converted/v3-classes", path_in_v3_classes
// + (isPear ? ".class" : ""));
// Path tgt = pfs.getPath(
// "/",
// isPear
// ? path2InsidePearOrJarPath.get(candidatePath) // needs to be bin/org/... etc
// : candidatePath); // needs to be org/... etc
// if (Files.exists(src)) {
// Files.copy(src, tgt, StandardCopyOption.REPLACE_EXISTING);
// reportPearOrJarClassReplace(pearOrJarCopy.toString(), path_in_v3_classes, kind);
// }
//}
///** for compiled mode, do recompiling and reassembly of Jars and Pears */
//
//private boolean compileAndReassemble(CommonConverted cc, Container container, Path path) {
// boolean noErrors = true;
// if (javaCompiler != null) {
// if (container.haveDifferentCapitalizedNamesCollidingOnWindows) {
// System.out.println("Skipping compiling / reassembly because class " + container.toString() + " has multiple names differing only in capitalization, please resolve first.");
// } else {
//
//
// noErrors = compileV3PearSources(container, path);
// noErrors = noErrors && compileV3NonPearSources(container, path);
//
// postProcessPearsOrJars("jars" , jars , jarClassReplace);
// postProcessPearsOrJars("pears", pears, pearClassReplace);
//
////
//// try {
//// Path pearOutDir = Paths.get(outputDirectory, "pears");
//// FileUtils.deleteRecursive(pearOutDir.toFile());
//// Files.createDirectories(pearOutDir);
//// } catch (IOException e) {
//// throw new RuntimeException(e);
//// }
////
//// System.out.format("replacing .class files in %,d PEARs%n", pears.size());
//// for (PearOrJar p : pears) {
//// pearOrJarPostProcessing(p);
//// }
//// try {
//// reportPaths("Reports of updated Pears", "pearFileUpdates.txt", pearClassReplace);
//// } catch (IOException e) {
//// throw new RuntimeException(e);
//// }
// }
// }
//
// return noErrors;
//}
///**
//* @return true if no errors
//*/
//private boolean compileV3PearSources() {
// boolean noError = true;
// Map<String, List<ClassnameAndPath>> p2c = c2ps.stream()
// .filter(c -> c.pearClasspath != null)
// .collect(Collectors.groupingBy(c -> c.pearClasspath));
//
// List<Entry<String, List<ClassnameAndPath>>> ea = p2c.entrySet().stream()
// .sorted(Comparator.comparing(Entry::getKey)) //(e1, e2) -> e1.getKey().compareTo(e2.getKey())
// .collect(Collectors.toList());
//
// for (Entry<String, List<ClassnameAndPath>> e : ea) {
// noError = noError && compileV3SourcesCommon(e.getValue(), "for Pear " + e.getKey(), e.getKey() );
// }
// return noError;
//}
//
///**
//* @return true if no errors
//*/
//private boolean compileV3NonPearSources() {
//
// List<ClassnameAndPath> cnps = c2ps.stream()
// .filter(c -> c.pearClasspath == null)
// .collect(Collectors.toList());
//
// return compileV3SourcesCommon(cnps, "(non PEAR)", null);
//}
///**
//* @param pathInPear a complete path to a class inside an (installed) pear
//* @return the part starting after the top node of the install dir
//*/
//private String getPath_in_v3_classes(String pathInPear) {
// return path2classname.get(pathInPear);
//}
//private boolean reportDuplicates() throws IOException {
//List<List<CommonConverted>> nonIdenticals = new ArrayList<>();
//List<CommonConverted> onlyIdenticals = new ArrayList<>();
//
//classname2multiSources.forEach(
// (classname, ccs) -> {
// if (ccs.size() > 1) {
// nonIdenticals.add(ccs);
// } else {
// CommonConverted cc = ccs.get(0);
// if (cc.containersAndV2Paths.size() > 1)
// onlyIdenticals.add(cc); // the same item in multiple containers and/or paths
// }
// }
// );
//
//if (nonIdenticals.size() == 0) {
// if (onlyIdenticals.size() == 0) {
// System.out.println("There were no duplicates found.");
// } else {
// // report identical duplicates
// try (BufferedWriter bw = Files.newBufferedWriter(makePath(outDirLog + "identical_duplicates.txt"), StandardOpenOption.CREATE)) {
// logPrintNl("Report of Identical duplicates:", bw);
// for (CommonConverted cc : onlyIdenticals) {
// int i = 0;
// logPrintNl("Class: " + cc.fqcn_slash, bw);
// for (ContainerAndPath cp : cc.containersAndV2Paths) {
// logPrintNl(" " + (++i) + " " + cp, bw);
// }
// logPrintNl("", bw);
// }
// }
// }
// return true;
//}
//
//// non-identicals, print out all of them
//try (BufferedWriter bw = Files.newBufferedWriter(makePath(outDirLog + "nonIdentical_duplicates.txt"), StandardOpenOption.CREATE)) {
// logPrintNl("Report of non-identical duplicates", bw);
// for (List<CommonConverted> nonIdentical : nonIdenticals) {
// String fqcn = nonIdentical.get(0).fqcn_slash;
// logPrintNl(" classname: " + fqcn, bw);
// int i = 1;
// // for each cc, and within each cc, for each containerAndPath
// for (CommonConverted cc : nonIdentical) {
//// logPrintNl(" version " + i, bw);
// assert fqcn.equals(cc.fqcn_slash);
// int j = 1;
// boolean isSame = cc.containersAndV2Paths.size() > 1;
// boolean isFirstTime = true;
// for (ContainerAndPath cp : cc.containersAndV2Paths) {
// String first = isSame && isFirstTime
// ? " same: "
// : isSame
// ? " "
// : " ";
// isFirstTime = false;
// logPrintNl(first + i + "." + (j++) + " " + cp, bw);
// }
// indent[0] -= 6;
//// logPrintNl("", bw);
// i++;
// }
//// logPrintNl("", bw);
// }
//}
//return false;
//}
}
| no Jira - change toString to use the no-limit version of list pretty printing
git-svn-id: d56ff9e7d7ea0b208561738885f328c1a8397aa6@1797119 13f79535-47bb-0310-9956-ffa450edef68
| uimaj-v3migration-jcas/src/main/java/org/apache/uima/migratev3/jcas/MigrateJCas.java | no Jira - change toString to use the no-limit version of list pretty printing | <ide><path>imaj-v3migration-jcas/src/main/java/org/apache/uima/migratev3/jcas/MigrateJCas.java
<ide> try {
<ide> si(sb); // new line + indent
<ide> sb.append("subContainers=");
<del> Misc.addElementsToStringBuilder(indent, sb, Misc.setAsList(subContainers), 100, (sbx, i) -> sbx.append(i.id)).append(',');
<add> Misc.addElementsToStringBuilder(indent, sb, Misc.setAsList(subContainers), -1, (sbx, i) -> sbx.append(i.id)).append(',');
<ide> si(sb).append("paths migrated="); // new line + indent
<del> Misc.addElementsToStringBuilder(indent, sb, candidates, 100, StringBuilder::append).append(',');
<add> Misc.addElementsToStringBuilder(indent, sb, candidates, -1, StringBuilder::append).append(',');
<ide> // si(sb).append("v3CompilePath="); // new line + indent
<ide> // Misc.addElementsToStringBuilder(indent, sb, v3CompiledPathAndContainerItemPath, 100, StringBuilder::append);
<ide> } finally {
<ide> "null").append(',');
<ide> si(sb).append("containersAndPaths=")
<ide> .append(containersAndV2Paths != null
<del> ? Misc.ppList(indent, Misc.setAsList(containersAndV2Paths), maxLen, StringBuilder::append)
<add> ? Misc.ppList(indent, Misc.setAsList(containersAndV2Paths), -1, StringBuilder::append)
<ide> : "null").append(',');
<ide> si(sb).append("v3SourcePath=").append(v3SourcePath).append(',');
<ide> si(sb).append("fqcn_slash=").append(fqcn_slash).append("]").append(Misc.ls); |
|
Java | apache-2.0 | f5cec02835cc2d4709f7999fc71301364b53a02b | 0 | matthew-compton/Petfinder | package com.ambergleam.petfinder.controller;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.ambergleam.petfinder.R;
import com.ambergleam.petfinder.model.Pet;
import com.ambergleam.petfinder.service.PetfinderServiceManager;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import rx.subscriptions.CompositeSubscription;
public abstract class PetListFragment extends BaseFragment {
public static final String TAG = PetListFragment.class.getSimpleName();
public static final String STATE_PETS = TAG + "STATE_PETS";
public static final String STATE_PETS_SIZE_UNFILTERED = TAG + "STATE_PETS_SIZE_UNFILTERED";
public static final String STATE_PETS_INDEX = TAG + "STATE_PETS_INDEX";
public static final String STATE_PETS_OFFSET = TAG + "STATE_PETS_OFFSET";
public static final String STATE_IMAGE_INDEX = TAG + "STATE_IMAGE_INDEX";
public static final int IMAGE_INDEX_INITIAL = 2;
public static final int IMAGE_INDEX_DELTA = 5;
CompositeSubscription mCompositeSubscription = new CompositeSubscription();
@Inject PetfinderServiceManager mPetfinderServiceManager;
@InjectView(R.id.pet_previous) ImageButton mPreviousPetButton;
@InjectView(R.id.pet_name) TextView mNameTextView;
@InjectView(R.id.pet_next) ImageButton mNextPetButton;
@InjectView(R.id.image_previous) ImageButton mPreviousImageButton;
@InjectView(R.id.image_index) TextView mIndexTextView;
@InjectView(R.id.image_next) ImageButton mNextImageButton;
@InjectView(R.id.image) ImageView mImage;
@InjectView(R.id.progress) ProgressBar mProgressBar;
@InjectView(R.id.error) RelativeLayout mError;
@InjectView(R.id.empty) TextView mEmpty;
public ArrayList<Pet> mPets;
public int mPetSizeUnfiltered;
public int mPetIndex;
public int mPetOffset;
public int mImageIndex;
protected abstract void findPets();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_pet, container, false);
ButterKnife.inject(this, layout);
if (savedInstanceState != null) {
mPets = (ArrayList<Pet>) savedInstanceState.getSerializable(STATE_PETS);
mPetSizeUnfiltered = savedInstanceState.getInt(STATE_PETS_SIZE_UNFILTERED);
mPetIndex = savedInstanceState.getInt(STATE_PETS_INDEX);
mPetOffset = savedInstanceState.getInt(STATE_PETS_OFFSET);
mImageIndex = savedInstanceState.getInt(STATE_IMAGE_INDEX);
}
mPetfinderServiceManager.getPetfinderPreference().loadPreference(getActivity());
mError.setOnClickListener(v -> refresh());
setHasOptionsMenu(true);
return layout;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(STATE_PETS, mPets);
outState.putInt(STATE_PETS_SIZE_UNFILTERED, mPetSizeUnfiltered);
outState.putInt(STATE_PETS_INDEX, mPetIndex);
outState.putInt(STATE_PETS_OFFSET, mPetOffset);
outState.putInt(STATE_IMAGE_INDEX, mImageIndex);
}
public void refresh() {
hideAll();
mPetIndex = 0;
mPetOffset = 0;
findPets();
}
@Override
public void onResume() {
super.onResume();
if (mPets == null || mPets.size() == 0) {
findPets();
} else {
updateUI();
}
}
@Override
public void onPause() {
super.onStop();
mCompositeSubscription.clear();
mCompositeSubscription.unsubscribe();
}
public ArrayList<Pet> filterPets(List<Pet> unfiltered) {
ArrayList<Pet> filtered = new ArrayList<>();
for (Pet pet : unfiltered) {
if (isValidPet(pet)) {
filtered.add(pet);
}
}
return filtered;
}
private boolean isValidPet(Pet pet) {
if (pet != null && pet.mMedia != null && pet.mMedia.mPhotos != null) {
return true;
}
return false;
}
@OnClick(R.id.pet_name)
public void onClickPetName() {
startDetailActivity();
}
public void startDetailActivity() {
Pet pet = mPets.get(mPetIndex);
Intent intentDetail = new Intent(getActivity(), DetailActivity.class);
intentDetail.putExtra(DetailFragment.EXTRA_PET, pet);
startActivity(intentDetail);
}
@OnClick(R.id.image_previous)
public void onClickPreviousImage() {
startImageLoading();
int imageIndexLength = mPets.get(mPetIndex).mMedia.mPhotos.mPhotos.length;
mImageIndex -= IMAGE_INDEX_DELTA;
if (mImageIndex < 0) {
mImageIndex = imageIndexLength + mImageIndex;
}
updateUI();
}
@OnClick(R.id.image_next)
public void onClickNextImage() {
startImageLoading();
int imageIndexLength = mPets.get(mPetIndex).mMedia.mPhotos.mPhotos.length;
mImageIndex += IMAGE_INDEX_DELTA;
mImageIndex %= imageIndexLength;
updateUI();
}
public void checkPetIndex() {
if (mPetIndex == -1) {
mPetIndex = mPets.size() - 1;
}
}
@OnClick(R.id.pet_previous)
public void onClickPreviousPet() {
startPetLoading();
mImageIndex = IMAGE_INDEX_INITIAL;
mPetIndex--;
if (mPetIndex < 0) {
mPetIndex = -1;
mPetOffset -= mPetfinderServiceManager.getCount();
findPets();
} else {
updateUI();
}
}
@OnClick(R.id.pet_next)
public void onClickNextPet() {
startPetLoading();
mImageIndex = IMAGE_INDEX_INITIAL;
mPetIndex++;
if (mPetIndex >= mPets.size()) {
mPetIndex %= mPets.size();
mPetOffset += mPetfinderServiceManager.getCount();
findPets();
} else {
updateUI();
}
}
public void updateUI() {
updateToolbarTop();
updateToolbarBottom();
updateImageView();
}
private void updateToolbarTop() {
updateNameView();
updatePetNavButtons();
}
private void updateToolbarBottom() {
updateImageIndexView();
updateImageNavButtons();
}
private void updateNameView() {
mNameTextView.setText(mPets.get(mPetIndex).mName.mString);
}
private void updatePetNavButtons() {
if (mPetIndex + mPetOffset - 1 < 0 || !mPetfinderServiceManager.getPetfinderPreference().isLocationSearch()) {
mPreviousPetButton.setVisibility(View.INVISIBLE);
} else {
mPreviousPetButton.setVisibility(View.VISIBLE);
}
if (mPetIndex + 1 >= mPets.size() && mPetSizeUnfiltered < mPetfinderServiceManager.getCount()) {
mNextPetButton.setVisibility(View.INVISIBLE);
} else {
mNextPetButton.setVisibility(View.VISIBLE);
}
}
private void updateImageIndexView() {
int imageIndex = (mImageIndex / IMAGE_INDEX_DELTA) + 1;
int imageIndexLength = mPets.get(mPetIndex).mMedia.mPhotos.mPhotos.length / IMAGE_INDEX_DELTA;
String index = new StringBuilder()
.append("( ")
.append(imageIndex)
.append(" / ")
.append(imageIndexLength)
.append(" )").toString();
mIndexTextView.setText(index);
}
private void updateImageNavButtons() {
if (mImageIndex - IMAGE_INDEX_DELTA < 0) {
mPreviousImageButton.setVisibility(View.INVISIBLE);
} else {
mPreviousImageButton.setVisibility(View.VISIBLE);
}
if (mImageIndex + IMAGE_INDEX_DELTA > mPets.get(mPetIndex).mMedia.mPhotos.mPhotos.length) {
mNextImageButton.setVisibility(View.INVISIBLE);
} else {
mNextImageButton.setVisibility(View.VISIBLE);
}
}
private void updateImageView() {
Picasso.with(getActivity())
.load(mPets.get(mPetIndex).mMedia.mPhotos.mPhotos[mImageIndex].mPhotoUrl)
.into(mImage,
new Callback() {
@Override
public void onSuccess() {
finishLoading();
}
@Override
public void onError() {
finishLoading();
}
});
}
public void startPetLoading() {
hideAll();
mProgressBar.setVisibility(View.VISIBLE);
mNameTextView.setVisibility(View.INVISIBLE);
mPreviousImageButton.setVisibility(View.INVISIBLE);
mIndexTextView.setVisibility(View.INVISIBLE);
mNextImageButton.setVisibility(View.INVISIBLE);
}
public void startImageLoading() {
hideAll();
mProgressBar.setVisibility(View.VISIBLE);
}
public void finishLoading() {
hideAll();
mNameTextView.setVisibility(View.VISIBLE);
mIndexTextView.setVisibility(View.VISIBLE);
mImage.setVisibility(View.VISIBLE);
getActivity().invalidateOptionsMenu();
}
public void showError() {
hideAll();
mError.setVisibility(View.VISIBLE);
getActivity().invalidateOptionsMenu();
}
public void showEmpty() {
hideAll();
mEmpty.setVisibility(View.VISIBLE);
mPreviousImageButton.setVisibility(View.INVISIBLE);
mNextImageButton.setVisibility(View.INVISIBLE);
getActivity().invalidateOptionsMenu();
}
private void hideAll() {
mProgressBar.setVisibility(View.GONE);
mImage.setVisibility(View.GONE);
mError.setVisibility(View.GONE);
mEmpty.setVisibility(View.GONE);
}
}
| app/src/main/java/com/ambergleam/petfinder/controller/PetListFragment.java | package com.ambergleam.petfinder.controller;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.ambergleam.petfinder.R;
import com.ambergleam.petfinder.model.Pet;
import com.ambergleam.petfinder.service.PetfinderServiceManager;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import rx.subscriptions.CompositeSubscription;
public abstract class PetListFragment extends BaseFragment {
public static final String TAG = PetListFragment.class.getSimpleName();
public static final String STATE_PETS = TAG + "STATE_PETS";
public static final String STATE_PETS_SIZE_UNFILTERED = TAG + "STATE_PETS_SIZE_UNFILTERED";
public static final String STATE_PETS_INDEX = TAG + "STATE_PETS_INDEX";
public static final String STATE_PETS_OFFSET = TAG + "STATE_PETS_OFFSET";
public static final String STATE_IMAGE_INDEX = TAG + "STATE_IMAGE_INDEX";
public static final int IMAGE_INDEX_INITIAL = 2;
public static final int IMAGE_INDEX_DELTA = 5;
CompositeSubscription mCompositeSubscription = new CompositeSubscription();
@Inject PetfinderServiceManager mPetfinderServiceManager;
@InjectView(R.id.pet_previous) ImageButton mPreviousPetButton;
@InjectView(R.id.pet_name) TextView mNameTextView;
@InjectView(R.id.pet_next) ImageButton mNextPetButton;
@InjectView(R.id.image_previous) ImageButton mPreviousImageButton;
@InjectView(R.id.image_index) TextView mIndexTextView;
@InjectView(R.id.image_next) ImageButton mNextImageButton;
@InjectView(R.id.image) ImageView mImage;
@InjectView(R.id.progress) ProgressBar mProgressBar;
@InjectView(R.id.error) RelativeLayout mError;
@InjectView(R.id.empty) TextView mEmpty;
public ArrayList<Pet> mPets;
public int mPetSizeUnfiltered;
public int mPetIndex;
public int mPetOffset;
public int mImageIndex;
protected abstract void findPets();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_pet, container, false);
ButterKnife.inject(this, layout);
if (savedInstanceState != null) {
mPets = (ArrayList<Pet>) savedInstanceState.getSerializable(STATE_PETS);
mPetSizeUnfiltered = savedInstanceState.getInt(STATE_PETS_SIZE_UNFILTERED);
mPetIndex = savedInstanceState.getInt(STATE_PETS_INDEX);
mPetOffset = savedInstanceState.getInt(STATE_PETS_OFFSET);
mImageIndex = savedInstanceState.getInt(STATE_IMAGE_INDEX);
updateUI();
}
mPetfinderServiceManager.getPetfinderPreference().loadPreference(getActivity());
mError.setOnClickListener(v -> refresh());
setHasOptionsMenu(true);
return layout;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(STATE_PETS, mPets);
outState.putInt(STATE_PETS_SIZE_UNFILTERED, mPetSizeUnfiltered);
outState.putInt(STATE_PETS_INDEX, mPetIndex);
outState.putInt(STATE_PETS_OFFSET, mPetOffset);
outState.putInt(STATE_IMAGE_INDEX, mImageIndex);
}
public void refresh() {
hideAll();
mPetIndex = 0;
mPetOffset = 0;
findPets();
}
@Override
public void onResume() {
super.onResume();
if (mPets == null || mPets.size() == 0) {
findPets();
} else {
updateUI();
}
}
@Override
public void onPause() {
super.onStop();
mCompositeSubscription.clear();
mCompositeSubscription.unsubscribe();
}
public ArrayList<Pet> filterPets(List<Pet> unfiltered) {
ArrayList<Pet> filtered = new ArrayList<>();
for (Pet pet : unfiltered) {
if (isValidPet(pet)) {
filtered.add(pet);
}
}
return filtered;
}
private boolean isValidPet(Pet pet) {
if (pet != null && pet.mMedia != null && pet.mMedia.mPhotos != null) {
return true;
}
return false;
}
@OnClick(R.id.pet_name)
public void onClickPetName() {
startDetailActivity();
}
public void startDetailActivity() {
Pet pet = mPets.get(mPetIndex);
Intent intentDetail = new Intent(getActivity(), DetailActivity.class);
intentDetail.putExtra(DetailFragment.EXTRA_PET, pet);
startActivity(intentDetail);
}
@OnClick(R.id.image_previous)
public void onClickPreviousImage() {
startImageLoading();
int imageIndexLength = mPets.get(mPetIndex).mMedia.mPhotos.mPhotos.length;
mImageIndex -= IMAGE_INDEX_DELTA;
if (mImageIndex < 0) {
mImageIndex = imageIndexLength + mImageIndex;
}
updateUI();
}
@OnClick(R.id.image_next)
public void onClickNextImage() {
startImageLoading();
int imageIndexLength = mPets.get(mPetIndex).mMedia.mPhotos.mPhotos.length;
mImageIndex += IMAGE_INDEX_DELTA;
mImageIndex %= imageIndexLength;
updateUI();
}
public void checkPetIndex() {
if (mPetIndex == -1) {
mPetIndex = mPets.size() - 1;
}
}
@OnClick(R.id.pet_previous)
public void onClickPreviousPet() {
startPetLoading();
mImageIndex = IMAGE_INDEX_INITIAL;
mPetIndex--;
if (mPetIndex < 0) {
mPetIndex = -1;
mPetOffset -= mPetfinderServiceManager.getCount();
findPets();
} else {
updateUI();
}
}
@OnClick(R.id.pet_next)
public void onClickNextPet() {
startPetLoading();
mImageIndex = IMAGE_INDEX_INITIAL;
mPetIndex++;
if (mPetIndex >= mPets.size()) {
mPetIndex %= mPets.size();
mPetOffset += mPetfinderServiceManager.getCount();
findPets();
} else {
updateUI();
}
}
public void updateUI() {
updateToolbarTop();
updateToolbarBottom();
updateImageView();
}
private void updateToolbarTop() {
updateNameView();
updatePetNavButtons();
}
private void updateToolbarBottom() {
updateImageIndexView();
updateImageNavButtons();
}
private void updateNameView() {
mNameTextView.setText(mPets.get(mPetIndex).mName.mString);
}
private void updatePetNavButtons() {
if (mPetIndex + mPetOffset - 1 < 0 || !mPetfinderServiceManager.getPetfinderPreference().isLocationSearch()) {
mPreviousPetButton.setVisibility(View.INVISIBLE);
} else {
mPreviousPetButton.setVisibility(View.VISIBLE);
}
if (mPetIndex + 1 >= mPets.size() && mPetSizeUnfiltered < mPetfinderServiceManager.getCount()) {
mNextPetButton.setVisibility(View.INVISIBLE);
} else {
mNextPetButton.setVisibility(View.VISIBLE);
}
}
private void updateImageIndexView() {
int imageIndex = (mImageIndex / IMAGE_INDEX_DELTA) + 1;
int imageIndexLength = mPets.get(mPetIndex).mMedia.mPhotos.mPhotos.length / IMAGE_INDEX_DELTA;
String index = new StringBuilder()
.append("( ")
.append(imageIndex)
.append(" / ")
.append(imageIndexLength)
.append(" )").toString();
mIndexTextView.setText(index);
}
private void updateImageNavButtons() {
if (mImageIndex - IMAGE_INDEX_DELTA < 0) {
mPreviousImageButton.setVisibility(View.INVISIBLE);
} else {
mPreviousImageButton.setVisibility(View.VISIBLE);
}
if (mImageIndex + IMAGE_INDEX_DELTA > mPets.get(mPetIndex).mMedia.mPhotos.mPhotos.length) {
mNextImageButton.setVisibility(View.INVISIBLE);
} else {
mNextImageButton.setVisibility(View.VISIBLE);
}
}
private void updateImageView() {
Picasso.with(getActivity())
.load(mPets.get(mPetIndex).mMedia.mPhotos.mPhotos[mImageIndex].mPhotoUrl)
.into(mImage,
new Callback() {
@Override
public void onSuccess() {
finishLoading();
}
@Override
public void onError() {
finishLoading();
}
});
}
public void startPetLoading() {
hideAll();
mProgressBar.setVisibility(View.VISIBLE);
mNameTextView.setVisibility(View.INVISIBLE);
mPreviousImageButton.setVisibility(View.INVISIBLE);
mIndexTextView.setVisibility(View.INVISIBLE);
mNextImageButton.setVisibility(View.INVISIBLE);
}
public void startImageLoading() {
hideAll();
mProgressBar.setVisibility(View.VISIBLE);
}
public void finishLoading() {
hideAll();
mNameTextView.setVisibility(View.VISIBLE);
mIndexTextView.setVisibility(View.VISIBLE);
mImage.setVisibility(View.VISIBLE);
getActivity().invalidateOptionsMenu();
}
public void showError() {
hideAll();
mError.setVisibility(View.VISIBLE);
getActivity().invalidateOptionsMenu();
}
public void showEmpty() {
hideAll();
mEmpty.setVisibility(View.VISIBLE);
mPreviousImageButton.setVisibility(View.INVISIBLE);
mNextImageButton.setVisibility(View.INVISIBLE);
getActivity().invalidateOptionsMenu();
}
private void hideAll() {
mProgressBar.setVisibility(View.GONE);
mImage.setVisibility(View.GONE);
mError.setVisibility(View.GONE);
mEmpty.setVisibility(View.GONE);
}
}
| Fixed null pointer on rotation during load
| app/src/main/java/com/ambergleam/petfinder/controller/PetListFragment.java | Fixed null pointer on rotation during load | <ide><path>pp/src/main/java/com/ambergleam/petfinder/controller/PetListFragment.java
<ide> mPetIndex = savedInstanceState.getInt(STATE_PETS_INDEX);
<ide> mPetOffset = savedInstanceState.getInt(STATE_PETS_OFFSET);
<ide> mImageIndex = savedInstanceState.getInt(STATE_IMAGE_INDEX);
<del> updateUI();
<ide> }
<ide> mPetfinderServiceManager.getPetfinderPreference().loadPreference(getActivity());
<ide> |
|
Java | apache-2.0 | b525c4ac74df7752578f976162f790675f3a2efd | 0 | apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc | /*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
* </p>
*/
package io.shardingsphere.core.jdbc.core;
import com.google.common.eventbus.Subscribe;
import io.shardingsphere.core.constant.ConnectionMode;
import io.shardingsphere.core.constant.DatabaseType;
import io.shardingsphere.core.exception.ShardingException;
import io.shardingsphere.core.executor.ExecutorEngine;
import io.shardingsphere.core.jdbc.metadata.JDBCTableMetaDataConnectionManager;
import io.shardingsphere.core.metadata.ShardingMetaData;
import io.shardingsphere.core.rule.ShardingRule;
import io.shardingsphere.jdbc.orchestration.internal.eventbus.jdbc.JDBCEventBusEvent;
import io.shardingsphere.jdbc.orchestration.internal.jdbc.datasource.CircuitBreakerDataSource;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Sharding runtime context.
*
* @author gaohongtao
* @author panjuan
*/
@RequiredArgsConstructor
@Getter
public final class ShardingContext {
private final Map<String, DataSource> dataSourceMap;
private final ShardingRule shardingRule;
private final DatabaseType databaseType;
private final ExecutorEngine executorEngine;
private ShardingMetaData metaData;
private final ConnectionMode connectionMode;
private final boolean showSQL;
private List<String> disabledDataSourceNames = new LinkedList<>();
private List<String> circuitBreakerDataSourceNames = new LinkedList<>();
/**
* Renew disable dataSource names.
*
* @param jdbcEventBusEvent jdbc event bus event
*/
@Subscribe
public void renewDisabledDataSourceNames(final JDBCEventBusEvent jdbcEventBusEvent) {
disabledDataSourceNames = jdbcEventBusEvent.getDisabledDataSourceNames();
metaData = new ShardingMetaData(
getDataSourceURLs(getDataSourceMap()), shardingRule, getDatabaseType(), executorEngine.getExecutorService(), new JDBCTableMetaDataConnectionManager(getDataSourceMap()));
}
/**
* Renew circuit breaker dataSource names.
*
* @param jdbcEventBusEvent jdbc event bus event
*/
@Subscribe
public void renewCircuitBreakerDataSourceNames(final JDBCEventBusEvent jdbcEventBusEvent) {
circuitBreakerDataSourceNames = jdbcEventBusEvent.getCircuitBreakerDataSource();
metaData = new ShardingMetaData(
getDataSourceURLs(getDataSourceMap()), shardingRule, getDatabaseType(), executorEngine.getExecutorService(), new JDBCTableMetaDataConnectionManager(getDataSourceMap()));
}
private static Map<String, String> getDataSourceURLs(final Map<String, DataSource> dataSourceMap) {
Map<String, String> result = new LinkedHashMap<>(dataSourceMap.size(), 1);
for (Map.Entry<String, DataSource> entry : dataSourceMap.entrySet()) {
result.put(entry.getKey(), getDataSourceURL(entry.getValue()));
}
return result;
}
private static String getDataSourceURL(final DataSource dataSource) {
try (Connection connection = dataSource.getConnection()) {
return connection.getMetaData().getURL();
} catch (final SQLException ex) {
throw new ShardingException(ex);
}
}
/**
* Get available data source map.
*
* @return available data source map
*/
public Map<String, DataSource> getDataSourceMap() {
if (!getCircuitBreakerDataSourceNames().isEmpty()) {
return getCircuitBreakerDataSourceMap();
}
if (!getDisabledDataSourceNames().isEmpty()) {
return getAvailableDataSourceMap();
}
return dataSourceMap;
}
private Map<String, DataSource> getAvailableDataSourceMap() {
Map<String, DataSource> result = new LinkedHashMap<>(dataSourceMap);
for (String each : disabledDataSourceNames) {
result.remove(each);
}
return result;
}
private Map<String, DataSource> getCircuitBreakerDataSourceMap() {
Map<String, DataSource> result = new LinkedHashMap<>();
for (String each : dataSourceMap.keySet()) {
result.put(each, new CircuitBreakerDataSource());
}
return result;
}
}
| sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/ShardingContext.java | /*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
* </p>
*/
package io.shardingsphere.core.jdbc.core;
import com.google.common.eventbus.Subscribe;
import io.shardingsphere.core.constant.ConnectionMode;
import io.shardingsphere.core.constant.DatabaseType;
import io.shardingsphere.core.exception.ShardingException;
import io.shardingsphere.core.executor.ExecutorEngine;
import io.shardingsphere.core.metadata.ShardingMetaData;
import io.shardingsphere.core.rule.ShardingRule;
import io.shardingsphere.jdbc.orchestration.internal.eventbus.jdbc.JDBCEventBusEvent;
import io.shardingsphere.jdbc.orchestration.internal.jdbc.datasource.CircuitBreakerDataSource;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Sharding runtime context.
*
* @author gaohongtao
* @author panjuan
*/
@RequiredArgsConstructor
@Getter
public final class ShardingContext {
private final Map<String, DataSource> dataSourceMap;
private final ShardingRule shardingRule;
private final DatabaseType databaseType;
private final ExecutorEngine executorEngine;
private final ShardingMetaData metaData;
private final ConnectionMode connectionMode;
private final boolean showSQL;
private List<String> disabledDataSourceNames = new LinkedList<>();
private List<String> circuitBreakerDataSourceNames = new LinkedList<>();
/**
* Renew disable dataSource names.
*
* @param jdbcEventBusEvent jdbc event bus event
*/
@Subscribe
public void renewDisabledDataSourceNames(final JDBCEventBusEvent jdbcEventBusEvent) {
disabledDataSourceNames = jdbcEventBusEvent.getDisabledDataSourceNames();
}
/**
* Renew circuit breaker dataSource names.
*
* @param jdbcEventBusEvent jdbc event bus event
*/
@Subscribe
public void renewCircuitBreakerDataSourceNames(final JDBCEventBusEvent jdbcEventBusEvent) {
circuitBreakerDataSourceNames = jdbcEventBusEvent.getCircuitBreakerDataSource();
}
private static Map<String, String> getDataSourceURLs(final Map<String, DataSource> dataSourceMap) {
Map<String, String> result = new LinkedHashMap<>(dataSourceMap.size(), 1);
for (Map.Entry<String, DataSource> entry : dataSourceMap.entrySet()) {
result.put(entry.getKey(), getDataSourceURL(entry.getValue()));
}
return result;
}
private static String getDataSourceURL(final DataSource dataSource) {
try (Connection connection = dataSource.getConnection()) {
return connection.getMetaData().getURL();
} catch (final SQLException ex) {
throw new ShardingException(ex);
}
}
/**
* Get available data source map.
*
* @return available data source map
*/
public Map<String, DataSource> getDataSourceMap() {
if (!getCircuitBreakerDataSourceNames().isEmpty()) {
return getCircuitBreakerDataSourceMap();
}
if (!getDisabledDataSourceNames().isEmpty()) {
return getAvailableDataSourceMap();
}
return dataSourceMap;
}
private Map<String, DataSource> getAvailableDataSourceMap() {
Map<String, DataSource> result = new LinkedHashMap<>(dataSourceMap);
for (String each : disabledDataSourceNames) {
result.remove(each);
}
return result;
}
private Map<String, DataSource> getCircuitBreakerDataSourceMap() {
Map<String, DataSource> result = new LinkedHashMap<>();
for (String each : dataSourceMap.keySet()) {
result.put(each, new CircuitBreakerDataSource());
}
return result;
}
}
| renew metaData
| sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/ShardingContext.java | renew metaData | <ide><path>harding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/ShardingContext.java
<ide> import io.shardingsphere.core.constant.DatabaseType;
<ide> import io.shardingsphere.core.exception.ShardingException;
<ide> import io.shardingsphere.core.executor.ExecutorEngine;
<add>import io.shardingsphere.core.jdbc.metadata.JDBCTableMetaDataConnectionManager;
<ide> import io.shardingsphere.core.metadata.ShardingMetaData;
<ide> import io.shardingsphere.core.rule.ShardingRule;
<ide> import io.shardingsphere.jdbc.orchestration.internal.eventbus.jdbc.JDBCEventBusEvent;
<ide>
<ide> private final ExecutorEngine executorEngine;
<ide>
<del> private final ShardingMetaData metaData;
<add> private ShardingMetaData metaData;
<ide>
<ide> private final ConnectionMode connectionMode;
<ide>
<ide> @Subscribe
<ide> public void renewDisabledDataSourceNames(final JDBCEventBusEvent jdbcEventBusEvent) {
<ide> disabledDataSourceNames = jdbcEventBusEvent.getDisabledDataSourceNames();
<add> metaData = new ShardingMetaData(
<add> getDataSourceURLs(getDataSourceMap()), shardingRule, getDatabaseType(), executorEngine.getExecutorService(), new JDBCTableMetaDataConnectionManager(getDataSourceMap()));
<ide> }
<ide>
<ide> /**
<ide> @Subscribe
<ide> public void renewCircuitBreakerDataSourceNames(final JDBCEventBusEvent jdbcEventBusEvent) {
<ide> circuitBreakerDataSourceNames = jdbcEventBusEvent.getCircuitBreakerDataSource();
<add> metaData = new ShardingMetaData(
<add> getDataSourceURLs(getDataSourceMap()), shardingRule, getDatabaseType(), executorEngine.getExecutorService(), new JDBCTableMetaDataConnectionManager(getDataSourceMap()));
<ide> }
<add>
<add>
<ide>
<ide> private static Map<String, String> getDataSourceURLs(final Map<String, DataSource> dataSourceMap) {
<ide> Map<String, String> result = new LinkedHashMap<>(dataSourceMap.size(), 1); |
|
Java | mit | 0d1b012aff5227a39613be96ef8923d7077fe315 | 0 | andreaslorentzen/Dansk-Datahistorisk-Forening | package app.ddf.danskdatahistoriskforening.helper;
import android.media.MediaRecorder;
import android.net.Uri;
import com.coremedia.iso.boxes.Container;
import com.googlecode.mp4parser.FileDataSourceImpl;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.Track;
import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder;
import com.googlecode.mp4parser.authoring.container.mp4.MovieCreator;
import com.googlecode.mp4parser.authoring.tracks.AppendTrack;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.List;
/**
* Mighty credits to Sebastian Annies (sannies @ github)!
*/
public class AudioRecorder {
private boolean isRecording;
private MediaRecorder mr;
public boolean isRecording() {
return isRecording;
}
public void startRecording() throws IOException {
isRecording = true;
mr = new MediaRecorder();
String mFileName = LocalMediaStorage.getOutputMediaFileUri(null, LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD_TEMP).getPath();
File tempFile = new File(mFileName);
if (tempFile.exists()) {
tempFile.delete();
mFileName = LocalMediaStorage.getOutputMediaFileUri(null,LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD_TEMP).getPath();
}
mr.setAudioSource(MediaRecorder.AudioSource.MIC);
mr.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mr.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mr.setAudioSamplingRate(16000);
mr.setAudioChannels(1);
mr.setOutputFile(mFileName);
mr.prepare();
mr.start();
}
public boolean stopRecording() throws IOException {
isRecording = false;
if (mr == null)
return false;
try{
mr.stop(); // stop recording
}catch(RuntimeException stopException){
return false;
}
mr.reset(); // set state to idle
mr.release(); // release resources back to the system
File recordedFile = new File(LocalMediaStorage.getOutputMediaFileUri(null, LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD).getPath());
File recordedFileTemp = new File(LocalMediaStorage.getOutputMediaFileUri(null, LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD_TEMP).getPath());
mergeAudioFile(recordedFile, recordedFileTemp);
isRecording = false;
return true;
}
private void mergeAudioFile(File recordedFile, File recordedFileTemp) throws IOException {
if (!recordedFile.exists()) {
recordedFileTemp.renameTo(new File(LocalMediaStorage.getOutputMediaFileUri(null, LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD).getPath()));
return;
}
final Movie movieA = MovieCreator.build(new FileDataSourceImpl(recordedFileTemp));
final Movie movieB = MovieCreator.build(new FileDataSourceImpl(recordedFile));
final Movie finalMovie = new Movie();
final List<Track> movieOneTracks = movieA.getTracks();
final List<Track> movieTwoTracks = movieB.getTracks();
//for (int i = 0; i < movieOneTracks.size() || i < movieTwoTracks.size(); ++i) {
finalMovie.addTrack(new AppendTrack(movieTwoTracks.get(0), movieOneTracks.get(0)));
//}
final Container container = new DefaultMp4Builder().build(finalMovie);
File recordedFileMerged = new File(LocalMediaStorage.getOutputMediaFileUri(null, LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD_MERGED).getPath());
if (recordedFileMerged.exists()) {
recordedFileMerged.delete();
}
final FileOutputStream fos = new FileOutputStream(new File(String.format(recordedFileMerged.getPath())));
final WritableByteChannel bb = Channels.newChannel(fos);
container.writeContainer(bb);
fos.close();
recordedFile.delete();
recordedFileTemp.delete();
recordedFileMerged.renameTo(new File(LocalMediaStorage.getOutputMediaFileUri(null, LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD).getPath()));
}
} | app/src/main/java/app/ddf/danskdatahistoriskforening/helper/AudioRecorder.java | package app.ddf.danskdatahistoriskforening.helper;
import android.media.MediaRecorder;
import android.net.Uri;
import com.coremedia.iso.boxes.Container;
import com.googlecode.mp4parser.FileDataSourceImpl;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.Track;
import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder;
import com.googlecode.mp4parser.authoring.container.mp4.MovieCreator;
import com.googlecode.mp4parser.authoring.tracks.AppendTrack;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.List;
/**
* Mighty credits to Sebastian Annies (sannies @ github)!
*/
public class AudioRecorder {
private boolean isRecording;
private MediaRecorder mr;
public boolean isRecording() {
return isRecording;
}
public void startRecording() throws IOException {
isRecording = true;
mr = new MediaRecorder();
String mFileName = LocalMediaStorage.getOutputMediaFileUri(null, LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD_TEMP).getPath();
File tempFile = new File(mFileName);
if (tempFile.exists()) {
tempFile.delete();
mFileName = LocalMediaStorage.getOutputMediaFileUri(null,LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD_TEMP).getPath();
}
mr.setAudioSource(MediaRecorder.AudioSource.MIC);
mr.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mr.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mr.setAudioSamplingRate(16000);
mr.setAudioChannels(1);
mr.setOutputFile(mFileName);
mr.prepare();
mr.start();
}
public boolean stopRecording() throws IOException {
isRecording = false;
if (mr == null)
return false;
try{
mr.stop(); // stop recording
}catch(RuntimeException stopException){
return false;
}
mr.reset(); // set state to idle
mr.release(); // release resources back to the system
File recordedFile = new File(LocalMediaStorage.getOutputMediaFileUri(null, LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD).getPath());
File recordedFileTemp = new File(LocalMediaStorage.getOutputMediaFileUri(null, LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD_TEMP).getPath());
mergeAudioFile(recordedFile, recordedFileTemp);
isRecording = false;
return true;
}
private void mergeAudioFile(File recordedFile, File recordedFileTemp) throws IOException {
if (!recordedFile.exists()) {
recordedFileTemp.renameTo(new File(LocalMediaStorage.getOutputMediaFileUri(null, LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD).getPath()));
return;
}
final Movie movieA = MovieCreator.build(new FileDataSourceImpl(recordedFileTemp));
final Movie movieB = MovieCreator.build(new FileDataSourceImpl(recordedFile));
final Movie finalMovie = new Movie();
final List<Track> movieOneTracks = movieA.getTracks();
final List<Track> movieTwoTracks = movieB.getTracks();
//for (int i = 0; i < movieOneTracks.size() || i < movieTwoTracks.size(); ++i) {
finalMovie.addTrack(new AppendTrack(movieTwoTracks.get(0), movieOneTracks.get(0)));
//}
final Container container = new DefaultMp4Builder().build(finalMovie);
File recordedFileMerged = new File(LocalMediaStorage.getOutputMediaFileUri(null, LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD_MERGED).getPath());
if (recordedFileMerged.exists()) {
recordedFileMerged.delete();
}
final FileOutputStream fos = new FileOutputStream(new File(String.format(recordedFileMerged.getPath())));
final WritableByteChannel bb = Channels.newChannel(fos);
container.writeContainer(bb);
fos.close();
recordedFile.delete();
recordedFileTemp.delete();
recordedFileMerged.renameTo(new File(LocalMediaStorage.getOutputMediaFileUri(null, LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD).getPath()));
}
public static MADATA mergeMultipleAudioFile(List<Uri> audioUris) throws IOException {
if (audioUris == null)
throw new IOException("AudioUris is null");
Movie finalMovie = new Movie();
List<Track> tracksList = new ArrayList<Track>();
List<Integer> durationList = new ArrayList<Integer>();
for (Uri uri : audioUris) {
File file = new File(LocalMediaStorage.getOutputMediaFileUri(uri.getPath(), LocalMediaStorage.MEDIA_TYPE_AUDIO).getPath());
Movie movie = MovieCreator.build(new FileDataSourceImpl(file));
List<Track> movieOneTracks = movie.getTracks();
tracksList.add(movieOneTracks.get(0));
durationList.add((int) movieOneTracks.get(0).getDuration());
}
Track[] tracks = (Track[]) tracksList.toArray();
finalMovie.addTrack(new AppendTrack(tracks));
final Container container = new DefaultMp4Builder().build(finalMovie);
File recordedFileMerged = new File(LocalMediaStorage.getOutputMediaFileUri(null, LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD_MERGED).getPath());
if (recordedFileMerged.exists()) {
recordedFileMerged.delete();
}
final FileOutputStream fos = new FileOutputStream(new File(String.format(recordedFileMerged.getPath())));
final WritableByteChannel bb = Channels.newChannel(fos);
container.writeContainer(bb);
fos.close();
return new MADATA(recordedFileMerged.toURI(), durationList);
}
} | #110 reformat finish
| app/src/main/java/app/ddf/danskdatahistoriskforening/helper/AudioRecorder.java | #110 reformat finish | <ide><path>pp/src/main/java/app/ddf/danskdatahistoriskforening/helper/AudioRecorder.java
<ide> recordedFileMerged.renameTo(new File(LocalMediaStorage.getOutputMediaFileUri(null, LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD).getPath()));
<ide> }
<ide>
<del> public static MADATA mergeMultipleAudioFile(List<Uri> audioUris) throws IOException {
<del> if (audioUris == null)
<del> throw new IOException("AudioUris is null");
<del> Movie finalMovie = new Movie();
<del> List<Track> tracksList = new ArrayList<Track>();
<del> List<Integer> durationList = new ArrayList<Integer>();
<del> for (Uri uri : audioUris) {
<del> File file = new File(LocalMediaStorage.getOutputMediaFileUri(uri.getPath(), LocalMediaStorage.MEDIA_TYPE_AUDIO).getPath());
<del> Movie movie = MovieCreator.build(new FileDataSourceImpl(file));
<del> List<Track> movieOneTracks = movie.getTracks();
<del> tracksList.add(movieOneTracks.get(0));
<del> durationList.add((int) movieOneTracks.get(0).getDuration());
<del> }
<del> Track[] tracks = (Track[]) tracksList.toArray();
<del> finalMovie.addTrack(new AppendTrack(tracks));
<del>
<del> final Container container = new DefaultMp4Builder().build(finalMovie);
<del> File recordedFileMerged = new File(LocalMediaStorage.getOutputMediaFileUri(null, LocalMediaStorage.MEDIA_TYPE_AUDIO_RECORD_MERGED).getPath());
<del> if (recordedFileMerged.exists()) {
<del> recordedFileMerged.delete();
<del> }
<del> final FileOutputStream fos = new FileOutputStream(new File(String.format(recordedFileMerged.getPath())));
<del> final WritableByteChannel bb = Channels.newChannel(fos);
<del> container.writeContainer(bb);
<del> fos.close();
<del> return new MADATA(recordedFileMerged.toURI(), durationList);
<del> }
<del>
<ide> } |
|
Java | apache-2.0 | f808f3646a94e4d523ab7fdf84cd2233ce3787c1 | 0 | simplifyops/cli-toolbelt | /**
* <p>Defines a set of commands with subcommands, using annotations to indicate methods to expose as subcommands.</p>
* <p>"Commands" represent an invocable named action, with optional arguments. A "Command" may also be a container
* for other "Commands" (i.e. "Subcommands"). In that case, the parent "command" is called a "command container".</p>
* <p>The simplest structure is a Class with Methods, where the Class is the command container, and the methods are the
* sub commands.</p>
* <p>For further nesting, the class can implement {@link com.simplifyops.toolbelt.HasSubCommands} and return
* other command container objects.</p>
*
* <p>Simplest usage:</p>
* <pre><code>
* class Greet{
* {@literal @}Command void hi({@literal @}Arg("name") String name){
* System.out.println("Hello, "+name+".");
* }
* {@literal @}Command void remark({@literal @}Arg("age") int age){
* System.out.println("I see you are "+age+" years old.");
* }
* }
* class Main{
* public static void main(String[] args){
* ToolBelt.with(new Greet()).runMain(args);
* }
* }
* </code></pre>
* <p>Commandline: </p>
* <code><pre>
* $ java ... Main greet hi --name bob
* Hello, bob.
* $ java ... Main greet remark --age 33
* I see you are 33 years old.
* </pre></code>
* <p>
* This constructs a {@link com.simplifyops.toolbelt.Tool} object, with a command "greet" (based on the class name
* Greet). "greet" has a "hi" and a "remark" subcommand. The class must have at least
* one method annotated with {@link com.simplifyops.toolbelt.Command @Command}. The parameters of that
* method (if any) should be annotated with {@link com.simplifyops.toolbelt.Arg @Arg} to define their names.
* (Alternately, if you compile your java class with {@code -parameters} flag to javac, the parameter names will be
* introspected.)
* This will use the {@link com.simplifyops.toolbelt.SimpleCommandInput} to parse "--somearg value" for a
* method parameter with arg name "somearg".
* </p>
* <p>You can define multiple commands (with their subcommands) in one step:</p>
* <code><pre>
* ToolBelt.with(new Command1(), new Command2(),...).runMain(args);
* </pre></code>
* <p>
* For more advanced usage, see below:
* </p>
* <p>
* Use {@link com.simplifyops.toolbelt.ToolBelt#belt(java.lang.String)} to create a builder.
* </p>
* <pre><code>
* ToolBelt.belt()
* .defaultHelp()
* .systemOutput()
* .addCommands(
* new MyCommand(),
* new MyCommand2()
* )
* .setParser(new JewelInput())
* .buckle();
* </code></pre>
* <p>
* Within your MyCommand classes, use the {@link com.simplifyops.toolbelt.Command @Command} annotation to indicate the
* class is a top-level command (optional). Add the same annotation on any methods within the class to expose them
* as subcommands. At least one method should be annotated this way.
* </p>
* <pre><code>
* {@literal @}Command(description = "Does something", name="doit")
* public class MyCommand{
* {@literal @}Command(name="sub1") public void sub1(InputArgs args){
* System.out.println("Input args: "+args);
* }
* }
* </code></pre>
*
* <p>
* The annotation can exclude the "name" attribute, and the lowercase name of the class or method is used as the
* command/subcommand. The method parameters will be parsed using the input parser (e.g. JewelCLI), so
* <code>InputArgs</code> must be defined with appropriate annotations.
*
* </p>
* <h2>Using HasSubCommand interface:</h2>
* <p>
* If a {@literal @}Command annotated class wants to define a subcommand which is also a container (has subcommands of
* its own), It should implement {@link com.simplifyops.toolbelt.HasSubCommands}, and return a list of command
* container objects.
* </p>
*<code><pre>
* {@literal @}Command class First implements HasSubCommands{
*
* {@literal @}Command void something(){
* System.out.println("This method prints something")
* }
*
* List<Object> getCommands(){
* return Arrays.asList(new Second());
* }
* }
* {@literal @}Command class Second{
* {@literal @}Command void third(){
* System.out.println("Third level nested command");
* }
* }
*</pre></code>
* <p>This will define an interface like:
*
* </p>
* <code><pre>
* $ java ... First
* Available commands: [something, second]
* $ java ... First something
* This method prints something
* $ java ... First second
* Availabe commands: [third]
* $ java ... First second third
* Third level nested command
* </pre></code>
*/
package com.simplifyops.toolbelt; | toolbelt/src/main/java/com/simplifyops/toolbelt/package-info.java | /**
* <p>Defines a set of commands with subcommands, using annotations to indicate methods to expose as subcommands.</p>
* <p>"Commands" represent an invocable named action, with optional arguments. A "Command" may also be a container
* for other "Commands" (i.e. "Subcommands"). In that case, the parent "command" is called a "command container".</p>
* <p>The simplest structure is a Class with Methods, where the Class is the command container, and the methods are the
* sub commands.</p>
* <p>For further nesting, the class can implement {@link com.simplifyops.toolbelt.HasSubCommands} and return
* other command container objects.</p>
*
* <p>Simplest usage:</p>
* <pre><code>
* class Greet{
* {@literal @}Command void hi({@literal @}Arg("name") String name){
* System.out.println("Hello, "+name+".");
* }
* {@literal @}Command void remark({@literal @}Arg("age") int age){
* System.out.println("I see you are "+age+" years old.");
* }
* }
* class Main{
* public static void main(String[] args){
* ToolBelt.with(new Greet()).runMain(args);
* }
* }
* </code></pre>
* <p>Commandline: </p>
* <code><pre>
* $ java ... Main greet hi --name bob
* Hello, bob.
* $ java ... Main greet remark --age 33
* I see you are 33 years old.
* </pre></code>
* <p>
* This constructs a {@link com.simplifyops.toolbelt.Tool} object, with a command "greet" (based on the class name
* Greet). "greet" has a "hi" and a "remark" subcommand. The class must have at least
* one method annotated with {@link com.simplifyops.toolbelt.Command @Command}. The parameters of that
* method (if any) should be annotated with {@link com.simplifyops.toolbelt.Arg @Arg} to define their names.
* (Alternately, if you compile your java class with {@code -parameters} flag to javac, the parameter names will be
* introspected.)
* This will use the {@link com.simplifyops.toolbelt.SimpleCommandInput} to parse "--somearg value" for a
* method parameter with arg name "somearg".
* </p>
* <p>You can define multiple commands (with their subcommands) in one step:</p>
* <code><pre>
* ToolBelt.with(new Command1(), new Command2(),...).runMain(args);
* </pre></code>
* <p>
* For more advanced usage, see below:
* </p>
* <p>
* Use {@link com.simplifyops.toolbelt.ToolBelt#belt()} to create a builder.
* </p>
* <pre><code>
* ToolBelt.belt()
* .defaultHelp()
* .systemOutput()
* .addCommands(
* new MyCommand(),
* new MyCommand2()
* )
* .setParser(new JewelInput())
* .buckle();
* </code></pre>
* <p>
* Within your MyCommand classes, use the {@link com.simplifyops.toolbelt.Command @Command} annotation to indicate the
* class is a top-level command (optional). Add the same annotation on any methods within the class to expose them
* as subcommands. At least one method should be annotated this way.
* </p>
* <pre><code>
* {@literal @}Command(description = "Does something", name="doit")
* public class MyCommand{
* {@literal @}Command(name="sub1") public void sub1(InputArgs args){
* System.out.println("Input args: "+args);
* }
* }
* </code></pre>
*
* <p>
* The annotation can exclude the "name" attribute, and the lowercase name of the class or method is used as the
* command/subcommand. The method parameters will be parsed using the input parser (e.g. JewelCLI), so
* <code>InputArgs</code> must be defined with appropriate annotations.
*
* </p>
* <h2>Using HasSubCommand interface:</h2>
* <p>
* If a {@literal @}Command annotated class wants to define a subcommand which is also a container (has subcommands of
* its own), It should implement {@link com.simplifyops.toolbelt.HasSubCommands}, and return a list of command
* container objects.
* </p>
*<code><pre>
* {@literal @}Command class First implements HasSubCommands{
*
* {@literal @}Command void something(){
* System.out.println("This method prints something")
* }
*
* List<Object> getCommands(){
* return Arrays.asList(new Second());
* }
* }
* {@literal @}Command class Second{
* {@literal @}Command void third(){
* System.out.println("Third level nested command");
* }
* }
*</pre></code>
* <p>This will define an interface like:
*
* </p>
* <code><pre>
* $ java ... First
* Available commands: [something, second]
* $ java ... First something
* This method prints something
* $ java ... First second
* Availabe commands: [third]
* $ java ... First second third
* Third level nested command
* </pre></code>
*/
package com.simplifyops.toolbelt; | fix javadoc
| toolbelt/src/main/java/com/simplifyops/toolbelt/package-info.java | fix javadoc | <ide><path>oolbelt/src/main/java/com/simplifyops/toolbelt/package-info.java
<ide> * For more advanced usage, see below:
<ide> * </p>
<ide> * <p>
<del> * Use {@link com.simplifyops.toolbelt.ToolBelt#belt()} to create a builder.
<add> * Use {@link com.simplifyops.toolbelt.ToolBelt#belt(java.lang.String)} to create a builder.
<ide> * </p>
<ide> * <pre><code>
<ide> * ToolBelt.belt() |
|
Java | isc | fa0d11c27edd5579af7ef290f089d115339a3739 | 0 | j256/simplejmx,j256/simplejmx | package com.j256.simplejmx.server;
import com.j256.simplejmx.common.JmxAttributeField;
import com.j256.simplejmx.common.JmxAttributeMethod;
import com.j256.simplejmx.common.JmxOperation;
import com.j256.simplejmx.common.JmxResource;
/**
* Here's a little example program that was written to show off the basic features of SimpleJmx.
*
* <p>
* <b>NOTE:</b> This is posted on the http://256.com/sources/simplejmx/ website.
* </p>
*
* @author graywatson
*/
public class ExampleTestProgram {
private static final int JMX_PORT = 8000;
public static void main(String[] args) throws Exception {
new ExampleTestProgram().doMain(args);
}
private void doMain(String[] args) throws Exception {
// create the object we will be exposing with JMX
RuntimeCounter counter = new RuntimeCounter();
// create a new JMX server listening on a port
JmxServer jmxServer = new JmxServer(JMX_PORT);
try {
// start our server
jmxServer.start();
// register our object
jmxServer.register(counter);
// we can register other objects here
// jmxServer.register(someOtherObject);
// do your other code here...
// we just sleep forever to let the server do its stuff
System.out.println("Sleeping for a while to let the server do its stuff");
Thread.sleep(1000000000);
} finally {
// unregister is not necessary if we are stopping the server
jmxServer.unregister(counter);
// stop our server
jmxServer.stop();
}
}
/**
* Here is our little bean that we are exposing via JMX. It can be in another class. It's just an inner class here
* for convenience.
*/
@JmxResource(description = "Runtime counter", domainName = "j256", beanName = "RuntimeCounter")
public static class RuntimeCounter {
// start our timer
private long startMillis = System.currentTimeMillis();
// we can annotate fields directly to be published in JMX, isReadible defaults to true
@JmxAttributeField(description = "Show runtime in seconds", isWritable = true)
private boolean showSeconds;
// we can annotate getter methods
@JmxAttributeMethod(description = "Run time in seconds or milliseconds")
public long getRunTime() {
// show how long we are running
long diffMillis = System.currentTimeMillis() - startMillis;
if (showSeconds) {
// as seconds
return diffMillis / 1000;
} else {
// or as milliseconds
return diffMillis;
}
}
/*
* NOTE: there is no setRunTime(...) so it won't be writable.
*/
// this is an operation that shows up in the operations tab in jconsole.
@JmxOperation(description = "Reset our start time to the current millis")
public String resetStartTime() {
startMillis = System.currentTimeMillis();
return "Timer has been reset to current millis";
}
}
}
| src/test/java/com/j256/simplejmx/server/ExampleTestProgram.java | package com.j256.simplejmx.server;
import com.j256.simplejmx.common.JmxAttributeField;
import com.j256.simplejmx.common.JmxAttributeMethod;
import com.j256.simplejmx.common.JmxOperation;
import com.j256.simplejmx.common.JmxResource;
/**
* Here's a little example program that was written to show off the basic features of SimpleJmx.
*
* <p>
* <b>NOTE:</b> This is posted on the http://256.com/sources/simplejmx/ website.
* </p>
*
* @author graywatson
*/
public class ExampleTestProgram {
private static final int JMX_PORT = 8000;
public static void main(String[] args) throws Exception {
new ExampleTestProgram().doMain(args);
}
private void doMain(String[] args) throws Exception {
// create the object we will be exposing with JMX
RuntimeCounter lookupCache = new RuntimeCounter();
// create a new JMX server listening on a port
JmxServer jmxServer = new JmxServer(JMX_PORT);
try {
// start our server
jmxServer.start();
// register our lookupCache object defined below
jmxServer.register(lookupCache);
// we can register other objects here
// jmxServer.register(someOtherObject);
// do your other code here...
// we just sleep forever to let the server do its stuff
System.out.println("Sleeping for a while to let the server do its stuff");
Thread.sleep(1000000000);
} finally {
// unregister is not necessary if we are stopping the server
jmxServer.unregister(lookupCache);
// stop our server
jmxServer.stop();
}
}
/**
* Here is our little bean that we are exposing via JMX. It can be in another class. It's just an inner class here
* for convenience.
*/
@JmxResource(description = "Runtime counter", domainName = "j256", beanName = "RuntimeCounter")
public static class RuntimeCounter {
// start our timer
private long startMillis = System.currentTimeMillis();
// we can annotate fields directly to be published in JMX, isReadible defaults to true
@JmxAttributeField(description = "Show runtime in seconds", isWritable = true)
private boolean showSeconds;
// we can annotate getter methods
@JmxAttributeMethod(description = "Run time in seconds or milliseconds")
public long getRunTime() {
// show how long we are running
long diffMillis = System.currentTimeMillis() - startMillis;
if (showSeconds) {
// as seconds
return diffMillis / 1000;
} else {
// or as milliseconds
return diffMillis;
}
}
/*
* NOTE: there is no setRunTime(...) so it won't be writable.
*/
// this is an operation that shows up in the operations tab in jconsole.
@JmxOperation(description = "Restart our timer")
public String restartTimer() {
startMillis = System.currentTimeMillis();
return "Timer has been restarted";
}
}
}
| Improved some the names.
| src/test/java/com/j256/simplejmx/server/ExampleTestProgram.java | Improved some the names. | <ide><path>rc/test/java/com/j256/simplejmx/server/ExampleTestProgram.java
<ide> private void doMain(String[] args) throws Exception {
<ide>
<ide> // create the object we will be exposing with JMX
<del> RuntimeCounter lookupCache = new RuntimeCounter();
<add> RuntimeCounter counter = new RuntimeCounter();
<ide>
<ide> // create a new JMX server listening on a port
<ide> JmxServer jmxServer = new JmxServer(JMX_PORT);
<ide> // start our server
<ide> jmxServer.start();
<ide>
<del> // register our lookupCache object defined below
<del> jmxServer.register(lookupCache);
<add> // register our object
<add> jmxServer.register(counter);
<ide> // we can register other objects here
<ide> // jmxServer.register(someOtherObject);
<ide>
<ide>
<ide> } finally {
<ide> // unregister is not necessary if we are stopping the server
<del> jmxServer.unregister(lookupCache);
<add> jmxServer.unregister(counter);
<ide> // stop our server
<ide> jmxServer.stop();
<ide> }
<ide> */
<ide>
<ide> // this is an operation that shows up in the operations tab in jconsole.
<del> @JmxOperation(description = "Restart our timer")
<del> public String restartTimer() {
<add> @JmxOperation(description = "Reset our start time to the current millis")
<add> public String resetStartTime() {
<ide> startMillis = System.currentTimeMillis();
<del> return "Timer has been restarted";
<add> return "Timer has been reset to current millis";
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | c70fa241f5a3f939efbbf16e47a3d4953de27f38 | 0 | zimingd/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services | package org.sagebionetworks.repo.manager.team;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
import static org.sagebionetworks.repo.manager.team.MembershipInvitationManagerImpl.TWENTY_FOUR_HOURS_IN_MS;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.sagebionetworks.reflection.model.PaginatedResults;
import org.sagebionetworks.repo.manager.AuthorizationManager;
import org.sagebionetworks.repo.manager.AuthorizationManagerUtil;
import org.sagebionetworks.repo.manager.MessageToUserAndBody;
import org.sagebionetworks.repo.manager.principal.SynapseEmailService;
import org.sagebionetworks.repo.manager.token.TokenGenerator;
import org.sagebionetworks.repo.model.ACCESS_TYPE;
import org.sagebionetworks.repo.model.Count;
import org.sagebionetworks.repo.model.InvalidModelException;
import org.sagebionetworks.repo.model.InviteeVerificationSignedToken;
import org.sagebionetworks.repo.model.MembershipInvitation;
import org.sagebionetworks.repo.model.MembershipInvitationDAO;
import org.sagebionetworks.repo.model.MembershipInvtnSignedToken;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.Team;
import org.sagebionetworks.repo.model.TeamDAO;
import org.sagebionetworks.repo.model.UnauthorizedException;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.principal.PrincipalAliasDAO;
import org.springframework.test.util.ReflectionTestUtils;
import com.amazonaws.services.simpleemail.model.SendRawEmailRequest;
@RunWith(MockitoJUnitRunner.class)
public class MembershipInvitationManagerImplTest {
private MembershipInvitationManagerImpl membershipInvitationManagerImpl;
@Mock
private AuthorizationManager mockAuthorizationManager = null;
@Mock
private MembershipInvitationDAO mockMembershipInvitationDAO = null;
@Mock
private TeamDAO mockTeamDAO = null;
@Mock
private SynapseEmailService mockSynapseEmailService;
@Mock
private TokenGenerator tokenGenerator;
private UserInfo userInfo = null;
private static final String MEMBER_PRINCIPAL_ID = "999";
private static final String INVITEE_EMAIL = "[email protected]";
private static final String TEAM_ID = "123";
private static final String MIS_ID = "987";
private static MembershipInvitation createMembershipInvtnSubmission(String id) {
MembershipInvitation mis = new MembershipInvitation();
mis.setId(id);
mis.setTeamId(TEAM_ID);
mis.setInviteeId(MEMBER_PRINCIPAL_ID);
mis.setMessage("Please join our team.");
return mis;
}
private static MembershipInvitation createMembershipInvtnSubmissionToEmail(String id) {
MembershipInvitation mis = new MembershipInvitation();
mis.setId(id);
mis.setTeamId(TEAM_ID);
mis.setInviteeEmail(INVITEE_EMAIL);
Date now = new Date();
mis.setCreatedOn(now);
mis.setExpiresOn(new Date(now.getTime() + TWENTY_FOUR_HOURS_IN_MS));
mis.setMessage("Please join our team.");
return mis;
}
private static MembershipInvitation createMembershipInvitation() {
MembershipInvitation mis = new MembershipInvitation();
mis.setTeamId(TEAM_ID);
mis.setInviteeId(MEMBER_PRINCIPAL_ID);
return mis;
}
@Before
public void setUp() throws Exception {
this.membershipInvitationManagerImpl = new MembershipInvitationManagerImpl();
ReflectionTestUtils.setField(membershipInvitationManagerImpl, "authorizationManager", mockAuthorizationManager);
ReflectionTestUtils.setField(membershipInvitationManagerImpl, "membershipInvitationDAO",
mockMembershipInvitationDAO);
ReflectionTestUtils.setField(membershipInvitationManagerImpl, "teamDAO", mockTeamDAO);
ReflectionTestUtils.setField(membershipInvitationManagerImpl, "sesClient", mockSynapseEmailService);
ReflectionTestUtils.setField(membershipInvitationManagerImpl, "tokenGenerator", tokenGenerator);
userInfo = new UserInfo(false, MEMBER_PRINCIPAL_ID);
}
private void validateForCreateExpectFailure(MembershipInvitation mis) {
try {
MembershipInvitationManagerImpl.validateForCreate(mis);
fail("InvalidModelException expected");
} catch (InvalidModelException e) {
// as expected
}
}
@Test
public void testValidateForCreate() throws Exception {
MembershipInvitation mis = new MembershipInvitation();
// Happy case
mis.setTeamId("101");
mis.setInviteeId(MEMBER_PRINCIPAL_ID);
MembershipInvitationManagerImpl.validateForCreate(mis);
// can't set createdBy
mis.setTeamId("101");
mis.setInviteeId(MEMBER_PRINCIPAL_ID);
mis.setCreatedBy("me");
validateForCreateExpectFailure(mis);
// must set invitees
mis.setTeamId("101");
mis.setInviteeId(null);
mis.setCreatedBy(null);
validateForCreateExpectFailure(mis);
// can't set createdOn
mis.setTeamId("101");
mis.setInviteeId(MEMBER_PRINCIPAL_ID);
mis.setCreatedBy(null);
mis.setCreatedOn(new Date());
validateForCreateExpectFailure(mis);
// must set Team
mis.setTeamId(null);
mis.setInviteeId(MEMBER_PRINCIPAL_ID);
mis.setCreatedBy(null);
mis.setCreatedOn(null);
validateForCreateExpectFailure(mis);
// can't set id
mis.setTeamId("101");
mis.setInviteeId(MEMBER_PRINCIPAL_ID);
mis.setCreatedBy(null);
mis.setCreatedOn(null);
mis.setId("007");
validateForCreateExpectFailure(mis);
}
@Test
public void testPopulateCreationFields() throws Exception {
MembershipInvitation mis = new MembershipInvitation();
Date now = new Date();
MembershipInvitationManagerImpl.populateCreationFields(userInfo, mis, now);
assertEquals(MEMBER_PRINCIPAL_ID, mis.getCreatedBy());
assertEquals(now, mis.getCreatedOn());
}
@Test(expected = UnauthorizedException.class)
public void testNonAdminCreate() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(null);
when(mockAuthorizationManager.canAccessMembershipInvitation(userInfo, mis, ACCESS_TYPE.CREATE))
.thenReturn(AuthorizationManagerUtil.ACCESS_DENIED);
membershipInvitationManagerImpl.create(userInfo, mis);
}
@Test
public void testAdminCreate() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(null);
when(mockAuthorizationManager.canAccessMembershipInvitation(userInfo, mis, ACCESS_TYPE.CREATE))
.thenReturn(AuthorizationManagerUtil.AUTHORIZED);
membershipInvitationManagerImpl.create(userInfo, mis);
Mockito.verify(mockMembershipInvitationDAO).create(mis);
}
@Test(expected = UnauthorizedException.class)
public void testNonAdminGet() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
when(mockAuthorizationManager.canAccessMembershipInvitation(userInfo, mis, ACCESS_TYPE.READ))
.thenReturn(AuthorizationManagerUtil.ACCESS_DENIED);
when(mockMembershipInvitationDAO.get(MIS_ID)).thenReturn(mis);
membershipInvitationManagerImpl.get(userInfo, MIS_ID);
}
@Test
public void testAdminGet() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
when(mockAuthorizationManager.canAccessMembershipInvitation(userInfo, mis, ACCESS_TYPE.READ))
.thenReturn(AuthorizationManagerUtil.AUTHORIZED);
when(mockMembershipInvitationDAO.get(MIS_ID)).thenReturn(mis);
assertEquals(mis, membershipInvitationManagerImpl.get(userInfo, MIS_ID));
}
@Test
public void testGetWithMembershipInvtnSignedToken() {
MembershipInvitation mis = createMembershipInvtnSubmissionToEmail(MIS_ID);
MembershipInvtnSignedToken token = new MembershipInvtnSignedToken();
when(mockAuthorizationManager.canAccessMembershipInvitation(any(MembershipInvtnSignedToken.class),
eq(ACCESS_TYPE.READ))).thenReturn(AuthorizationManagerUtil.AUTHORIZED);
when(mockMembershipInvitationDAO.get(MIS_ID)).thenReturn(mis);
assertEquals(mis, membershipInvitationManagerImpl.get(MIS_ID, token));
}
@Test(expected = UnauthorizedException.class)
public void testNonAdminDelete() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
when(mockAuthorizationManager.canAccessMembershipInvitation(userInfo, mis, ACCESS_TYPE.DELETE))
.thenReturn(AuthorizationManagerUtil.ACCESS_DENIED);
when(mockMembershipInvitationDAO.get(MIS_ID)).thenReturn(mis);
membershipInvitationManagerImpl.delete(userInfo, MIS_ID);
}
@Test
public void testAdminDelete() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
when(mockAuthorizationManager.canAccessMembershipInvitation(userInfo, mis, ACCESS_TYPE.DELETE))
.thenReturn(AuthorizationManagerUtil.AUTHORIZED);
when(mockMembershipInvitationDAO.get(MIS_ID)).thenReturn(mis);
membershipInvitationManagerImpl.delete(userInfo, MIS_ID);
Mockito.verify(mockMembershipInvitationDAO).delete(MIS_ID);
}
@Test
public void testGetOpenForUserInRange() throws Exception {
MembershipInvitation mis = createMembershipInvitation();
List<MembershipInvitation> expected = Arrays.asList(new MembershipInvitation[] { mis });
when(mockMembershipInvitationDAO.getOpenByUserInRange(eq(Long.parseLong(MEMBER_PRINCIPAL_ID)), anyLong(),
anyLong(), anyLong())).thenReturn(expected);
when(mockMembershipInvitationDAO.getOpenByUserCount(eq(Long.parseLong(MEMBER_PRINCIPAL_ID)), anyLong()))
.thenReturn((long) expected.size());
PaginatedResults<MembershipInvitation> actual = membershipInvitationManagerImpl
.getOpenForUserInRange(MEMBER_PRINCIPAL_ID, 1, 0);
assertEquals(expected, actual.getResults());
assertEquals(1L, actual.getTotalNumberOfResults());
}
@Test
public void testGetOpenForUserAndTeamInRange() throws Exception {
MembershipInvitation mis = createMembershipInvitation();
List<MembershipInvitation> expected = Arrays.asList(new MembershipInvitation[] { mis });
when(mockMembershipInvitationDAO.getOpenByTeamAndUserInRange(eq(Long.parseLong(TEAM_ID)),
eq(Long.parseLong(MEMBER_PRINCIPAL_ID)), anyLong(), anyLong(), anyLong())).thenReturn(expected);
when(mockMembershipInvitationDAO.getOpenByTeamAndUserCount(eq(Long.parseLong(TEAM_ID)),
eq(Long.parseLong(MEMBER_PRINCIPAL_ID)), anyLong())).thenReturn((long) expected.size());
PaginatedResults<MembershipInvitation> actual = membershipInvitationManagerImpl
.getOpenForUserAndTeamInRange(MEMBER_PRINCIPAL_ID, TEAM_ID, 1, 0);
assertEquals(expected, actual.getResults());
assertEquals(1L, actual.getTotalNumberOfResults());
}
@Test
public void testGetOpenSubmissionsForTeamInRange() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
when(mockAuthorizationManager.canAccess(userInfo, mis.getTeamId(), ObjectType.TEAM,
ACCESS_TYPE.TEAM_MEMBERSHIP_UPDATE)).thenReturn(AuthorizationManagerUtil.AUTHORIZED);
List<MembershipInvitation> expected = Arrays.asList(new MembershipInvitation[] { mis });
when(mockMembershipInvitationDAO.getOpenByTeamInRange(eq(Long.parseLong(TEAM_ID)), anyLong(), anyLong(),
anyLong())).thenReturn(expected);
when(mockMembershipInvitationDAO.getOpenByTeamCount(eq(Long.parseLong(TEAM_ID)), anyLong()))
.thenReturn((long) expected.size());
PaginatedResults<MembershipInvitation> actual = membershipInvitationManagerImpl
.getOpenSubmissionsForTeamInRange(userInfo, TEAM_ID, 1, 0);
assertEquals(expected, actual.getResults());
assertEquals(1L, actual.getTotalNumberOfResults());
}
@Test(expected = UnauthorizedException.class)
public void testGetOpenSubmissionsForTeamInRangeUnauthorized() throws Exception {
when(mockAuthorizationManager.canAccess(userInfo, TEAM_ID, ObjectType.TEAM, ACCESS_TYPE.TEAM_MEMBERSHIP_UPDATE))
.thenReturn(AuthorizationManagerUtil.ACCESS_DENIED);
membershipInvitationManagerImpl.getOpenSubmissionsForTeamInRange(userInfo, TEAM_ID, 1, 0);
}
@Test
public void testGetOpenSubmissionsForTeamAndRequesterInRange() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
when(mockAuthorizationManager.canAccess(userInfo, mis.getTeamId(), ObjectType.TEAM,
ACCESS_TYPE.TEAM_MEMBERSHIP_UPDATE)).thenReturn(AuthorizationManagerUtil.AUTHORIZED);
List<MembershipInvitation> expected = Arrays.asList(new MembershipInvitation[] { mis });
when(mockMembershipInvitationDAO.getOpenByTeamAndUserInRange(eq(Long.parseLong(TEAM_ID)), anyLong(), anyLong(),
anyLong(), anyLong())).thenReturn(expected);
when(mockMembershipInvitationDAO.getOpenByTeamCount(eq(Long.parseLong(TEAM_ID)), anyLong()))
.thenReturn((long) expected.size());
PaginatedResults<MembershipInvitation> actual = membershipInvitationManagerImpl
.getOpenSubmissionsForUserAndTeamInRange(userInfo, MEMBER_PRINCIPAL_ID, TEAM_ID, 1, 0);
assertEquals(expected, actual.getResults());
assertEquals(1L, actual.getTotalNumberOfResults());
}
@Test(expected = UnauthorizedException.class)
public void testGetOpenSubmissionsForTeamAndRequesterInRangeUnauthorized() throws Exception {
when(mockAuthorizationManager.canAccess(userInfo, TEAM_ID, ObjectType.TEAM, ACCESS_TYPE.TEAM_MEMBERSHIP_UPDATE))
.thenReturn(AuthorizationManagerUtil.ACCESS_DENIED);
membershipInvitationManagerImpl.getOpenSubmissionsForUserAndTeamInRange(userInfo, MEMBER_PRINCIPAL_ID, TEAM_ID,
1, 0);
}
@Test
public void testCreateInvitationToUser() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
testCreateInvitationToUserHelper(mis);
}
@Test
public void testCreateInvitationToUserWithNullCreatedOn() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
mis.setCreatedOn(null);
testCreateInvitationToUserHelper(mis);
}
private void testCreateInvitationToUserHelper(MembershipInvitation mis) {
Team team = new Team();
team.setName("test team");
team.setId(TEAM_ID);
when(mockTeamDAO.get(TEAM_ID)).thenReturn(team);
String acceptInvitationEndpoint = "https://synapse.org/#acceptInvitationEndpoint:";
String notificationUnsubscribeEndpoint = "https://synapse.org/#notificationUnsubscribeEndpoint:";
MessageToUserAndBody result = membershipInvitationManagerImpl.createInvitationMessageToUser(mis,
acceptInvitationEndpoint, notificationUnsubscribeEndpoint);
assertEquals("You Have Been Invited to Join a Team", result.getMetadata().getSubject());
assertEquals(Collections.singleton(MEMBER_PRINCIPAL_ID), result.getMetadata().getRecipients());
assertEquals(notificationUnsubscribeEndpoint, result.getMetadata().getNotificationUnsubscribeEndpoint());
assertTrue(result.getBody().contains(acceptInvitationEndpoint));
}
@Test
public void testSendInvitationToEmail() throws Exception {
Team team = new Team();
String teamName = "Test team";
team.setName(teamName);
team.setId(TEAM_ID);
when(mockTeamDAO.get(TEAM_ID)).thenReturn(team);
MembershipInvitation mis = createMembershipInvtnSubmissionToEmail(MIS_ID);
String acceptInvitationEndpoint = "https://synapse.org/#acceptInvitationEndpoint:";
membershipInvitationManagerImpl.sendInvitationToEmail(mis, acceptInvitationEndpoint);
ArgumentCaptor<SendRawEmailRequest> argument = ArgumentCaptor.forClass(SendRawEmailRequest.class);
Mockito.verify(mockSynapseEmailService).sendRawEmail(argument.capture());
SendRawEmailRequest emailRequest = argument.getValue();
assertEquals(Collections.singletonList(INVITEE_EMAIL), emailRequest.getDestinations());
MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()),
new ByteArrayInputStream(emailRequest.getRawMessage().getData().array()));
String body = (String) ((MimeMultipart) mimeMessage.getContent()).getBodyPart(0).getContent();
assertNotNull(mimeMessage.getSubject());
assertFalse(body.contains(mis.getTeamId())); //PLFM-5369: Users kept clicking the team page instead of joining the team via invitation link.
assertTrue(body.contains(teamName));
assertTrue(body.contains(mis.getMessage()));
assertTrue(body.contains(acceptInvitationEndpoint));
}
@Test(expected = IllegalArgumentException.class)
public void testGetOpenInvitationCountForUserWithNullPrincipalId() {
membershipInvitationManagerImpl.getOpenInvitationCountForUser(null);
}
@Test
public void testGetOpenInvitationCountForUser() {
Long count = 7L;
when(mockMembershipInvitationDAO.getOpenByUserCount(anyLong(), anyLong())).thenReturn(count);
Count result = membershipInvitationManagerImpl.getOpenInvitationCountForUser(MEMBER_PRINCIPAL_ID);
assertNotNull(result);
assertEquals(count, result.getCount());
}
@Test
public void testVerifyInvitee() {
// Setup
MembershipInvitation mis = createMembershipInvtnSubmissionToEmail(MIS_ID);
when(mockMembershipInvitationDAO.get(MIS_ID)).thenReturn(mis);
Long userId = Long.parseLong(MEMBER_PRINCIPAL_ID);
// Mock listPrincipalAliases to return one alias with the invitee email
PrincipalAliasDAO mockPrincipalAliasDAO = Mockito.mock(PrincipalAliasDAO.class);
ReflectionTestUtils.setField(membershipInvitationManagerImpl, "principalAliasDAO", mockPrincipalAliasDAO);
when(mockPrincipalAliasDAO.aliasIsBoundToPrincipal(INVITEE_EMAIL, MEMBER_PRINCIPAL_ID)).thenReturn(true);
// Test getInviteeVerificationSignedToken by inspecting the token it returns
InviteeVerificationSignedToken token = membershipInvitationManagerImpl.getInviteeVerificationSignedToken(userId,
MIS_ID);
assertNotNull(token);
assertEquals(MEMBER_PRINCIPAL_ID, token.getInviteeId());
assertEquals(MIS_ID, token.getMembershipInvitationId());
tokenGenerator.validateToken(token);
// Test failure cases
// Failure 1 - mis is expired
Date expiresOn = mis.getExpiresOn();
mis.setExpiresOn(new Date(new Date().getTime() - 999999L));
boolean caughtException = false;
try {
membershipInvitationManagerImpl.getInviteeVerificationSignedToken(userId, MIS_ID);
} catch (IllegalArgumentException e) {
caughtException = true;
}
assertTrue(caughtException);
// Restore expiresOn
mis.setExpiresOn(expiresOn);
// Failure 2 - inviteeId is set
mis.setInviteeId("not-null");
caughtException = false;
try {
membershipInvitationManagerImpl.getInviteeVerificationSignedToken(userId, MIS_ID);
} catch (IllegalArgumentException e) {
caughtException = true;
}
assertTrue(caughtException);
mis.setInviteeId(null);
// Failure 3 - invitee email is not associated with user
when(mockPrincipalAliasDAO.aliasIsBoundToPrincipal(INVITEE_EMAIL, MEMBER_PRINCIPAL_ID)).thenReturn(false);
caughtException = false;
try {
membershipInvitationManagerImpl.getInviteeVerificationSignedToken(userId, MIS_ID);
} catch (UnauthorizedException e) {
caughtException = true;
}
assertTrue(caughtException);
}
@Test
public void testUpdateId() {
// Setup
Long userId = Long.parseLong(MEMBER_PRINCIPAL_ID);
MembershipInvitation mis = createMembershipInvtnSubmissionToEmail(MIS_ID);
InviteeVerificationSignedToken token = new InviteeVerificationSignedToken();
token.setMembershipInvitationId(MIS_ID);
token.setExpiresOn(mis.getExpiresOn());
// Mock happy case behavior
when(mockAuthorizationManager.canAccessMembershipInvitation(userId, token, ACCESS_TYPE.UPDATE))
.thenReturn(AuthorizationManagerUtil.AUTHORIZED);
when(mockMembershipInvitationDAO.getWithUpdateLock(MIS_ID)).thenReturn(mis);
// Happy case should succeed
membershipInvitationManagerImpl.updateInviteeId(userId, MIS_ID, token);
Mockito.verify(mockMembershipInvitationDAO).updateInviteeId(MIS_ID, userId);
// URI id and signed token id should match
boolean caughtException = false;
try {
membershipInvitationManagerImpl.updateInviteeId(userId, "incorrectId", token);
} catch (IllegalArgumentException e) {
caughtException = true;
}
assertTrue(caughtException);
// Token with null expiresOn should fail
token.setExpiresOn(null);
caughtException = false;
try {
membershipInvitationManagerImpl.updateInviteeId(userId, MIS_ID, token);
} catch (IllegalArgumentException e) {
caughtException = true;
}
assertTrue(caughtException);
// Restore valid expiration date
token.setExpiresOn(mis.getExpiresOn());
// Expired token should fail
token.setExpiresOn(new Date(new Date().getTime() - TWENTY_FOUR_HOURS_IN_MS));
caughtException = false;
try {
membershipInvitationManagerImpl.updateInviteeId(userId, MIS_ID, token);
} catch (IllegalArgumentException e) {
caughtException = true;
}
assertTrue(caughtException);
// Restore valid expiration date
token.setExpiresOn(mis.getExpiresOn());
// Mock the authorization manager so that it denies access
when(mockAuthorizationManager.canAccessMembershipInvitation(userId, token, ACCESS_TYPE.UPDATE))
.thenReturn(AuthorizationManagerUtil.ACCESS_DENIED);
// Updating the inviteeId should throw an UnauthorizedException
caughtException = false;
try {
membershipInvitationManagerImpl.updateInviteeId(userId, MIS_ID, token);
} catch (UnauthorizedException e) {
caughtException = true;
}
assertTrue(caughtException);
// Restore the authorization manager to allow access again
when(mockAuthorizationManager.canAccessMembershipInvitation(userId, token, ACCESS_TYPE.UPDATE))
.thenReturn(AuthorizationManagerUtil.AUTHORIZED);
// Set the existing invitation's inviteeId
mis.setInviteeId(userId.toString());
// Updating the inviteeId should throw an UnauthorizedException
caughtException = false;
try {
membershipInvitationManagerImpl.updateInviteeId(userId, MIS_ID, token);
} catch (IllegalArgumentException e) {
caughtException = true;
}
assertTrue(caughtException);
}
}
| services/repository-managers/src/test/java/org/sagebionetworks/repo/manager/team/MembershipInvitationManagerImplTest.java | package org.sagebionetworks.repo.manager.team;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
import static org.sagebionetworks.repo.manager.team.MembershipInvitationManagerImpl.TWENTY_FOUR_HOURS_IN_MS;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.sagebionetworks.reflection.model.PaginatedResults;
import org.sagebionetworks.repo.manager.AuthorizationManager;
import org.sagebionetworks.repo.manager.AuthorizationManagerUtil;
import org.sagebionetworks.repo.manager.MessageToUserAndBody;
import org.sagebionetworks.repo.manager.principal.SynapseEmailService;
import org.sagebionetworks.repo.manager.token.TokenGenerator;
import org.sagebionetworks.repo.model.ACCESS_TYPE;
import org.sagebionetworks.repo.model.Count;
import org.sagebionetworks.repo.model.InvalidModelException;
import org.sagebionetworks.repo.model.InviteeVerificationSignedToken;
import org.sagebionetworks.repo.model.MembershipInvitation;
import org.sagebionetworks.repo.model.MembershipInvitationDAO;
import org.sagebionetworks.repo.model.MembershipInvtnSignedToken;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.Team;
import org.sagebionetworks.repo.model.TeamDAO;
import org.sagebionetworks.repo.model.UnauthorizedException;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.principal.PrincipalAliasDAO;
import org.springframework.test.util.ReflectionTestUtils;
import com.amazonaws.services.simpleemail.model.SendRawEmailRequest;
@RunWith(MockitoJUnitRunner.class)
public class MembershipInvitationManagerImplTest {
private MembershipInvitationManagerImpl membershipInvitationManagerImpl;
@Mock
private AuthorizationManager mockAuthorizationManager = null;
@Mock
private MembershipInvitationDAO mockMembershipInvitationDAO = null;
@Mock
private TeamDAO mockTeamDAO = null;
@Mock
private SynapseEmailService mockSynapseEmailService;
@Mock
private TokenGenerator tokenGenerator;
private UserInfo userInfo = null;
private static final String MEMBER_PRINCIPAL_ID = "999";
private static final String INVITEE_EMAIL = "[email protected]";
private static final String TEAM_ID = "123";
private static final String MIS_ID = "987";
private static MembershipInvitation createMembershipInvtnSubmission(String id) {
MembershipInvitation mis = new MembershipInvitation();
mis.setId(id);
mis.setTeamId(TEAM_ID);
mis.setInviteeId(MEMBER_PRINCIPAL_ID);
mis.setMessage("Please join our team.");
return mis;
}
private static MembershipInvitation createMembershipInvtnSubmissionToEmail(String id) {
MembershipInvitation mis = new MembershipInvitation();
mis.setId(id);
mis.setTeamId(TEAM_ID);
mis.setInviteeEmail(INVITEE_EMAIL);
Date now = new Date();
mis.setCreatedOn(now);
mis.setExpiresOn(new Date(now.getTime() + TWENTY_FOUR_HOURS_IN_MS));
mis.setMessage("Please join our team.");
return mis;
}
private static MembershipInvitation createMembershipInvitation() {
MembershipInvitation mis = new MembershipInvitation();
mis.setTeamId(TEAM_ID);
mis.setInviteeId(MEMBER_PRINCIPAL_ID);
return mis;
}
@Before
public void setUp() throws Exception {
this.membershipInvitationManagerImpl = new MembershipInvitationManagerImpl();
ReflectionTestUtils.setField(membershipInvitationManagerImpl, "authorizationManager", mockAuthorizationManager);
ReflectionTestUtils.setField(membershipInvitationManagerImpl, "membershipInvitationDAO",
mockMembershipInvitationDAO);
ReflectionTestUtils.setField(membershipInvitationManagerImpl, "teamDAO", mockTeamDAO);
ReflectionTestUtils.setField(membershipInvitationManagerImpl, "sesClient", mockSynapseEmailService);
ReflectionTestUtils.setField(membershipInvitationManagerImpl, "tokenGenerator", tokenGenerator);
userInfo = new UserInfo(false, MEMBER_PRINCIPAL_ID);
}
private void validateForCreateExpectFailure(MembershipInvitation mis) {
try {
MembershipInvitationManagerImpl.validateForCreate(mis);
fail("InvalidModelException expected");
} catch (InvalidModelException e) {
// as expected
}
}
@Test
public void testValidateForCreate() throws Exception {
MembershipInvitation mis = new MembershipInvitation();
// Happy case
mis.setTeamId("101");
mis.setInviteeId(MEMBER_PRINCIPAL_ID);
MembershipInvitationManagerImpl.validateForCreate(mis);
// can't set createdBy
mis.setTeamId("101");
mis.setInviteeId(MEMBER_PRINCIPAL_ID);
mis.setCreatedBy("me");
validateForCreateExpectFailure(mis);
// must set invitees
mis.setTeamId("101");
mis.setInviteeId(null);
mis.setCreatedBy(null);
validateForCreateExpectFailure(mis);
// can't set createdOn
mis.setTeamId("101");
mis.setInviteeId(MEMBER_PRINCIPAL_ID);
mis.setCreatedBy(null);
mis.setCreatedOn(new Date());
validateForCreateExpectFailure(mis);
// must set Team
mis.setTeamId(null);
mis.setInviteeId(MEMBER_PRINCIPAL_ID);
mis.setCreatedBy(null);
mis.setCreatedOn(null);
validateForCreateExpectFailure(mis);
// can't set id
mis.setTeamId("101");
mis.setInviteeId(MEMBER_PRINCIPAL_ID);
mis.setCreatedBy(null);
mis.setCreatedOn(null);
mis.setId("007");
validateForCreateExpectFailure(mis);
}
@Test
public void testPopulateCreationFields() throws Exception {
MembershipInvitation mis = new MembershipInvitation();
Date now = new Date();
MembershipInvitationManagerImpl.populateCreationFields(userInfo, mis, now);
assertEquals(MEMBER_PRINCIPAL_ID, mis.getCreatedBy());
assertEquals(now, mis.getCreatedOn());
}
@Test(expected = UnauthorizedException.class)
public void testNonAdminCreate() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(null);
when(mockAuthorizationManager.canAccessMembershipInvitation(userInfo, mis, ACCESS_TYPE.CREATE))
.thenReturn(AuthorizationManagerUtil.ACCESS_DENIED);
membershipInvitationManagerImpl.create(userInfo, mis);
}
@Test
public void testAdminCreate() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(null);
when(mockAuthorizationManager.canAccessMembershipInvitation(userInfo, mis, ACCESS_TYPE.CREATE))
.thenReturn(AuthorizationManagerUtil.AUTHORIZED);
membershipInvitationManagerImpl.create(userInfo, mis);
Mockito.verify(mockMembershipInvitationDAO).create(mis);
}
@Test(expected = UnauthorizedException.class)
public void testNonAdminGet() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
when(mockAuthorizationManager.canAccessMembershipInvitation(userInfo, mis, ACCESS_TYPE.READ))
.thenReturn(AuthorizationManagerUtil.ACCESS_DENIED);
when(mockMembershipInvitationDAO.get(MIS_ID)).thenReturn(mis);
membershipInvitationManagerImpl.get(userInfo, MIS_ID);
}
@Test
public void testAdminGet() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
when(mockAuthorizationManager.canAccessMembershipInvitation(userInfo, mis, ACCESS_TYPE.READ))
.thenReturn(AuthorizationManagerUtil.AUTHORIZED);
when(mockMembershipInvitationDAO.get(MIS_ID)).thenReturn(mis);
assertEquals(mis, membershipInvitationManagerImpl.get(userInfo, MIS_ID));
}
@Test
public void testGetWithMembershipInvtnSignedToken() {
MembershipInvitation mis = createMembershipInvtnSubmissionToEmail(MIS_ID);
MembershipInvtnSignedToken token = new MembershipInvtnSignedToken();
when(mockAuthorizationManager.canAccessMembershipInvitation(any(MembershipInvtnSignedToken.class),
eq(ACCESS_TYPE.READ))).thenReturn(AuthorizationManagerUtil.AUTHORIZED);
when(mockMembershipInvitationDAO.get(MIS_ID)).thenReturn(mis);
assertEquals(mis, membershipInvitationManagerImpl.get(MIS_ID, token));
}
@Test(expected = UnauthorizedException.class)
public void testNonAdminDelete() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
when(mockAuthorizationManager.canAccessMembershipInvitation(userInfo, mis, ACCESS_TYPE.DELETE))
.thenReturn(AuthorizationManagerUtil.ACCESS_DENIED);
when(mockMembershipInvitationDAO.get(MIS_ID)).thenReturn(mis);
membershipInvitationManagerImpl.delete(userInfo, MIS_ID);
}
@Test
public void testAdminDelete() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
when(mockAuthorizationManager.canAccessMembershipInvitation(userInfo, mis, ACCESS_TYPE.DELETE))
.thenReturn(AuthorizationManagerUtil.AUTHORIZED);
when(mockMembershipInvitationDAO.get(MIS_ID)).thenReturn(mis);
membershipInvitationManagerImpl.delete(userInfo, MIS_ID);
Mockito.verify(mockMembershipInvitationDAO).delete(MIS_ID);
}
@Test
public void testGetOpenForUserInRange() throws Exception {
MembershipInvitation mis = createMembershipInvitation();
List<MembershipInvitation> expected = Arrays.asList(new MembershipInvitation[] { mis });
when(mockMembershipInvitationDAO.getOpenByUserInRange(eq(Long.parseLong(MEMBER_PRINCIPAL_ID)), anyLong(),
anyLong(), anyLong())).thenReturn(expected);
when(mockMembershipInvitationDAO.getOpenByUserCount(eq(Long.parseLong(MEMBER_PRINCIPAL_ID)), anyLong()))
.thenReturn((long) expected.size());
PaginatedResults<MembershipInvitation> actual = membershipInvitationManagerImpl
.getOpenForUserInRange(MEMBER_PRINCIPAL_ID, 1, 0);
assertEquals(expected, actual.getResults());
assertEquals(1L, actual.getTotalNumberOfResults());
}
@Test
public void testGetOpenForUserAndTeamInRange() throws Exception {
MembershipInvitation mis = createMembershipInvitation();
List<MembershipInvitation> expected = Arrays.asList(new MembershipInvitation[] { mis });
when(mockMembershipInvitationDAO.getOpenByTeamAndUserInRange(eq(Long.parseLong(TEAM_ID)),
eq(Long.parseLong(MEMBER_PRINCIPAL_ID)), anyLong(), anyLong(), anyLong())).thenReturn(expected);
when(mockMembershipInvitationDAO.getOpenByTeamAndUserCount(eq(Long.parseLong(TEAM_ID)),
eq(Long.parseLong(MEMBER_PRINCIPAL_ID)), anyLong())).thenReturn((long) expected.size());
PaginatedResults<MembershipInvitation> actual = membershipInvitationManagerImpl
.getOpenForUserAndTeamInRange(MEMBER_PRINCIPAL_ID, TEAM_ID, 1, 0);
assertEquals(expected, actual.getResults());
assertEquals(1L, actual.getTotalNumberOfResults());
}
@Test
public void testGetOpenSubmissionsForTeamInRange() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
when(mockAuthorizationManager.canAccess(userInfo, mis.getTeamId(), ObjectType.TEAM,
ACCESS_TYPE.TEAM_MEMBERSHIP_UPDATE)).thenReturn(AuthorizationManagerUtil.AUTHORIZED);
List<MembershipInvitation> expected = Arrays.asList(new MembershipInvitation[] { mis });
when(mockMembershipInvitationDAO.getOpenByTeamInRange(eq(Long.parseLong(TEAM_ID)), anyLong(), anyLong(),
anyLong())).thenReturn(expected);
when(mockMembershipInvitationDAO.getOpenByTeamCount(eq(Long.parseLong(TEAM_ID)), anyLong()))
.thenReturn((long) expected.size());
PaginatedResults<MembershipInvitation> actual = membershipInvitationManagerImpl
.getOpenSubmissionsForTeamInRange(userInfo, TEAM_ID, 1, 0);
assertEquals(expected, actual.getResults());
assertEquals(1L, actual.getTotalNumberOfResults());
}
@Test(expected = UnauthorizedException.class)
public void testGetOpenSubmissionsForTeamInRangeUnauthorized() throws Exception {
when(mockAuthorizationManager.canAccess(userInfo, TEAM_ID, ObjectType.TEAM, ACCESS_TYPE.TEAM_MEMBERSHIP_UPDATE))
.thenReturn(AuthorizationManagerUtil.ACCESS_DENIED);
membershipInvitationManagerImpl.getOpenSubmissionsForTeamInRange(userInfo, TEAM_ID, 1, 0);
}
@Test
public void testGetOpenSubmissionsForTeamAndRequesterInRange() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
when(mockAuthorizationManager.canAccess(userInfo, mis.getTeamId(), ObjectType.TEAM,
ACCESS_TYPE.TEAM_MEMBERSHIP_UPDATE)).thenReturn(AuthorizationManagerUtil.AUTHORIZED);
List<MembershipInvitation> expected = Arrays.asList(new MembershipInvitation[] { mis });
when(mockMembershipInvitationDAO.getOpenByTeamAndUserInRange(eq(Long.parseLong(TEAM_ID)), anyLong(), anyLong(),
anyLong(), anyLong())).thenReturn(expected);
when(mockMembershipInvitationDAO.getOpenByTeamCount(eq(Long.parseLong(TEAM_ID)), anyLong()))
.thenReturn((long) expected.size());
PaginatedResults<MembershipInvitation> actual = membershipInvitationManagerImpl
.getOpenSubmissionsForUserAndTeamInRange(userInfo, MEMBER_PRINCIPAL_ID, TEAM_ID, 1, 0);
assertEquals(expected, actual.getResults());
assertEquals(1L, actual.getTotalNumberOfResults());
}
@Test(expected = UnauthorizedException.class)
public void testGetOpenSubmissionsForTeamAndRequesterInRangeUnauthorized() throws Exception {
when(mockAuthorizationManager.canAccess(userInfo, TEAM_ID, ObjectType.TEAM, ACCESS_TYPE.TEAM_MEMBERSHIP_UPDATE))
.thenReturn(AuthorizationManagerUtil.ACCESS_DENIED);
membershipInvitationManagerImpl.getOpenSubmissionsForUserAndTeamInRange(userInfo, MEMBER_PRINCIPAL_ID, TEAM_ID,
1, 0);
}
@Test
public void testCreateInvitationToUser() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
testCreateInvitationToUserHelper(mis);
}
@Test
public void testCreateInvitationToUserWithNullCreatedOn() throws Exception {
MembershipInvitation mis = createMembershipInvtnSubmission(MIS_ID);
mis.setCreatedOn(null);
testCreateInvitationToUserHelper(mis);
}
private void testCreateInvitationToUserHelper(MembershipInvitation mis) {
Team team = new Team();
team.setName("test team");
team.setId(TEAM_ID);
when(mockTeamDAO.get(TEAM_ID)).thenReturn(team);
String acceptInvitationEndpoint = "https://synapse.org/#acceptInvitationEndpoint:";
String notificationUnsubscribeEndpoint = "https://synapse.org/#notificationUnsubscribeEndpoint:";
MessageToUserAndBody result = membershipInvitationManagerImpl.createInvitationMessageToUser(mis,
acceptInvitationEndpoint, notificationUnsubscribeEndpoint);
assertEquals("You Have Been Invited to Join a Team", result.getMetadata().getSubject());
assertEquals(Collections.singleton(MEMBER_PRINCIPAL_ID), result.getMetadata().getRecipients());
assertEquals(notificationUnsubscribeEndpoint, result.getMetadata().getNotificationUnsubscribeEndpoint());
assertTrue(result.getBody().contains(acceptInvitationEndpoint));
}
@Test
public void testSendInvitationToEmail() throws Exception {
Team team = new Team();
String teamName = "Test team";
team.setName(teamName);
team.setId(TEAM_ID);
when(mockTeamDAO.get(TEAM_ID)).thenReturn(team);
MembershipInvitation mis = createMembershipInvtnSubmissionToEmail(MIS_ID);
String acceptInvitationEndpoint = "https://synapse.org/#acceptInvitationEndpoint:";
membershipInvitationManagerImpl.sendInvitationToEmail(mis, acceptInvitationEndpoint);
ArgumentCaptor<SendRawEmailRequest> argument = ArgumentCaptor.forClass(SendRawEmailRequest.class);
Mockito.verify(mockSynapseEmailService).sendRawEmail(argument.capture());
SendRawEmailRequest emailRequest = argument.getValue();
assertEquals(Collections.singletonList(INVITEE_EMAIL), emailRequest.getDestinations());
MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()),
new ByteArrayInputStream(emailRequest.getRawMessage().getData().array()));
String body = (String) ((MimeMultipart) mimeMessage.getContent()).getBodyPart(0).getContent();
assertNotNull(mimeMessage.getSubject());
assertTrue(body.contains(mis.getTeamId()));
assertTrue(body.contains(teamName));
assertTrue(body.contains(mis.getMessage()));
assertTrue(body.contains(acceptInvitationEndpoint));
}
@Test(expected = IllegalArgumentException.class)
public void testGetOpenInvitationCountForUserWithNullPrincipalId() {
membershipInvitationManagerImpl.getOpenInvitationCountForUser(null);
}
@Test
public void testGetOpenInvitationCountForUser() {
Long count = 7L;
when(mockMembershipInvitationDAO.getOpenByUserCount(anyLong(), anyLong())).thenReturn(count);
Count result = membershipInvitationManagerImpl.getOpenInvitationCountForUser(MEMBER_PRINCIPAL_ID);
assertNotNull(result);
assertEquals(count, result.getCount());
}
@Test
public void testVerifyInvitee() {
// Setup
MembershipInvitation mis = createMembershipInvtnSubmissionToEmail(MIS_ID);
when(mockMembershipInvitationDAO.get(MIS_ID)).thenReturn(mis);
Long userId = Long.parseLong(MEMBER_PRINCIPAL_ID);
// Mock listPrincipalAliases to return one alias with the invitee email
PrincipalAliasDAO mockPrincipalAliasDAO = Mockito.mock(PrincipalAliasDAO.class);
ReflectionTestUtils.setField(membershipInvitationManagerImpl, "principalAliasDAO", mockPrincipalAliasDAO);
when(mockPrincipalAliasDAO.aliasIsBoundToPrincipal(INVITEE_EMAIL, MEMBER_PRINCIPAL_ID)).thenReturn(true);
// Test getInviteeVerificationSignedToken by inspecting the token it returns
InviteeVerificationSignedToken token = membershipInvitationManagerImpl.getInviteeVerificationSignedToken(userId,
MIS_ID);
assertNotNull(token);
assertEquals(MEMBER_PRINCIPAL_ID, token.getInviteeId());
assertEquals(MIS_ID, token.getMembershipInvitationId());
tokenGenerator.validateToken(token);
// Test failure cases
// Failure 1 - mis is expired
Date expiresOn = mis.getExpiresOn();
mis.setExpiresOn(new Date(new Date().getTime() - 999999L));
boolean caughtException = false;
try {
membershipInvitationManagerImpl.getInviteeVerificationSignedToken(userId, MIS_ID);
} catch (IllegalArgumentException e) {
caughtException = true;
}
assertTrue(caughtException);
// Restore expiresOn
mis.setExpiresOn(expiresOn);
// Failure 2 - inviteeId is set
mis.setInviteeId("not-null");
caughtException = false;
try {
membershipInvitationManagerImpl.getInviteeVerificationSignedToken(userId, MIS_ID);
} catch (IllegalArgumentException e) {
caughtException = true;
}
assertTrue(caughtException);
mis.setInviteeId(null);
// Failure 3 - invitee email is not associated with user
when(mockPrincipalAliasDAO.aliasIsBoundToPrincipal(INVITEE_EMAIL, MEMBER_PRINCIPAL_ID)).thenReturn(false);
caughtException = false;
try {
membershipInvitationManagerImpl.getInviteeVerificationSignedToken(userId, MIS_ID);
} catch (UnauthorizedException e) {
caughtException = true;
}
assertTrue(caughtException);
}
@Test
public void testUpdateId() {
// Setup
Long userId = Long.parseLong(MEMBER_PRINCIPAL_ID);
MembershipInvitation mis = createMembershipInvtnSubmissionToEmail(MIS_ID);
InviteeVerificationSignedToken token = new InviteeVerificationSignedToken();
token.setMembershipInvitationId(MIS_ID);
token.setExpiresOn(mis.getExpiresOn());
// Mock happy case behavior
when(mockAuthorizationManager.canAccessMembershipInvitation(userId, token, ACCESS_TYPE.UPDATE))
.thenReturn(AuthorizationManagerUtil.AUTHORIZED);
when(mockMembershipInvitationDAO.getWithUpdateLock(MIS_ID)).thenReturn(mis);
// Happy case should succeed
membershipInvitationManagerImpl.updateInviteeId(userId, MIS_ID, token);
Mockito.verify(mockMembershipInvitationDAO).updateInviteeId(MIS_ID, userId);
// URI id and signed token id should match
boolean caughtException = false;
try {
membershipInvitationManagerImpl.updateInviteeId(userId, "incorrectId", token);
} catch (IllegalArgumentException e) {
caughtException = true;
}
assertTrue(caughtException);
// Token with null expiresOn should fail
token.setExpiresOn(null);
caughtException = false;
try {
membershipInvitationManagerImpl.updateInviteeId(userId, MIS_ID, token);
} catch (IllegalArgumentException e) {
caughtException = true;
}
assertTrue(caughtException);
// Restore valid expiration date
token.setExpiresOn(mis.getExpiresOn());
// Expired token should fail
token.setExpiresOn(new Date(new Date().getTime() - TWENTY_FOUR_HOURS_IN_MS));
caughtException = false;
try {
membershipInvitationManagerImpl.updateInviteeId(userId, MIS_ID, token);
} catch (IllegalArgumentException e) {
caughtException = true;
}
assertTrue(caughtException);
// Restore valid expiration date
token.setExpiresOn(mis.getExpiresOn());
// Mock the authorization manager so that it denies access
when(mockAuthorizationManager.canAccessMembershipInvitation(userId, token, ACCESS_TYPE.UPDATE))
.thenReturn(AuthorizationManagerUtil.ACCESS_DENIED);
// Updating the inviteeId should throw an UnauthorizedException
caughtException = false;
try {
membershipInvitationManagerImpl.updateInviteeId(userId, MIS_ID, token);
} catch (UnauthorizedException e) {
caughtException = true;
}
assertTrue(caughtException);
// Restore the authorization manager to allow access again
when(mockAuthorizationManager.canAccessMembershipInvitation(userId, token, ACCESS_TYPE.UPDATE))
.thenReturn(AuthorizationManagerUtil.AUTHORIZED);
// Set the existing invitation's inviteeId
mis.setInviteeId(userId.toString());
// Updating the inviteeId should throw an UnauthorizedException
caughtException = false;
try {
membershipInvitationManagerImpl.updateInviteeId(userId, MIS_ID, token);
} catch (IllegalArgumentException e) {
caughtException = true;
}
assertTrue(caughtException);
}
}
| fix MembershipInvitationManagerImplTest
| services/repository-managers/src/test/java/org/sagebionetworks/repo/manager/team/MembershipInvitationManagerImplTest.java | fix MembershipInvitationManagerImplTest | <ide><path>ervices/repository-managers/src/test/java/org/sagebionetworks/repo/manager/team/MembershipInvitationManagerImplTest.java
<ide> package org.sagebionetworks.repo.manager.team;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertFalse;
<ide> import static org.junit.Assert.assertNotNull;
<ide> import static org.junit.Assert.assertTrue;
<ide> import static org.junit.Assert.fail;
<ide> new ByteArrayInputStream(emailRequest.getRawMessage().getData().array()));
<ide> String body = (String) ((MimeMultipart) mimeMessage.getContent()).getBodyPart(0).getContent();
<ide> assertNotNull(mimeMessage.getSubject());
<del> assertTrue(body.contains(mis.getTeamId()));
<add> assertFalse(body.contains(mis.getTeamId())); //PLFM-5369: Users kept clicking the team page instead of joining the team via invitation link.
<ide> assertTrue(body.contains(teamName));
<ide> assertTrue(body.contains(mis.getMessage()));
<ide> assertTrue(body.contains(acceptInvitationEndpoint)); |
|
Java | apache-2.0 | 31897342017bb84a98c82b534737a91384ceedeb | 0 | nasa/MCT-Plugins | /*******************************************************************************
* Mission Control Technologies, Copyright (c) 2009-2012, United States Government
* as represented by the Administrator of the National Aeronautics and Space
* Administration. All rights reserved.
*
* The MCT platform 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.
*
* MCT includes source code licensed under additional open source licenses. See
* the MCT Open Source Licenses file included with this distribution or the About
* MCT Licenses dialog available at runtime from the MCT Help menu for additional
* information.
*******************************************************************************/
package gov.nasa.arc.mct.scenario.view;
import gov.nasa.arc.mct.components.AbstractComponent;
import gov.nasa.arc.mct.gui.View;
import gov.nasa.arc.mct.scenario.component.CostFunctionCapability;
import gov.nasa.arc.mct.scenario.component.TimelineComponent;
import gov.nasa.arc.mct.services.component.ViewInfo;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class ScenarioView extends AbstractTimelineView {
private static final long serialVersionUID = 4734756748449290286L;
private static final int BORDER_SIZE = 12;
private static final int BORDER_GAP = 6;
private static final Color TIMELINE_BACKGROUND = new Color(240, 244, 248);
public ScenarioView(AbstractComponent ac, ViewInfo vi) {
super(ac, vi);
setOpaque(false);
JPanel upperPanel = new JPanel();
upperPanel.setLayout(new BoxLayout(upperPanel, BoxLayout.Y_AXIS));
upperPanel.setOpaque(false);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(upperPanel, BorderLayout.NORTH);
getContentPane().setBackground(Color.WHITE);
//getContentPane().setOpaque(false);
//TODO: Use clone strategy, set work unit delegate for kids
for (AbstractComponent child : ac.getComponents()) {
if (child instanceof TimelineComponent) {
upperPanel.add(createTimeline((TimelineComponent) child));
}
}
List<CostFunctionCapability> costs = ac.getCapabilities(CostFunctionCapability.class);
if (costs != null && !costs.isEmpty()) {
upperPanel.add(new CollapsibleContainer(GraphView.VIEW_INFO.createView(getManifestedComponent())));
}
}
private Component createTimeline(TimelineComponent component) {
View view = TimelineView.VIEW_INFO.createView(component);
View label = LabelView.VIEW_INFO.createView(component);
JComponent container = new CollapsibleContainer(view, label);
container.setOpaque(true);
container.setBackground(TIMELINE_BACKGROUND);
container.setBorder(new Border() {
@Override
public void paintBorder(Component c, Graphics g, int x, int y,
int width, int height) {
g.setColor(getContentPane().getBackground());
g.fillRect(x, y , width, BORDER_SIZE + BORDER_GAP/2);
g.fillRect(x, y+height-BORDER_SIZE - BORDER_GAP/2, width, BORDER_SIZE + BORDER_GAP/2);
if (g instanceof Graphics2D) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
g.setColor(c.getBackground());
g.fillRoundRect(x, y + BORDER_GAP/2, width-1, BORDER_SIZE*2, BORDER_SIZE*2, BORDER_SIZE*2);
g.fillRoundRect(x, y+height-BORDER_SIZE*2-BORDER_GAP/2, width-1, BORDER_SIZE*2, BORDER_SIZE*2, BORDER_SIZE*2);
}
@Override
public Insets getBorderInsets(Component c) {
return new Insets(BORDER_SIZE + BORDER_GAP/2, 0, BORDER_SIZE + BORDER_GAP/2, 0);
}
@Override
public boolean isBorderOpaque() {
return true;
}
});
return container;
}
}
| scenario/src/main/java/gov/nasa/arc/mct/scenario/view/ScenarioView.java | /*******************************************************************************
* Mission Control Technologies, Copyright (c) 2009-2012, United States Government
* as represented by the Administrator of the National Aeronautics and Space
* Administration. All rights reserved.
*
* The MCT platform 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.
*
* MCT includes source code licensed under additional open source licenses. See
* the MCT Open Source Licenses file included with this distribution or the About
* MCT Licenses dialog available at runtime from the MCT Help menu for additional
* information.
*******************************************************************************/
package gov.nasa.arc.mct.scenario.view;
import gov.nasa.arc.mct.components.AbstractComponent;
import gov.nasa.arc.mct.gui.View;
import gov.nasa.arc.mct.scenario.component.CostFunctionCapability;
import gov.nasa.arc.mct.scenario.component.TimelineComponent;
import gov.nasa.arc.mct.services.component.ViewInfo;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JPanel;
public class ScenarioView extends AbstractTimelineView {
private static final long serialVersionUID = 4734756748449290286L;
public ScenarioView(AbstractComponent ac, ViewInfo vi) {
super(ac, vi);
setOpaque(false);
JPanel upperPanel = new JPanel();
upperPanel.setLayout(new BoxLayout(upperPanel, BoxLayout.Y_AXIS));
upperPanel.setOpaque(false);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(upperPanel, BorderLayout.NORTH);
getContentPane().setBackground(Color.WHITE);
//getContentPane().setOpaque(false);
//TODO: Use clone strategy, set work unit delegate for kids
for (AbstractComponent child : ac.getComponents()) {
if (child instanceof TimelineComponent) {
upperPanel.add(createTimeline((TimelineComponent) child));
}
}
List<CostFunctionCapability> costs = ac.getCapabilities(CostFunctionCapability.class);
if (costs != null && !costs.isEmpty()) {
upperPanel.add(new CollapsibleContainer(GraphView.VIEW_INFO.createView(getManifestedComponent())));
}
}
private Component createTimeline(TimelineComponent component) {
View view = TimelineView.VIEW_INFO.createView(component);
View label = LabelView.VIEW_INFO.createView(component);
JComponent container = new CollapsibleContainer(view, label);
container.setOpaque(true);
container.setBackground(Color.LIGHT_GRAY);
return container;
}
}
| [Scenario] Add borders to Timelines in Scenario view
| scenario/src/main/java/gov/nasa/arc/mct/scenario/view/ScenarioView.java | [Scenario] Add borders to Timelines in Scenario view | <ide><path>cenario/src/main/java/gov/nasa/arc/mct/scenario/view/ScenarioView.java
<ide> import java.awt.BorderLayout;
<ide> import java.awt.Color;
<ide> import java.awt.Component;
<add>import java.awt.Graphics;
<add>import java.awt.Graphics2D;
<add>import java.awt.Insets;
<add>import java.awt.RenderingHints;
<ide> import java.util.List;
<ide>
<ide> import javax.swing.BoxLayout;
<ide> import javax.swing.JComponent;
<ide> import javax.swing.JPanel;
<add>import javax.swing.border.Border;
<ide>
<ide> public class ScenarioView extends AbstractTimelineView {
<ide> private static final long serialVersionUID = 4734756748449290286L;
<ide>
<add> private static final int BORDER_SIZE = 12;
<add> private static final int BORDER_GAP = 6;
<add> private static final Color TIMELINE_BACKGROUND = new Color(240, 244, 248);
<add>
<ide> public ScenarioView(AbstractComponent ac, ViewInfo vi) {
<ide> super(ac, vi);
<ide>
<ide> JComponent container = new CollapsibleContainer(view, label);
<ide>
<ide> container.setOpaque(true);
<del> container.setBackground(Color.LIGHT_GRAY);
<add> container.setBackground(TIMELINE_BACKGROUND);
<add> container.setBorder(new Border() {
<add>
<add> @Override
<add> public void paintBorder(Component c, Graphics g, int x, int y,
<add> int width, int height) {
<add> g.setColor(getContentPane().getBackground());
<add> g.fillRect(x, y , width, BORDER_SIZE + BORDER_GAP/2);
<add> g.fillRect(x, y+height-BORDER_SIZE - BORDER_GAP/2, width, BORDER_SIZE + BORDER_GAP/2);
<add>
<add> if (g instanceof Graphics2D) {
<add> Graphics2D g2d = (Graphics2D) g;
<add> g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
<add> }
<add>
<add> g.setColor(c.getBackground());
<add> g.fillRoundRect(x, y + BORDER_GAP/2, width-1, BORDER_SIZE*2, BORDER_SIZE*2, BORDER_SIZE*2);
<add> g.fillRoundRect(x, y+height-BORDER_SIZE*2-BORDER_GAP/2, width-1, BORDER_SIZE*2, BORDER_SIZE*2, BORDER_SIZE*2);
<add> }
<add>
<add> @Override
<add> public Insets getBorderInsets(Component c) {
<add> return new Insets(BORDER_SIZE + BORDER_GAP/2, 0, BORDER_SIZE + BORDER_GAP/2, 0);
<add> }
<add>
<add> @Override
<add> public boolean isBorderOpaque() {
<add> return true;
<add> }
<add>
<add> });
<ide>
<ide> return container;
<ide> } |
|
Java | bsd-3-clause | 479ef7b452a594e9423902a00cc5b4c56130e968 | 0 | muloem/xins,muloem/xins,muloem/xins | /*
* $Id$
*
* Copyright 2003-2005 Wanadoo Nederland B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.tests.common.collections;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import org.apache.log4j.PropertyConfigurator;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.xins.common.collections.IncorrectSecretKeyException;
import org.xins.common.collections.ProtectedList;
/**
* Tests for class <code>ProtectedList</code>.
*
* @version $Revision$ $Date$
* @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>)
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*/
public class ProtectedListTests extends TestCase {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* The secret key for the test protected list.
*/
private final static Object SECRET_KEY = new Object();
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
/**
* Returns a test suite with all test cases defined by this class.
*
* @return
* the test suite, never <code>null</code>.
*/
public static Test suite() {
return new TestSuite(ProtectedListTests.class);
}
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>ProtectedList</code> test suite with
* the specified name. The name will be passed to the superconstructor.
*
* @param name
* the name for this test suite.
*/
public ProtectedListTests(String name) {
super(name);
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
Properties settings = new Properties();
settings.setProperty("log4j.rootLogger", "DEBUG, console");
settings.setProperty("log4j.appender.console", "org.apache.log4j.ConsoleAppender");
settings.setProperty("log4j.appender.console.layout", "org.apache.log4j.PatternLayout");
settings.setProperty("log4j.appender.console.layout.ConversionPattern", "%d %t %-5p [%c] %m%n");
settings.setProperty("log4j.logger.httpclient.wire", "WARN");
settings.setProperty("log4j.logger.org.apache.commons.httpclient", "WARN");
PropertyConfigurator.configure(settings);
}
public void testProtectedList() {
// Construct a ProtectedList with null as secret key (should fail)
try {
new ProtectedList(null);
fail("Expected IllegalArgumentException.");
} catch (IllegalArgumentException exception) {
// as expected
}
try {
new ProtectedList(null, 15);
fail("Expected IllegalArgumentException.");
} catch (IllegalArgumentException exception) {
// as expected
}
try {
new ProtectedList(null, new ArrayList());
fail("Expected IllegalArgumentException.");
} catch (IllegalArgumentException exception) {
// as expected
}
// Construct a ProtectedList with the secret key
ProtectedList list = new ProtectedList(SECRET_KEY);
assertEquals(0, list.size());
// Try unsupported standard add-operation
try {
list.add("hello1");
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException exception) {
// as expected
}
// Add using secret key should succeed
list.add(SECRET_KEY, "hello2");
assertEquals(1, list.size());
assertEquals("hello2", list.get(0));
assertEquals(0, list.indexOf("hello2"));
assertEquals(0, list.lastIndexOf("hello2"));
assertTrue(list.contains("hello2"));
// Add using incorrect secret key should fail
try {
list.add(null, "hello3");
fail("Expected IncorrectSecretKeyException.");
} catch (IncorrectSecretKeyException exception) {
// as expected
}
try {
list.add(new Object(), "hello3");
fail("Expected IncorrectSecretKeyException.");
} catch (IncorrectSecretKeyException exception) {
// as expected
}
assertEquals(1, list.size());
assertEquals("hello2", list.get(0));
assertEquals(0, list.indexOf("hello2"));
assertEquals(0, list.lastIndexOf("hello2"));
assertTrue(list.contains("hello2"));
assertFalse(list.contains("hello3"));
// Try removing with incorrect secret key
try {
list.remove(null, -1);
fail("Expected IncorrectSecretKeyException.");
} catch (IncorrectSecretKeyException exception) {
// as expected
}
try {
list.remove(new Object(), -1);
fail("Expected IncorrectSecretKeyException.");
} catch (IncorrectSecretKeyException exception) {
// as expected
}
// Try removing with correct secret key, but invalid index
try {
list.remove(SECRET_KEY, -1);
fail("Expected IndexOutOfBoundsException.");
} catch (IndexOutOfBoundsException exception) {
// as expected
}
try {
list.remove(SECRET_KEY, 1);
fail("Expected IndexOutOfBoundsException.");
} catch (IndexOutOfBoundsException exception) {
// as expected
}
assertEquals(1, list.size());
assertEquals("hello2", list.get(0));
assertEquals(0, list.indexOf("hello2"));
assertEquals(0, list.lastIndexOf("hello2"));
assertTrue(list.contains("hello2"));
assertFalse(list.contains("hello3"));
// Really remove
list.remove(SECRET_KEY, 0);
assertEquals(0, list.size());
assertEquals(-1, list.indexOf("hello2"));
assertEquals(-1, list.lastIndexOf("hello2"));
assertFalse(list.contains("hello2"));
assertFalse(list.contains("hello3"));
}
}
| src/tests/org/xins/tests/common/collections/ProtectedListTests.java | /*
* $Id$
*
* Copyright 2003-2005 Wanadoo Nederland B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.tests.common.collections;
import java.lang.Exception;
import java.util.Iterator;
import java.util.Properties;
import org.apache.log4j.PropertyConfigurator;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.xins.common.collections.ProtectedList;
/**
* Tests for class <code>ProtectedList</code>.
*
* @version $Revision$ $Date$
* @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>)
*/
public class ProtectedListTests extends TestCase {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* The secret key for the test protected list.
*/
private final static Object KEY = new Object();
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
/**
* Returns a test suite with all test cases defined by this class.
*
* @return
* the test suite, never <code>null</code>.
*/
public static Test suite() {
return new TestSuite(ProtectedListTests.class);
}
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>ProtectedList</code> test suite with
* the specified name. The name will be passed to the superconstructor.
*
* @param name
* the name for this test suite.
*/
public ProtectedListTests(String name) {
super(name);
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/*
* @see TestCase#setUp()
*/
protected void setUp()
throws Exception {
super.setUp();
Properties settings = new Properties();
settings.setProperty("log4j.rootLogger", "DEBUG, console");
settings.setProperty("log4j.appender.console", "org.apache.log4j.ConsoleAppender");
settings.setProperty("log4j.appender.console.layout", "org.apache.log4j.PatternLayout");
settings.setProperty("log4j.appender.console.layout.ConversionPattern", "%d %t %-5p [%c] %m%n");
settings.setProperty("log4j.logger.httpclient.wire", "WARN");
settings.setProperty("log4j.logger.org.apache.commons.httpclient", "WARN");
PropertyConfigurator.configure(settings);
}
public void testList() {
ProtectedList list = new ProtectedList(KEY);
assertEquals("The size of the list is incorrect.", 0, list.size());
try {
list.add("hello1");
fail("BasicPropertyReader.set(null, null) should throw an IllegalArgumentException.");
} catch (Exception exception) {
// as expected
}
try {
list.add(KEY, "hello2");
} catch (Exception exception) {
fail("BasicPropertyReader.set(null, null) should throw an IllegalArgumentException.");
}
try {
list.add(new Object(), "hello3");
fail("BasicPropertyReader.set(null, null) should throw an IllegalArgumentException.");
} catch (Exception exception) {
// as expected
}
assertEquals("The size of the list is incorrect.", 1, list.size());
assertEquals("The value of the element in the list is incorrect.", "hello2", list.get(0));
}
}
| Improved a great deal.
| src/tests/org/xins/tests/common/collections/ProtectedListTests.java | Improved a great deal. | <ide><path>rc/tests/org/xins/tests/common/collections/ProtectedListTests.java
<ide> */
<ide> package org.xins.tests.common.collections;
<ide>
<del>import java.lang.Exception;
<add>import java.util.ArrayList;
<ide> import java.util.Iterator;
<ide> import java.util.Properties;
<ide>
<ide> import junit.framework.TestCase;
<ide> import junit.framework.TestSuite;
<ide>
<add>import org.xins.common.collections.IncorrectSecretKeyException;
<ide> import org.xins.common.collections.ProtectedList;
<ide>
<ide> /**
<ide> *
<ide> * @version $Revision$ $Date$
<ide> * @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>)
<add> * @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
<ide> */
<ide> public class ProtectedListTests extends TestCase {
<ide>
<ide> /**
<ide> * The secret key for the test protected list.
<ide> */
<del> private final static Object KEY = new Object();
<add> private final static Object SECRET_KEY = new Object();
<add>
<ide>
<ide> //-------------------------------------------------------------------------
<ide> // Class functions
<ide> super(name);
<ide> }
<ide>
<add>
<ide> //-------------------------------------------------------------------------
<ide> // Fields
<ide> //-------------------------------------------------------------------------
<ide> /*
<ide> * @see TestCase#setUp()
<ide> */
<del> protected void setUp()
<del> throws Exception {
<add> protected void setUp() throws Exception {
<ide> super.setUp();
<ide> Properties settings = new Properties();
<ide> settings.setProperty("log4j.rootLogger", "DEBUG, console");
<ide> PropertyConfigurator.configure(settings);
<ide> }
<ide>
<del> public void testList() {
<del> ProtectedList list = new ProtectedList(KEY);
<add> public void testProtectedList() {
<ide>
<del> assertEquals("The size of the list is incorrect.", 0, list.size());
<del>
<add> // Construct a ProtectedList with null as secret key (should fail)
<ide> try {
<del> list.add("hello1");
<del> fail("BasicPropertyReader.set(null, null) should throw an IllegalArgumentException.");
<del> } catch (Exception exception) {
<add> new ProtectedList(null);
<add> fail("Expected IllegalArgumentException.");
<add> } catch (IllegalArgumentException exception) {
<add> // as expected
<add> }
<add> try {
<add> new ProtectedList(null, 15);
<add> fail("Expected IllegalArgumentException.");
<add> } catch (IllegalArgumentException exception) {
<add> // as expected
<add> }
<add> try {
<add> new ProtectedList(null, new ArrayList());
<add> fail("Expected IllegalArgumentException.");
<add> } catch (IllegalArgumentException exception) {
<ide> // as expected
<ide> }
<ide>
<add> // Construct a ProtectedList with the secret key
<add> ProtectedList list = new ProtectedList(SECRET_KEY);
<add> assertEquals(0, list.size());
<add>
<add> // Try unsupported standard add-operation
<ide> try {
<del> list.add(KEY, "hello2");
<del> } catch (Exception exception) {
<del> fail("BasicPropertyReader.set(null, null) should throw an IllegalArgumentException.");
<del> }
<del>
<del> try {
<del> list.add(new Object(), "hello3");
<del> fail("BasicPropertyReader.set(null, null) should throw an IllegalArgumentException.");
<del> } catch (Exception exception) {
<add> list.add("hello1");
<add> fail("Expected UnsupportedOperationException.");
<add> } catch (UnsupportedOperationException exception) {
<ide> // as expected
<ide> }
<ide>
<del> assertEquals("The size of the list is incorrect.", 1, list.size());
<del> assertEquals("The value of the element in the list is incorrect.", "hello2", list.get(0));
<add> // Add using secret key should succeed
<add> list.add(SECRET_KEY, "hello2");
<add> assertEquals(1, list.size());
<add> assertEquals("hello2", list.get(0));
<add> assertEquals(0, list.indexOf("hello2"));
<add> assertEquals(0, list.lastIndexOf("hello2"));
<add> assertTrue(list.contains("hello2"));
<add>
<add> // Add using incorrect secret key should fail
<add> try {
<add> list.add(null, "hello3");
<add> fail("Expected IncorrectSecretKeyException.");
<add> } catch (IncorrectSecretKeyException exception) {
<add> // as expected
<add> }
<add> try {
<add> list.add(new Object(), "hello3");
<add> fail("Expected IncorrectSecretKeyException.");
<add> } catch (IncorrectSecretKeyException exception) {
<add> // as expected
<add> }
<add> assertEquals(1, list.size());
<add> assertEquals("hello2", list.get(0));
<add> assertEquals(0, list.indexOf("hello2"));
<add> assertEquals(0, list.lastIndexOf("hello2"));
<add> assertTrue(list.contains("hello2"));
<add> assertFalse(list.contains("hello3"));
<add>
<add> // Try removing with incorrect secret key
<add> try {
<add> list.remove(null, -1);
<add> fail("Expected IncorrectSecretKeyException.");
<add> } catch (IncorrectSecretKeyException exception) {
<add> // as expected
<add> }
<add> try {
<add> list.remove(new Object(), -1);
<add> fail("Expected IncorrectSecretKeyException.");
<add> } catch (IncorrectSecretKeyException exception) {
<add> // as expected
<add> }
<add>
<add> // Try removing with correct secret key, but invalid index
<add> try {
<add> list.remove(SECRET_KEY, -1);
<add> fail("Expected IndexOutOfBoundsException.");
<add> } catch (IndexOutOfBoundsException exception) {
<add> // as expected
<add> }
<add> try {
<add> list.remove(SECRET_KEY, 1);
<add> fail("Expected IndexOutOfBoundsException.");
<add> } catch (IndexOutOfBoundsException exception) {
<add> // as expected
<add> }
<add> assertEquals(1, list.size());
<add> assertEquals("hello2", list.get(0));
<add> assertEquals(0, list.indexOf("hello2"));
<add> assertEquals(0, list.lastIndexOf("hello2"));
<add> assertTrue(list.contains("hello2"));
<add> assertFalse(list.contains("hello3"));
<add>
<add> // Really remove
<add> list.remove(SECRET_KEY, 0);
<add> assertEquals(0, list.size());
<add> assertEquals(-1, list.indexOf("hello2"));
<add> assertEquals(-1, list.lastIndexOf("hello2"));
<add> assertFalse(list.contains("hello2"));
<add> assertFalse(list.contains("hello3"));
<ide> }
<del>
<ide> } |
|
Java | apache-2.0 | e82f97e727b3661a2a3c064473d8c5a947146106 | 0 | DevStreet/FinanceAnalytics,DevStreet/FinanceAnalytics,McLeodMoores/starling,McLeodMoores/starling,DevStreet/FinanceAnalytics,jeorme/OG-Platform,nssales/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,ChinaQuants/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,jeorme/OG-Platform,ChinaQuants/OG-Platform,nssales/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform | /**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.web.analytics;
import static org.testng.AssertJUnit.assertTrue;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.annotations.Test;
import org.threeten.bp.Duration;
import com.google.common.collect.ImmutableList;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.cache.NotCalculatedSentinel;
import com.opengamma.engine.target.ComputationTargetType;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.id.UniqueId;
import com.opengamma.util.test.TestGroup;
import com.opengamma.web.analytics.formatting.ResultsFormatter;
import com.opengamma.web.analytics.formatting.TypeFormatter;
/**
* Test.
*/
@Test(groups = TestGroup.UNIT)
public class ViewportResultsJsonWriterTest {
private static final Duration DURATION = Duration.ofMillis(1234);
private final ViewportDefinition _viewportDefinition = ViewportDefinition.create(0,
ImmutableList.of(0),
ImmutableList.of(0),
ImmutableList.<GridCell>of(),
TypeFormatter.Format.CELL,
false);
private final ValueRequirement _valueReq =
new ValueRequirement("valueName", ComputationTargetType.POSITION, UniqueId.of("foo", "bar"));
private final ComputationTargetSpecification _target =
new ComputationTargetSpecification(ComputationTargetType.POSITION, UniqueId.of("foo", "bar"));
private final ValueSpecification _valueSpec =
new ValueSpecification(_valueReq.getValueName(), _target,
ValueProperties.builder().with(ValuePropertyNames.FUNCTION, "fnName").get());
private final ViewportResultsJsonWriter _writer = new ViewportResultsJsonWriter(new ResultsFormatter());
private static GridColumnGroups createColumns(Class<?> type) {
GridColumn.CellRenderer renderer = new TestCellRenderer();
GridColumn column = new GridColumn("header", "desc", type, renderer);
return new GridColumnGroups(new GridColumnGroup("grp", ImmutableList.of(column), false));
}
private List<ResultsCell> createResults(Object value, List<Object> history, Class<?> columnType) {
return ImmutableList.of(ResultsCell.forCalculatedValue(value, _valueSpec, history, null, false, columnType));
}
@Test
public void valueWithNoHistory() throws JSONException {
List<ResultsCell> results = createResults("val", null, String.class);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(String.class), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"val\"}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
@Test
public void valueWithHistory() throws JSONException {
List<ResultsCell> results = createResults(3d, ImmutableList.<Object>of(1d, 2d, 3d), Double.class);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(Double.class), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"3.0\",\"h\":[1,2,3]}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
@Test
public void valueWithUnknownType() throws JSONException {
List<ResultsCell> results = createResults(3d, null, null);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(null), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"3.0\",\"t\":\"DOUBLE\"}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
@Test
public void nullValueWithUnknownType() throws JSONException {
List<ResultsCell> results = createResults(null, null, null);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(null), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"\",\"t\":\"STRING\"}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
@Test
public void valueWithUnknownTypeAndHistory() throws JSONException {
List<ResultsCell> results = createResults(3d, ImmutableList.<Object>of(1d, 2d, 3d), null);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(null), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"3.0\",\"t\":\"DOUBLE\",\"h\":[1,2,3]}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
@Test
public void errorValueNoHistory() throws JSONException {
List<ResultsCell> results = createResults(NotCalculatedSentinel.EVALUATION_ERROR, null, String.class);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(String.class), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"Evaluation error\", \"error\":true}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
@Test
public void errorValueWithHistory() throws JSONException {
ImmutableList<Object> history = ImmutableList.<Object>of(1d, 2d, NotCalculatedSentinel.EVALUATION_ERROR);
List<ResultsCell> results = createResults(NotCalculatedSentinel.EVALUATION_ERROR, history, Double.class);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(Double.class), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"Evaluation error\", \"h\":[1,2], \"error\":true}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
//assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
@Test
public void errorValueInHistory() throws JSONException {
ImmutableList<Object> history = ImmutableList.<Object>of(1d, NotCalculatedSentinel.EVALUATION_ERROR, 3d);
List<ResultsCell> results = createResults(3d, history, Double.class);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(Double.class), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"3.0\",\"h\":[1,3]}]}";
//String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"3.0\",\"h\":[1,null,3]}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
private static class TestCellRenderer implements GridColumn.CellRenderer {
@Override
public ResultsCell getResults(int rowIndex, ResultsCache cache, Class<?> columnType, Object inlineKey) {
return null;
}
}
// TODO tests for log output
}
| projects/OG-Web/src/test/java/com/opengamma/web/analytics/ViewportResultsJsonWriterTest.java | /**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.web.analytics;
import static org.testng.AssertJUnit.assertTrue;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.annotations.Test;
import org.threeten.bp.Duration;
import com.google.common.collect.ImmutableList;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.cache.NotCalculatedSentinel;
import com.opengamma.engine.target.ComputationTargetType;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.id.UniqueId;
import com.opengamma.util.test.TestGroup;
import com.opengamma.web.analytics.formatting.ResultsFormatter;
import com.opengamma.web.analytics.formatting.TypeFormatter;
/**
* Test.
*/
@Test(groups = TestGroup.UNIT)
public class ViewportResultsJsonWriterTest {
private static final Duration DURATION = Duration.ofMillis(1234);
private final ViewportDefinition _viewportDefinition = ViewportDefinition.create(0,
ImmutableList.of(0),
ImmutableList.of(0),
ImmutableList.<GridCell>of(),
TypeFormatter.Format.CELL,
false);
private final ValueRequirement _valueReq =
new ValueRequirement("valueName", ComputationTargetType.POSITION, UniqueId.of("foo", "bar"));
private final ComputationTargetSpecification _target =
new ComputationTargetSpecification(ComputationTargetType.POSITION, UniqueId.of("foo", "bar"));
private final ValueSpecification _valueSpec =
new ValueSpecification(_valueReq.getValueName(), _target,
ValueProperties.builder().with(ValuePropertyNames.FUNCTION, "fnName").get());
private final ViewportResultsJsonWriter _writer = new ViewportResultsJsonWriter(new ResultsFormatter());
private static GridColumnGroups createColumns(Class<?> type) {
GridColumn.CellRenderer renderer = new TestCellRenderer();
GridColumn column = new GridColumn("header", "desc", type, renderer);
return new GridColumnGroups(new GridColumnGroup("grp", ImmutableList.of(column), false));
}
private List<ResultsCell> createResults(Object value, List<Object> history, Class<?> columnType) {
return ImmutableList.of(ResultsCell.forCalculatedValue(value, _valueSpec, history, null, false, columnType));
}
@Test
public void valueWithNoHistory() throws JSONException {
List<ResultsCell> results = createResults("val", null, String.class);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(String.class), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"val\"}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
@Test
public void valueWithHistory() throws JSONException {
List<ResultsCell> results = createResults(3d, ImmutableList.<Object>of(1d, 2d, 3d), Double.class);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(Double.class), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"3.0\",\"h\":[1,2,3]}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
@Test
public void valueWithUnknownType() throws JSONException {
List<ResultsCell> results = createResults(3d, null, null);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(null), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"3.0\",\"t\":\"DOUBLE\"}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
@Test
public void nullValueWithUnknownType() throws JSONException {
List<ResultsCell> results = createResults(null, null, null);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(null), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"\",\"t\":\"STRING\"}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
@Test
public void valueWithUnknownTypeAndHistory() throws JSONException {
List<ResultsCell> results = createResults(3d, ImmutableList.<Object>of(1d, 2d, 3d), null);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(null), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"3.0\",\"t\":\"DOUBLE\",\"h\":[1,2,3]}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
@Test
public void errorValueNoHistory() throws JSONException {
List<ResultsCell> results = createResults(NotCalculatedSentinel.EVALUATION_ERROR, null, String.class);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(String.class), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"Evaluation error\", \"error\":true}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
@Test
public void errorValueWithHistory() throws JSONException {
ImmutableList<Object> history = ImmutableList.<Object>of(1d, 2d, NotCalculatedSentinel.EVALUATION_ERROR);
List<ResultsCell> results = createResults(NotCalculatedSentinel.EVALUATION_ERROR, history, Double.class);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(Double.class), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"Evaluation error\", \"h\":[1,2,null], \"error\":true}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
@Test
public void errorValueInHistory() throws JSONException {
ImmutableList<Object> history = ImmutableList.<Object>of(1d, NotCalculatedSentinel.EVALUATION_ERROR, 3d);
List<ResultsCell> results = createResults(3d, history, Double.class);
ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(Double.class), DURATION);
String json = _writer.getJson(viewportResults);
String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"3.0\",\"h\":[1,null,3]}]}";
assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
}
private static class TestCellRenderer implements GridColumn.CellRenderer {
@Override
public ResultsCell getResults(int rowIndex, ResultsCache cache, Class<?> columnType, Object inlineKey) {
return null;
}
}
// TODO tests for log output
}
| [GUI-227] Fix test
| projects/OG-Web/src/test/java/com/opengamma/web/analytics/ViewportResultsJsonWriterTest.java | [GUI-227] Fix test | <ide><path>rojects/OG-Web/src/test/java/com/opengamma/web/analytics/ViewportResultsJsonWriterTest.java
<ide> List<ResultsCell> results = createResults(NotCalculatedSentinel.EVALUATION_ERROR, history, Double.class);
<ide> ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(Double.class), DURATION);
<ide> String json = _writer.getJson(viewportResults);
<del> String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"Evaluation error\", \"h\":[1,2,null], \"error\":true}]}";
<add> String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"Evaluation error\", \"h\":[1,2], \"error\":true}]}";
<ide> assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
<add> //assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
<ide> }
<ide>
<ide> @Test
<ide> List<ResultsCell> results = createResults(3d, history, Double.class);
<ide> ViewportResults viewportResults = new ViewportResults(results, _viewportDefinition, createColumns(Double.class), DURATION);
<ide> String json = _writer.getJson(viewportResults);
<del> String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"3.0\",\"h\":[1,null,3]}]}";
<add> String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"3.0\",\"h\":[1,3]}]}";
<add> //String expectedJson = "{\"version\":0, \"calculationDuration\":\"1,234\", \"data\":[{\"v\":\"3.0\",\"h\":[1,null,3]}]}";
<ide> assertTrue(JsonTestUtils.equal(new JSONObject(expectedJson), new JSONObject(json)));
<ide> }
<ide> |
|
Java | lgpl-2.1 | 326e8b5903c6e17d46191455dcdf0a578641435e | 0 | tomazzupan/wildfly,rhusar/wildfly,99sono/wildfly,jstourac/wildfly,xasx/wildfly,jstourac/wildfly,tomazzupan/wildfly,iweiss/wildfly,iweiss/wildfly,99sono/wildfly,99sono/wildfly,pferraro/wildfly,golovnin/wildfly,jstourac/wildfly,golovnin/wildfly,wildfly/wildfly,iweiss/wildfly,jstourac/wildfly,pferraro/wildfly,rhusar/wildfly,golovnin/wildfly,tadamski/wildfly,tadamski/wildfly,rhusar/wildfly,pferraro/wildfly,xasx/wildfly,wildfly/wildfly,wildfly/wildfly,tomazzupan/wildfly,rhusar/wildfly,wildfly/wildfly,iweiss/wildfly,xasx/wildfly,tadamski/wildfly,pferraro/wildfly | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation;
import java.security.PrivilegedAction;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import javax.validation.ValidationProviderResolver;
import javax.validation.spi.ValidationProvider;
import org.hibernate.validator.HibernateValidator;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* A {@link ValidationProviderResolver} to be used within WildFly. If several BV providers are available,
* {@code HibernateValidator} will be the first element of the returned provider list.
* <p/>
* The providers are loaded via the current thread's context class loader; If no providers are found, the loader of this class
* will be tried as fallback.
*
* @author Hardy Ferentschik
* @author Gunnar Morling
*/
public class WildFlyProviderResolver implements ValidationProviderResolver {
/**
* Returns a list with all {@link ValidationProvider} validation providers.
*
* @return a list with all {@link ValidationProvider} validation providers
*/
@Override
public List<ValidationProvider<?>> getValidationProviders() {
// first try the TCCL
List<ValidationProvider<?>> providers = getValidationProviders(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged());
if (providers != null && !providers.isEmpty()) {
return providers;
}
// otherwise use the loader of this class
else {
return getValidationProviders(WildFlySecurityManager.getClassLoaderPrivileged(WildFlyProviderResolver.class));
}
}
private List<ValidationProvider<?>> getValidationProviders(final ClassLoader classLoader) {
if(WildFlySecurityManager.isChecking()) {
return WildFlySecurityManager.doUnchecked(new PrivilegedAction<List<ValidationProvider<?>>>() {
@Override
public List<ValidationProvider<?>> run() {
return loadProviders(classLoader);
}
});
} else {
return loadProviders(classLoader);
}
}
/**
* Retrieves the providers from the given loader, using the service loader mechanism.
*
* @param classLoader the class loader to use
* @return a list with providers retrieved via the given loader. May be empty but never {@code null}
*/
private List<ValidationProvider<?>> loadProviders(ClassLoader classLoader) {
@SuppressWarnings("rawtypes")
Iterator<ValidationProvider> providerIterator = ServiceLoader.load(ValidationProvider.class, classLoader).iterator();
LinkedList<ValidationProvider<?>> providers = new LinkedList<ValidationProvider<?>>();
while (providerIterator.hasNext()) {
try {
ValidationProvider<?> provider = providerIterator.next();
// put Hibernate Validator to the beginning of the list
if (provider.getClass().getName().equals(HibernateValidator.class.getName())) {
providers.addFirst(provider);
} else {
providers.add(provider);
}
} catch (ServiceConfigurationError e) {
// ignore, because it can happen when multiple
// providers are present and some of them are not class loader
// compatible with our API.
}
}
return providers;
}
}
| ee/src/main/java/org/jboss/as/ee/beanvalidation/WildFlyProviderResolver.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ee.beanvalidation;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import javax.validation.ValidationProviderResolver;
import javax.validation.spi.ValidationProvider;
import org.hibernate.validator.HibernateValidator;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* A {@link ValidationProviderResolver} to be used within WildFly. If several BV providers are available,
* {@code HibernateValidator} will be the first element of the returned provider list.
* <p/>
* The providers are loaded via the current thread's context class loader; If no providers are found, the loader of this class
* will be tried as fallback.
*
* @author Hardy Ferentschik
* @author Gunnar Morling
*/
public class WildFlyProviderResolver implements ValidationProviderResolver {
/**
* Returns a list with all {@link ValidationProvider} validation providers.
*
* @return a list with all {@link ValidationProvider} validation providers
*/
@Override
public List<ValidationProvider<?>> getValidationProviders() {
// first try the TCCL
List<ValidationProvider<?>> providers = loadProviders(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged());
if (providers != null && !providers.isEmpty()) {
return providers;
}
// otherwise use the loader of this class
else {
return loadProviders(WildFlySecurityManager.getClassLoaderPrivileged(WildFlyProviderResolver.class));
}
}
/**
* Retrieves the providers from the given loader, using the service loader mechanism.
*
* @param classLoader the class loader to use
* @return a list with providers retrieved via the given loader. May be empty but never {@code null}
*/
private List<ValidationProvider<?>> loadProviders(ClassLoader classLoader) {
@SuppressWarnings("rawtypes")
Iterator<ValidationProvider> providerIterator = ServiceLoader.load(ValidationProvider.class, classLoader).iterator();
LinkedList<ValidationProvider<?>> providers = new LinkedList<ValidationProvider<?>>();
while (providerIterator.hasNext()) {
try {
ValidationProvider<?> provider = providerIterator.next();
// put Hibernate Validator to the beginning of the list
if (provider.getClass().getName().equals(HibernateValidator.class.getName())) {
providers.addFirst(provider);
} else {
providers.add(provider);
}
} catch (ServiceConfigurationError e) {
// ignore, because it can happen when multiple
// providers are present and some of them are not class loader
// compatible with our API.
}
}
return providers;
}
}
| Fix permission issue with bean validation
| ee/src/main/java/org/jboss/as/ee/beanvalidation/WildFlyProviderResolver.java | Fix permission issue with bean validation | <ide><path>e/src/main/java/org/jboss/as/ee/beanvalidation/WildFlyProviderResolver.java
<ide> */
<ide> package org.jboss.as.ee.beanvalidation;
<ide>
<add>import java.security.PrivilegedAction;
<ide> import java.util.Iterator;
<ide> import java.util.LinkedList;
<ide> import java.util.List;
<ide> @Override
<ide> public List<ValidationProvider<?>> getValidationProviders() {
<ide> // first try the TCCL
<del> List<ValidationProvider<?>> providers = loadProviders(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged());
<add> List<ValidationProvider<?>> providers = getValidationProviders(WildFlySecurityManager.getCurrentContextClassLoaderPrivileged());
<ide>
<ide> if (providers != null && !providers.isEmpty()) {
<ide> return providers;
<ide> }
<ide> // otherwise use the loader of this class
<ide> else {
<del> return loadProviders(WildFlySecurityManager.getClassLoaderPrivileged(WildFlyProviderResolver.class));
<add> return getValidationProviders(WildFlySecurityManager.getClassLoaderPrivileged(WildFlyProviderResolver.class));
<add> }
<add> }
<add>
<add> private List<ValidationProvider<?>> getValidationProviders(final ClassLoader classLoader) {
<add> if(WildFlySecurityManager.isChecking()) {
<add> return WildFlySecurityManager.doUnchecked(new PrivilegedAction<List<ValidationProvider<?>>>() {
<add> @Override
<add> public List<ValidationProvider<?>> run() {
<add> return loadProviders(classLoader);
<add> }
<add> });
<add> } else {
<add> return loadProviders(classLoader);
<ide> }
<ide> }
<ide> |
|
Java | mit | d955de22aa6939b6682ebf10e829812b73616048 | 0 | culvertsoft/mgen,culvertsoft/mgen,culvertsoft/mgen,culvertsoft/mgen,culvertsoft/mgen,culvertsoft/mgen | package se.culvertsoft.mgen.javapack.serialization;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_BOOL;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_CUSTOM;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_FLOAT32;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_FLOAT64;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_INT16;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_INT32;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_INT64;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_INT8;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_LIST;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_MAP;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_STRING;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import se.culvertsoft.mgen.api.model.ArrayType;
import se.culvertsoft.mgen.api.model.CustomType;
import se.culvertsoft.mgen.api.model.Field;
import se.culvertsoft.mgen.api.model.ListType;
import se.culvertsoft.mgen.api.model.MapType;
import se.culvertsoft.mgen.api.model.Type;
import se.culvertsoft.mgen.javapack.classes.ClassRegistryBase;
import se.culvertsoft.mgen.javapack.classes.MGenBase;
import se.culvertsoft.mgen.javapack.exceptions.SerializationException;
import se.culvertsoft.mgen.javapack.util.FastByteBuffer;
import se.culvertsoft.mgen.javapack.util.Varint;
public class BinaryWriter extends BuiltInWriter {
public static final boolean DEFAULT_COMPACT = false;
public static final int FLUSH_SIZE = 256;
private final FastByteBuffer m_buffer;
private final OutputStream m_streamOut;
private final boolean m_compact;
private long m_expectType;
public BinaryWriter(
final OutputStream stream,
final ClassRegistryBase classRegistry,
final boolean compact) {
super(classRegistry);
m_buffer = new FastByteBuffer(FLUSH_SIZE * 2);
m_streamOut = stream;
m_compact = compact;
m_expectType = -1;
}
public BinaryWriter(final OutputStream stream, final ClassRegistryBase classRegistry) {
this(stream, classRegistry, DEFAULT_COMPACT);
}
@Override
public void writeObject(final MGenBase o) throws IOException {
m_expectType = -1;
m_buffer.clear();
writeMGenObject(o, true, null);
flush();
}
@Override
public void beginWrite(final MGenBase object, final int nFieldsSet, final int nFieldsTotal)
throws IOException {
if (shouldOmitIds(object)) {
writeSize((nFieldsSet << 2) | 0x02);
} else {
final short[] ids = object._typeIds16Bit();
writeSize((ids.length << 2) | 0x01);
for (final short id : ids)
writeInt16(id, false);
writeSize(nFieldsSet);
}
}
@Override
public void finishWrite() {
}
@Override
public void writeBooleanField(final boolean b, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_BOOL);
writeBoolean(b, false);
}
@Override
public void writeInt8Field(final byte b, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_INT8);
writeInt8(b, false);
}
@Override
public void writeInt16Field(final short s, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_INT16);
writeInt16(s, false);
}
@Override
public void writeInt32Field(final int i, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_INT32);
writeInt32(i, false);
}
@Override
public void writeInt64Field(final long l, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_INT64);
writeInt64(l, false);
}
@Override
public void writeFloat32Field(final float f, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_FLOAT32);
writeFloat32(f, false);
}
@Override
public void writeFloat64Field(final double d, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_FLOAT64);
writeFloat64(d, false);
}
@Override
public void writeStringField(final String s, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_STRING);
writeString(s, false);
}
@Override
public void writeListField(final ArrayList<Object> list, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_LIST);
writeList(list, (ListType) field.typ(), false);
}
@Override
public void writeMapField(final HashMap<Object, Object> map, final Field field)
throws IOException {
writeFieldStart(field.id(), TAG_MAP);
writeMap(map, (MapType) field.typ(), false);
}
@Override
public void writeArrayField(final Object arrayObj, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_LIST);
writeArray(arrayObj, (ArrayType) field.typ(), false);
}
@Override
public void writeEnumField(final Enum<?> e, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_STRING);
writeEnum(e, false);
}
@Override
public void writeMGenObjectField(final MGenBase o, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_CUSTOM);
writeMGenObject(o, false, (CustomType) field.typ());
}
/*******************************************************************
*
*
* - - - - - - - - - - INTERNAL METHODS
*
******************************************************************/
private void writeMGenObject(final MGenBase o, final boolean tag, final CustomType typ)
throws IOException {
if (tag)
writeTypeTag(TAG_CUSTOM);
if (o != null) {
m_expectType = typ != null ? typ.typeId() : 0;
o._accept(this);
} else {
writeByte(0);
}
}
private void writeFieldStart(final short id, final byte tag) throws IOException {
writeInt16(id, false);
writeTypeTag(tag);
}
private void writeEnum(final Enum<?> e, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_STRING);
writeString(String.valueOf(e), tag);
}
private void writeBoolean(final boolean b, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_BOOL);
writeByte(b ? 1 : 0);
}
private void writeInt8(final int b, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_INT8);
writeByte(b);
}
private void writeInt16(final short s, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_INT16);
writeRawInt16(s);
}
private void writeInt32(final int i, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_INT32);
writeSignedVarint32(i);
}
private void writeInt64(final long l, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_INT64);
writeSignedVarint64(l);
}
private void writeFloat32(final float f, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_FLOAT32);
writeRawInt32(Float.floatToIntBits(f));
}
private void writeFloat64(final double d, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_FLOAT64);
writeRawInt64(Double.doubleToLongBits(d));
}
private void writeString(final String s, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_STRING);
if (s != null && !s.isEmpty()) {
m_stringEncoder.encode(s);
writeSize(m_stringEncoder.size());
writeBytes(m_stringEncoder.data(), m_stringEncoder.size());
} else {
writeSize(0);
}
}
private void writeList(final List<Object> list, final ListType typ, final boolean tag)
throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
writeElements(false, list, typ.elementType());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void writeElements(
final boolean doWriteListTag,
final Collection<Object> list,
final Type elementType) throws IOException {
if (doWriteListTag)
writeTypeTag(TAG_LIST);
if (list != null && !list.isEmpty()) {
writeSize(list.size());
writeTypeTag(elementType.typeTag());
switch (elementType.typeEnum()) {
case ENUM: {
final Collection<Enum<?>> l = (Collection) list;
for (final Enum<?> e : l)
writeEnum(e, false);
break;
}
case BOOL: {
final Collection<Boolean> l = (Collection) list;
for (final Boolean e : l)
writeBoolean(e != null ? e : false, false);
break;
}
case INT8: {
final Collection<Byte> l = (Collection) list;
for (final Byte e : l)
writeInt8(e != null ? e : (byte) 0, false);
break;
}
case INT16: {
final Collection<Short> l = (Collection) list;
for (final Short e : l)
writeInt16(e != null ? e : (short) 0, false);
break;
}
case INT32: {
final Collection<Integer> l = (Collection) list;
for (final Integer e : l)
writeInt32(e != null ? e : 0, false);
break;
}
case INT64: {
final Collection<Long> l = (Collection) list;
for (final Long e : l)
writeInt64(e != null ? e : 0, false);
break;
}
case FLOAT32: {
final Collection<Float> l = (Collection) list;
for (final Float e : l)
writeFloat32(e != null ? e : 0.0f, false);
break;
}
case FLOAT64: {
final Collection<Double> l = (Collection) list;
for (final Double e : l)
writeFloat64(e != null ? e : 0.0, false);
break;
}
case STRING: {
final Collection<String> l = (Collection) list;
for (final String e : l)
writeString(e, false);
break;
}
default:
for (final Object o : list)
writeObject(o, elementType, false);
break;
}
} else {
writeSize(0);
}
}
private void writeMap(final HashMap<Object, Object> map, final MapType typ, final boolean tag)
throws IOException {
if (tag)
writeTypeTag(TAG_MAP);
if (map != null && !map.isEmpty()) {
writeSize(map.size());
writeElements(true, map.keySet(), typ.keyType());
writeElements(true, map.values(), typ.valueType());
} else {
writeSize(0);
}
}
private void writeArray(final Object arrayObj, final ArrayType typ, final boolean tag)
throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (arrayObj != null) {
final Type elementType = typ.elementType();
switch (elementType.typeEnum()) {
case ENUM:
writeEnumArray((Enum<?>[]) arrayObj, false);
break;
case BOOL:
writeBooleanArray((boolean[]) arrayObj, false);
break;
case INT8:
writeInt8Array((byte[]) arrayObj, false);
break;
case INT16:
writeInt16Array((short[]) arrayObj, false);
break;
case INT32:
writeInt32Array((int[]) arrayObj, false);
break;
case INT64:
writeInt64Array((long[]) arrayObj, false);
break;
case FLOAT32:
writeFloat32Array((float[]) arrayObj, false);
break;
case FLOAT64:
writeFloat64Array((double[]) arrayObj, false);
break;
case STRING:
writeStringArray((String[]) arrayObj, false);
break;
default:
writeObjectArray((Object[]) arrayObj, elementType, false);
break;
}
} else {
writeSize(0);
}
}
private void writeEnumArray(final Enum<?>[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_STRING);
for (final Enum<?> e : array)
writeEnum(e, false);
} else {
writeSize(0);
}
}
private void writeBooleanArray(final boolean[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_BOOL);
for (final boolean b : array)
writeBoolean(b, false);
} else {
writeSize(0);
}
}
private void writeInt8Array(final byte[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_INT8);
writeBytes(array);
} else {
writeSize(0);
}
}
private void writeInt16Array(final short[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_INT16);
for (final short s : array)
writeInt16(s, false);
} else {
writeSize(0);
}
}
private void writeInt32Array(final int[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_INT32);
for (final int i : array)
writeInt32(i, false);
} else {
writeSize(0);
}
}
private void writeInt64Array(final long[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_INT64);
for (final long l : array)
writeInt64(l, false);
} else {
writeSize(0);
}
}
private void writeFloat32Array(final float[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_FLOAT32);
for (final float f : array)
writeFloat32(f, false);
} else {
writeSize(0);
}
}
private void writeStringArray(final String[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_STRING);
for (final String s : array)
writeString(s, false);
} else {
writeSize(0);
}
}
private void writeFloat64Array(final double[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_FLOAT64);
for (final double f : array)
writeFloat64(f, false);
} else {
writeSize(0);
}
}
private void writeObjectArray(final Object[] array, final Type elementType, final boolean tag)
throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(elementType.typeTag());
for (final Object o : array)
writeObject(o, elementType, false);
} else {
writeSize(0);
}
}
private void flush() throws IOException {
if (m_buffer.nonEmpty()) {
m_streamOut.write(m_buffer.data(), 0, m_buffer.size());
m_buffer.clear();
}
}
private void checkFlush() throws IOException {
if (m_buffer.size() >= FLUSH_SIZE)
flush();
}
private void writeByte(int b) throws IOException {
m_buffer.write(b);
checkFlush();
}
private void writeBytes(final byte[] data, final int offset, final int sz) throws IOException {
m_buffer.write(data, offset, sz);
checkFlush();
}
private void writeBytes(final byte[] data, final int sz) throws IOException {
writeBytes(data, 0, sz);
}
private void writeBytes(final byte[] data) throws IOException {
writeBytes(data, 0, data.length);
}
private void writeRawInt16(short s) throws IOException {
writeByte(s >>> 8);
writeByte(s >>> 0);
}
private void writeRawInt32(int v) throws IOException {
writeByte(v >>> 24);
writeByte(v >>> 16);
writeByte(v >>> 8);
writeByte(v >>> 0);
}
private void writeRawInt64(long v) throws IOException {
writeByte((int) (v >>> 56));
writeByte((int) (v >>> 48));
writeByte((int) (v >>> 40));
writeByte((int) (v >>> 32));
writeByte((int) (v >>> 24));
writeByte((int) (v >>> 16));
writeByte((int) (v >>> 8));
writeByte((int) (v >>> 0));
}
private void writeSignedVarint32(final int i) throws IOException {
Varint.writeSignedVarInt(i, m_buffer);
checkFlush();
}
private void writeSignedVarint64(final long l) throws IOException {
Varint.writeSignedVarLong(l, m_buffer);
checkFlush();
}
private void writeUnsignedVarint32(final int i) throws IOException {
Varint.writeUnsignedVarInt(i, m_buffer);
checkFlush();
}
private void writeSize(final int i) throws IOException {
writeUnsignedVarint32(i);
}
@SuppressWarnings("unchecked")
private void writeObject(final Object o, final Type typ, boolean tag) throws IOException {
switch (typ.typeEnum()) {
case ENUM:
writeEnum((Enum<?>) o, tag);
break;
case BOOL:
writeBoolean(o != null ? (Boolean) o : false, tag);
break;
case INT8:
writeInt8(o != null ? (Byte) o : 0, tag);
break;
case INT16:
writeInt16(o != null ? (Short) o : 0, tag);
break;
case INT32:
writeInt32(o != null ? (Integer) o : 0, tag);
break;
case INT64:
writeInt64(o != null ? (Long) o : 0, tag);
break;
case FLOAT32:
writeFloat32(o != null ? (Float) o : 0.0f, tag);
break;
case FLOAT64:
writeFloat64(o != null ? (Double) o : 0.0, tag);
break;
case ARRAY:
writeArray(o, (ArrayType) typ, tag);
break;
case STRING:
writeString((String) o, tag);
break;
case LIST:
writeList((List<Object>) o, (ListType) typ, tag);
break;
case MAP:
writeMap((HashMap<Object, Object>) o, (MapType) typ, tag);
break;
case CUSTOM:
case UNKNOWN:
writeMGenObject((MGenBase) o, tag, (CustomType) typ);
break;
default:
throw new SerializationException("Unknown type tag for writeObject");
}
}
private boolean shouldOmitIds(final MGenBase o) {
return m_compact && o._typeId() == m_expectType;
}
private void writeTypeTag(byte tag) throws IOException {
writeByte(tag);
}
}
| mgen-javalib/src/main/java/se/culvertsoft/mgen/javapack/serialization/BinaryWriter.java | package se.culvertsoft.mgen.javapack.serialization;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_BOOL;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_CUSTOM;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_FLOAT32;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_FLOAT64;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_INT16;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_INT32;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_INT64;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_INT8;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_LIST;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_MAP;
import static se.culvertsoft.mgen.api.model.BinaryTypeTag.TAG_STRING;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import se.culvertsoft.mgen.api.model.ArrayType;
import se.culvertsoft.mgen.api.model.CustomType;
import se.culvertsoft.mgen.api.model.Field;
import se.culvertsoft.mgen.api.model.ListType;
import se.culvertsoft.mgen.api.model.MapType;
import se.culvertsoft.mgen.api.model.Type;
import se.culvertsoft.mgen.javapack.classes.ClassRegistryBase;
import se.culvertsoft.mgen.javapack.classes.MGenBase;
import se.culvertsoft.mgen.javapack.exceptions.SerializationException;
import se.culvertsoft.mgen.javapack.util.FastByteBuffer;
import se.culvertsoft.mgen.javapack.util.Varint;
public class BinaryWriter extends BuiltInWriter {
public static final boolean DEFAULT_COMPACT = false;
public static final int FLUSH_SIZE = 256;
private final FastByteBuffer m_buffer;
private final OutputStream m_streamOut;
private final boolean m_compact;
private long m_expectType;
public BinaryWriter(
final OutputStream stream,
final ClassRegistryBase classRegistry,
final boolean compact) {
super(classRegistry);
m_buffer = new FastByteBuffer(FLUSH_SIZE * 2);
m_streamOut = stream;
m_compact = compact;
m_expectType = -1;
}
public BinaryWriter(final OutputStream stream, final ClassRegistryBase classRegistry) {
this(stream, classRegistry, DEFAULT_COMPACT);
}
@Override
public void writeObject(final MGenBase o) throws IOException {
m_expectType = -1;
m_buffer.clear();
writeMGenObject(o, true, null);
flush();
}
@Override
public void beginWrite(final MGenBase object, final int nFieldsSet, final int nFieldsTotal)
throws IOException {
if (shouldOmitIds(object)) {
writeSize((nFieldsSet << 2) | 0x02);
} else {
final short[] ids = object._typeIds16Bit();
writeSize((ids.length << 2) | 0x01);
for (final short id : ids)
writeInt16(id, false);
writeSize(nFieldsSet);
}
}
@Override
public void finishWrite() {
}
@Override
public void writeBooleanField(final boolean b, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_BOOL);
writeBoolean(b, false);
}
@Override
public void writeInt8Field(final byte b, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_INT8);
writeInt8(b, false);
}
@Override
public void writeInt16Field(final short s, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_INT16);
writeInt16(s, false);
}
@Override
public void writeInt32Field(final int i, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_INT32);
writeInt32(i, false);
}
@Override
public void writeInt64Field(final long l, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_INT64);
writeInt64(l, false);
}
@Override
public void writeFloat32Field(final float f, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_FLOAT32);
writeFloat32(f, false);
}
@Override
public void writeFloat64Field(final double d, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_FLOAT64);
writeFloat64(d, false);
}
@Override
public void writeStringField(final String s, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_STRING);
writeString(s, false);
}
@Override
public void writeListField(final ArrayList<Object> list, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_LIST);
writeList(list, (ListType) field.typ(), false);
}
@Override
public void writeMapField(final HashMap<Object, Object> map, final Field field)
throws IOException {
writeFieldStart(field.id(), TAG_MAP);
writeMap(map, (MapType) field.typ(), false);
}
@Override
public void writeArrayField(final Object arrayObj, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_LIST);
writeArray(arrayObj, (ArrayType) field.typ(), false);
}
@Override
public void writeEnumField(final Enum<?> e, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_STRING);
writeEnum(e, false);
}
@Override
public void writeMGenObjectField(final MGenBase o, final Field field) throws IOException {
writeFieldStart(field.id(), TAG_CUSTOM);
writeMGenObject(o, false, (CustomType) field.typ());
}
/*******************************************************************
*
*
* - - - - - - - - - - INTERNAL METHODS
*
******************************************************************/
private void writeMGenObject(final MGenBase o, final boolean tag, final CustomType typ)
throws IOException {
if (tag)
writeTypeTag(TAG_CUSTOM);
if (o != null) {
m_expectType = typ != null ? typ.typeId() : 0;
o._accept(this);
} else {
writeByte(0);
}
}
private void writeFieldStart(final short id, final byte tag) throws IOException {
writeInt16(id, false);
writeTypeTag(tag);
}
private void writeEnum(final Enum<?> e, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_STRING);
writeString(String.valueOf(e), tag);
}
private void writeBoolean(final boolean b, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_BOOL);
writeByte(b ? 1 : 0);
}
private void writeInt8(final int b, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_INT8);
writeByte(b);
}
private void writeInt16(final short s, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_INT16);
writeRawInt16(s);
}
private void writeInt32(final int i, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_INT32);
writeSignedVarint32(i);
}
private void writeInt64(final long l, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_INT64);
writeSignedVarint64(l);
}
private void writeFloat32(final float f, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_FLOAT32);
writeRawInt32(Float.floatToIntBits(f));
}
private void writeFloat64(final double d, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_FLOAT64);
writeRawInt64(Double.doubleToLongBits(d));
}
private void writeString(final String s, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_STRING);
if (s != null && !s.isEmpty()) {
m_stringEncoder.encode(s);
writeSize(m_stringEncoder.size());
writeBytes(m_stringEncoder.data(), m_stringEncoder.size());
} else {
writeSize(0);
}
}
private void writeList(final List<Object> list, final ListType typ, final boolean tag)
throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
writeElements(false, list, typ.elementType());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void writeElements(
final boolean doWriteListTag,
final Collection<Object> list,
final Type elementType) throws IOException {
if (doWriteListTag)
writeTypeTag(TAG_LIST);
if (list != null && !list.isEmpty()) {
writeSize(list.size());
writeTypeTag(elementType.typeTag());
switch (elementType.typeEnum()) {
case ENUM: {
final Collection<Enum<?>> l = (Collection) list;
for (final Enum<?> e : l)
writeEnum(e, false);
break;
}
case BOOL: {
final Collection<Boolean> l = (Collection) list;
for (final Boolean e : l)
writeBoolean(e != null ? e : false, false);
break;
}
case INT8: {
final Collection<Byte> l = (Collection) list;
for (final Byte e : l)
writeInt8(e != null ? e : (byte) 0, false);
break;
}
case INT16: {
final Collection<Short> l = (Collection) list;
for (final Short e : l)
writeInt16(e != null ? e : (short) 0, false);
break;
}
case INT32: {
final Collection<Integer> l = (Collection) list;
for (final Integer e : l)
writeInt32(e != null ? e : 0, false);
break;
}
case INT64: {
final Collection<Long> l = (Collection) list;
for (final Long e : l)
writeInt64(e != null ? e : 0, false);
break;
}
case FLOAT32: {
final Collection<Float> l = (Collection) list;
for (final Float e : l)
writeFloat32(e != null ? e : 0.0f, false);
break;
}
case FLOAT64: {
final Collection<Double> l = (Collection) list;
for (final Double e : l)
writeFloat64(e != null ? e : 0.0, false);
break;
}
case STRING: {
final Collection<String> l = (Collection) list;
for (final String e : l)
writeString(e, false);
break;
}
default:
for (final Object o : list)
writeObject(o, elementType, false);
break;
}
} else {
writeSize(0);
}
}
private void writeMap(final HashMap<Object, Object> map, final MapType typ, final boolean tag)
throws IOException {
if (tag)
writeTypeTag(TAG_MAP);
if (map != null && !map.isEmpty()) {
writeSize(map.size());
writeElements(true, map.keySet(), typ.keyType());
writeElements(true, map.values(), typ.valueType());
} else {
writeSize(0);
}
}
private void writeArray(final Object arrayObj, final ArrayType typ, final boolean tag)
throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (arrayObj != null) {
final Type elementType = typ.elementType();
switch (elementType.typeEnum()) {
case ENUM:
writeEnumArray((Enum<?>[]) arrayObj, false);
break;
case BOOL:
writeBooleanArray((boolean[]) arrayObj, false);
break;
case INT8:
writeInt8Array((byte[]) arrayObj, false);
break;
case INT16:
writeInt16Array((short[]) arrayObj, false);
break;
case INT32:
writeInt32Array((int[]) arrayObj, false);
break;
case INT64:
writeInt64Array((long[]) arrayObj, false);
break;
case FLOAT32:
writeFloat32Array((float[]) arrayObj, false);
break;
case FLOAT64:
writeFloat64Array((double[]) arrayObj, false);
break;
default:
writeObjectArray((Object[]) arrayObj, elementType, false);
break;
}
} else {
writeSize(0);
}
}
private void writeEnumArray(final Enum<?>[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_STRING);
for (final Enum<?> e : array)
writeEnum(e, false);
} else {
writeSize(0);
}
}
private void writeBooleanArray(final boolean[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_BOOL);
for (final boolean b : array)
writeBoolean(b, false);
} else {
writeSize(0);
}
}
private void writeInt8Array(final byte[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_INT8);
writeBytes(array);
} else {
writeSize(0);
}
}
private void writeInt16Array(final short[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_INT16);
for (final short s : array)
writeInt16(s, false);
} else {
writeSize(0);
}
}
private void writeInt32Array(final int[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_INT32);
for (final int i : array)
writeInt32(i, false);
} else {
writeSize(0);
}
}
private void writeInt64Array(final long[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_INT64);
for (final long l : array)
writeInt64(l, false);
} else {
writeSize(0);
}
}
private void writeFloat32Array(final float[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_FLOAT32);
for (final float f : array)
writeFloat32(f, false);
} else {
writeSize(0);
}
}
private void writeFloat64Array(final double[] array, final boolean tag) throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(TAG_FLOAT64);
for (final double f : array)
writeFloat64(f, false);
} else {
writeSize(0);
}
}
private void writeObjectArray(final Object[] array, final Type elementType, final boolean tag)
throws IOException {
if (tag)
writeTypeTag(TAG_LIST);
if (array != null && array.length != 0) {
writeSize(array.length);
writeTypeTag(elementType.typeTag());
for (final Object o : array)
writeObject(o, elementType, false);
} else {
writeSize(0);
}
}
private void flush() throws IOException {
if (m_buffer.nonEmpty()) {
m_streamOut.write(m_buffer.data(), 0, m_buffer.size());
m_buffer.clear();
}
}
private void checkFlush() throws IOException {
if (m_buffer.size() >= FLUSH_SIZE)
flush();
}
private void writeByte(int b) throws IOException {
m_buffer.write(b);
checkFlush();
}
private void writeBytes(final byte[] data, final int offset, final int sz) throws IOException {
m_buffer.write(data, offset, sz);
checkFlush();
}
private void writeBytes(final byte[] data, final int sz) throws IOException {
writeBytes(data, 0, sz);
}
private void writeBytes(final byte[] data) throws IOException {
writeBytes(data, 0, data.length);
}
private void writeRawInt16(short s) throws IOException {
writeByte(s >>> 8);
writeByte(s >>> 0);
}
private void writeRawInt32(int v) throws IOException {
writeByte(v >>> 24);
writeByte(v >>> 16);
writeByte(v >>> 8);
writeByte(v >>> 0);
}
private void writeRawInt64(long v) throws IOException {
writeByte((int) (v >>> 56));
writeByte((int) (v >>> 48));
writeByte((int) (v >>> 40));
writeByte((int) (v >>> 32));
writeByte((int) (v >>> 24));
writeByte((int) (v >>> 16));
writeByte((int) (v >>> 8));
writeByte((int) (v >>> 0));
}
private void writeSignedVarint32(final int i) throws IOException {
Varint.writeSignedVarInt(i, m_buffer);
checkFlush();
}
private void writeSignedVarint64(final long l) throws IOException {
Varint.writeSignedVarLong(l, m_buffer);
checkFlush();
}
private void writeUnsignedVarint32(final int i) throws IOException {
Varint.writeUnsignedVarInt(i, m_buffer);
checkFlush();
}
private void writeSize(final int i) throws IOException {
writeUnsignedVarint32(i);
}
@SuppressWarnings("unchecked")
private void writeObject(final Object o, final Type typ, boolean tag) throws IOException {
switch (typ.typeEnum()) {
case ENUM:
writeEnum((Enum<?>) o, tag);
break;
case BOOL:
writeBoolean(o != null ? (Boolean) o : false, tag);
break;
case INT8:
writeInt8(o != null ? (Byte) o : 0, tag);
break;
case INT16:
writeInt16(o != null ? (Short) o : 0, tag);
break;
case INT32:
writeInt32(o != null ? (Integer) o : 0, tag);
break;
case INT64:
writeInt64(o != null ? (Long) o : 0, tag);
break;
case FLOAT32:
writeFloat32(o != null ? (Float) o : 0.0f, tag);
break;
case FLOAT64:
writeFloat64(o != null ? (Double) o : 0.0, tag);
break;
case ARRAY:
writeArray(o, (ArrayType) typ, tag);
break;
case STRING:
writeString((String) o, tag);
break;
case LIST:
writeList((List<Object>) o, (ListType) typ, tag);
break;
case MAP:
writeMap((HashMap<Object, Object>) o, (MapType) typ, tag);
break;
case CUSTOM:
case UNKNOWN:
writeMGenObject((MGenBase) o, tag, (CustomType) typ);
break;
default:
throw new SerializationException("Unknown type tag for writeObject");
}
}
private boolean shouldOmitIds(final MGenBase o) {
return m_compact && o._typeId() == m_expectType;
}
private void writeTypeTag(byte tag) throws IOException {
writeByte(tag);
}
}
| Added optimized writeStringArray to java binarywriter
| mgen-javalib/src/main/java/se/culvertsoft/mgen/javapack/serialization/BinaryWriter.java | Added optimized writeStringArray to java binarywriter | <ide><path>gen-javalib/src/main/java/se/culvertsoft/mgen/javapack/serialization/BinaryWriter.java
<ide> case FLOAT64:
<ide> writeFloat64Array((double[]) arrayObj, false);
<ide> break;
<add> case STRING:
<add> writeStringArray((String[]) arrayObj, false);
<add> break;
<ide> default:
<ide> writeObjectArray((Object[]) arrayObj, elementType, false);
<ide> break;
<ide>
<ide> }
<ide>
<add> private void writeStringArray(final String[] array, final boolean tag) throws IOException {
<add>
<add> if (tag)
<add> writeTypeTag(TAG_LIST);
<add>
<add> if (array != null && array.length != 0) {
<add>
<add> writeSize(array.length);
<add>
<add> writeTypeTag(TAG_STRING);
<add>
<add> for (final String s : array)
<add> writeString(s, false);
<add>
<add> } else {
<add> writeSize(0);
<add> }
<add>
<add> }
<add>
<ide> private void writeFloat64Array(final double[] array, final boolean tag) throws IOException {
<ide>
<ide> if (tag) |
|
Java | mit | 6549a0ef31fb05ff62cc8b12f73e594d04f40528 | 0 | Thatsmusic99/HeadsPlus | package io.github.thatsmusic99.headsplus.commands.maincommand;
import io.github.thatsmusic99.headsplus.HeadsPlus;
import io.github.thatsmusic99.headsplus.api.HPPlayer;
import io.github.thatsmusic99.headsplus.commands.CommandInfo;
import io.github.thatsmusic99.headsplus.commands.IHeadsPlusCommand;
import io.github.thatsmusic99.headsplus.config.ConfigCrafting;
import io.github.thatsmusic99.headsplus.config.ConfigMobs;
import io.github.thatsmusic99.headsplus.config.MessagesManager;
import io.github.thatsmusic99.headsplus.inventories.InventoryManager;
import io.github.thatsmusic99.headsplus.managers.PersistenceManager;
import io.github.thatsmusic99.headsplus.managers.SellableHeadsManager;
import io.github.thatsmusic99.headsplus.util.DebugFileCreator;
import io.github.thatsmusic99.headsplus.util.events.HeadsPlusException;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
@CommandInfo(
commandname = "debug",
permission = "headsplus.maincommand.debug",
maincommand = true,
usage = "/hp debug <dump|head|player|clearim|item|delete|save|transfer> <Player IGN>|<Database>",
descriptionPath = "descriptions.hp.debug"
)
@Deprecated // Also needs a cleanup
public class DebugPrint implements IHeadsPlusCommand {
private static final MessagesManager hpc = MessagesManager.get();
public static void createReport(Exception e, String name, boolean command, CommandSender sender) {
try {
Logger log = HeadsPlus.get().getLogger();
e.printStackTrace();
if (command && sender != null) {
hpc.sendMessage("commands.errors.cmd-fail", sender);
}
log.severe("HeadsPlus has failed to execute this task. An error report has been made in /plugins/HeadsPlus/debug");
String s = DebugFileCreator.createReport(new HeadsPlusException(e));
log.severe("Report name: " + s);
log.severe("Please submit this report to the developer at one of the following links:");
log.severe("https://github.com/Thatsmusic99/HeadsPlus/issues");
log.severe("https://discord.gg/nbT7wC2");
log.severe("https://www.spigotmc.org/threads/headsplus-1-8-x-1-12-x.237088/");
} catch (Exception ex) {
HeadsPlus.get().getLogger().warning("An error has occurred! We tried creating a debug report, but that didn't work... stacktraces:");
e.printStackTrace();
ex.printStackTrace();
}
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
try {
if (args.length < 2) {
hpc.sendMessage("commands.errors.invalid-args", sender);
return false;
}
String subcommand = args[1].toLowerCase();
// Subcommands are fairly brief, so there isn't necessarily any point in creating separate classes
if (sender.hasPermission("headsplus.maincommand.debug." + subcommand)) {
String report;
switch (subcommand) {
case "dump":
report = DebugFileCreator.createReport(null);
sender.sendMessage(ChatColor.GREEN + "Report name: " + report);
break;
case "player":
if (args.length > 2) {
HPPlayer pl = HPPlayer.getHPPlayer(Bukkit.getOfflinePlayer(args[2]).getUniqueId());
if (pl != null) {
report = new DebugFileCreator().createPlayerReport(pl);
sender.sendMessage(ChatColor.GREEN + "Report name: " + report);
} else {
hpc.sendMessage("commands.profile.no-data", sender);
}
} else {
hpc.sendMessage("commands.errors.invalid-args", sender);
}
break;
case "head":
if (sender instanceof Player) {
ItemStack is = ((Player) sender).getInventory().getItemInMainHand();
String s = new DebugFileCreator().createHeadReport(is);
sender.sendMessage(ChatColor.GREEN + "Report name: " + s);
}
break;
case "clearim":
InventoryManager.storedInventories.clear();
sender.sendMessage(ChatColor.GREEN + "Inventory cache cleared.");
break;
case "item":
if (sender instanceof Player) {
ItemStack item = ((Player) sender).getInventory().getItemInMainHand();
String s = new DebugFileCreator().createItemReport(item);
sender.sendMessage(ChatColor.GREEN + "Report name: " + s);
} else {
hpc.sendMessage("commands.errors.not-a-player", sender);
}
break;
case "fix":
if (sender instanceof Player) {
Player player = (Player) sender;
if (args.length > 2) {
if (SellableHeadsManager.get().isRegistered(args[2])) {
int slot = player.getInventory().getHeldItemSlot();
// lmao who needs getItemInMainHand
ItemStack item = player.getInventory().getItem(slot);
if (item == null) return false;
item = item.clone();
PersistenceManager.get().setSellable(item, true);
PersistenceManager.get().setSellType(item, args[2]);
double price;
double headsPrice = ConfigMobs.get().getPrice(args[2].toLowerCase().replaceAll("_", ""));
if (headsPrice != 0.0) {
price = headsPrice;
} else {
price = ConfigCrafting.get().getPrice(args[2]);
}
PersistenceManager.get().setSellPrice(item, price);
final ItemStack finalItem = item;
Bukkit.getScheduler().runTask(HeadsPlus.get(), () -> player.getInventory().setItem(slot, finalItem));
} else {
hpc.sendMessage("commands.errors.invalid-args", sender);
}
} else {
hpc.sendMessage("commands.errors.invalid-args", sender);
}
} else {
hpc.sendMessage("commands.errors.not-a-player", sender);
}
break;
case "verbose":
DebugVerbose.fire(sender, args);
}
}
} catch (IOException | IllegalAccessException e) {
e.printStackTrace();
}
return true;
}
@Override
public boolean shouldEnable() {
return true;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) {
List<String> results = new ArrayList<>();
if (sender.hasPermission("headsplus.commands.debug")) {
if (args.length == 2) {
StringUtil.copyPartialMatches(args[1], Arrays.asList("dump", "head", "player", "clearim", "item", "delete", "save", "transfer", "fix", "verbose"), results);
} else if (args.length > 2) {
switch (args[1].toLowerCase()) {
case "fix":
StringUtil.copyPartialMatches(args[2], SellableHeadsManager.get().getKeys(), results);
break;
case "verbose":
results = DebugVerbose.onTabComplete(sender, args);
break;
default:
StringUtil.copyPartialMatches(args[2], IHeadsPlusCommand.getPlayers(sender), results);
break;
}
}
}
return results;
}
}
| src/main/java/io/github/thatsmusic99/headsplus/commands/maincommand/DebugPrint.java | package io.github.thatsmusic99.headsplus.commands.maincommand;
import io.github.thatsmusic99.headsplus.HeadsPlus;
import io.github.thatsmusic99.headsplus.api.HPPlayer;
import io.github.thatsmusic99.headsplus.commands.CommandInfo;
import io.github.thatsmusic99.headsplus.commands.IHeadsPlusCommand;
import io.github.thatsmusic99.headsplus.config.ConfigCrafting;
import io.github.thatsmusic99.headsplus.config.ConfigMobs;
import io.github.thatsmusic99.headsplus.config.MessagesManager;
import io.github.thatsmusic99.headsplus.inventories.InventoryManager;
import io.github.thatsmusic99.headsplus.managers.PersistenceManager;
import io.github.thatsmusic99.headsplus.managers.SellableHeadsManager;
import io.github.thatsmusic99.headsplus.util.DebugFileCreator;
import io.github.thatsmusic99.headsplus.util.events.HeadsPlusException;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
@CommandInfo(
commandname = "debug",
permission = "headsplus.maincommand.debug",
maincommand = true,
usage = "/hp debug <dump|head|player|clearim|item|delete|save|transfer> <Player IGN>|<Database>",
descriptionPath = "descriptions.hp.debug"
)
@Deprecated // Also needs a cleanup
public class DebugPrint implements IHeadsPlusCommand {
private static final MessagesManager hpc = MessagesManager.get();
public static void createReport(Exception e, String name, boolean command, CommandSender sender) {
try {
Logger log = HeadsPlus.get().getLogger();
e.printStackTrace();
if (command && sender != null) {
hpc.sendMessage("commands.errors.cmd-fail", sender);
}
log.severe("HeadsPlus has failed to execute this task. An error report has been made in /plugins/HeadsPlus/debug");
String s = DebugFileCreator.createReport(new HeadsPlusException(e));
log.severe("Report name: " + s);
log.severe("Please submit this report to the developer at one of the following links:");
log.severe("https://github.com/Thatsmusic99/HeadsPlus/issues");
log.severe("https://discord.gg/nbT7wC2");
log.severe("https://www.spigotmc.org/threads/headsplus-1-8-x-1-12-x.237088/");
} catch (Exception ex) {
HeadsPlus.get().getLogger().warning("An error has occurred! We tried creating a debug report, but that didn't work... stacktraces:");
e.printStackTrace();
ex.printStackTrace();
}
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
try {
if (args.length < 2) {
hpc.sendMessage("commands.errors.invalid-args", sender);
return false;
}
String subcommand = args[1].toLowerCase();
// Subcommands are fairly brief, so there isn't necessarily any point in creating separate classes
if (sender.hasPermission("headsplus.maincommand.debug." + subcommand)) {
String report;
switch (subcommand) {
case "dump":
report = DebugFileCreator.createReport(null);
sender.sendMessage(ChatColor.GREEN + "Report name: " + report);
break;
case "player":
if (args.length > 2) {
HPPlayer pl = HPPlayer.getHPPlayer(Bukkit.getOfflinePlayer(args[2]).getUniqueId());
if (pl != null) {
report = new DebugFileCreator().createPlayerReport(pl);
sender.sendMessage(ChatColor.GREEN + "Report name: " + report);
} else {
hpc.sendMessage("commands.profile.no-data", sender);
}
} else {
hpc.sendMessage("commands.errors.invalid-args", sender);
}
break;
case "head":
if (sender instanceof Player) {
ItemStack is = ((Player) sender).getInventory().getItemInMainHand();
String s = new DebugFileCreator().createHeadReport(is);
sender.sendMessage(ChatColor.GREEN + "Report name: " + s);
}
break;
case "clearim":
InventoryManager.storedInventories.clear();
sender.sendMessage(ChatColor.GREEN + "Inventory cache cleared.");
break;
case "item":
if (sender instanceof Player) {
ItemStack item = ((Player) sender).getInventory().getItemInMainHand();
String s = new DebugFileCreator().createItemReport(item);
sender.sendMessage(ChatColor.GREEN + "Report name: " + s);
} else {
hpc.sendMessage("commands.errors.not-a-player", sender);
}
break;
case "fix":
if (sender instanceof Player) {
Player player = (Player) sender;
if (args.length > 2) {
if (SellableHeadsManager.get().isRegistered(args[2])) {
int slot = player.getInventory().getHeldItemSlot();
// lmao who needs getItemInMainHand
ItemStack item = player.getInventory().getItem(slot);
PersistenceManager.get().setSellable(item, true);
PersistenceManager.get().setSellType(item, args[2]);
double price;
double headsPrice = ConfigMobs.get().getPrice(args[2].toLowerCase().replaceAll("_", ""));
if (headsPrice != 0.0) {
price = headsPrice;
} else {
price = ConfigCrafting.get().getPrice(args[2]);
}
PersistenceManager.get().setSellPrice(item, price);
player.getInventory().setItem(slot, item);
} else {
hpc.sendMessage("commands.errors.invalid-args", sender);
}
} else {
hpc.sendMessage("commands.errors.invalid-args", sender);
}
} else {
hpc.sendMessage("commands.errors.not-a-player", sender);
}
break;
case "verbose":
DebugVerbose.fire(sender, args);
}
}
} catch (IOException | IllegalAccessException e) {
e.printStackTrace();
}
return true;
}
@Override
public boolean shouldEnable() {
return true;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) {
List<String> results = new ArrayList<>();
if (sender.hasPermission("headsplus.commands.debug")) {
if (args.length == 2) {
StringUtil.copyPartialMatches(args[1], Arrays.asList("dump", "head", "player", "clearim", "item", "delete", "save", "transfer", "fix", "verbose"), results);
} else if (args.length > 2) {
switch (args[1].toLowerCase()) {
case "fix":
StringUtil.copyPartialMatches(args[2], SellableHeadsManager.get().getKeys(), results);
break;
case "verbose":
results = DebugVerbose.onTabComplete(sender, args);
break;
default:
StringUtil.copyPartialMatches(args[2], IHeadsPlusCommand.getPlayers(sender), results);
break;
}
}
}
return results;
}
}
| Something trying to fix that other issue, just because
| src/main/java/io/github/thatsmusic99/headsplus/commands/maincommand/DebugPrint.java | Something trying to fix that other issue, just because | <ide><path>rc/main/java/io/github/thatsmusic99/headsplus/commands/maincommand/DebugPrint.java
<ide> int slot = player.getInventory().getHeldItemSlot();
<ide> // lmao who needs getItemInMainHand
<ide> ItemStack item = player.getInventory().getItem(slot);
<add> if (item == null) return false;
<add> item = item.clone();
<ide> PersistenceManager.get().setSellable(item, true);
<ide> PersistenceManager.get().setSellType(item, args[2]);
<ide> double price;
<ide> price = ConfigCrafting.get().getPrice(args[2]);
<ide> }
<ide> PersistenceManager.get().setSellPrice(item, price);
<del> player.getInventory().setItem(slot, item);
<add> final ItemStack finalItem = item;
<add> Bukkit.getScheduler().runTask(HeadsPlus.get(), () -> player.getInventory().setItem(slot, finalItem));
<ide> } else {
<ide> hpc.sendMessage("commands.errors.invalid-args", sender);
<ide> } |
|
Java | mit | 69f1c43ae6b73f70963d20069b2e8e993db68418 | 0 | CS2103JAN2017-W15-B4/main,CS2103JAN2017-W15-B4/main | package seedu.geekeep.storage;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import seedu.geekeep.commons.exceptions.IllegalValueException;
import seedu.geekeep.model.tag.Tag;
import seedu.geekeep.model.tag.UniqueTagList;
import seedu.geekeep.model.task.DateTime;
import seedu.geekeep.model.task.Location;
import seedu.geekeep.model.task.ReadOnlyTask;
import seedu.geekeep.model.task.Task;
import seedu.geekeep.model.task.Title;
/**
* JAXB-friendly version of the Task.
*/
public class XmlAdaptedTask {
@XmlElement(required = true)
private String title;
@XmlElement(required = true)
private String startDateTime;
@XmlElement(required = true)
private String endDateTime;
@XmlElement(required = true)
private String location;
@XmlElement
private List<XmlAdaptedTag> tagged = new ArrayList<>();
/**
* Constructs an XmlAdaptedTask.
* This is the no-arg constructor that is required by JAXB.
*/
public XmlAdaptedTask() {}
/**
* Converts a given Task into this class for JAXB use.
*
* @param source future changes to this will not affect the created XmlAdaptedTask
*/
public XmlAdaptedTask(ReadOnlyTask source) {
title = source.getTitle().fullTitle;
endDateTime = source.getEndDateTime() == null ? "" : source.getEndDateTime().value;
startDateTime = source.getStartDateTime() == null ? "" : source.getStartDateTime().value;
location = source.getLocation() == null ? "" : source.getLocation().value;
tagged = new ArrayList<>();
for (Tag tag : source.getTags()) {
tagged.add(new XmlAdaptedTag(tag));
}
}
/**
* Converts this jaxb-friendly adapted task object into the model's Task object.
*
* @throws IllegalValueException if there were any data constraints violated in the adapted task
*/
public Task toModelType() throws IllegalValueException {
final List<Tag> taskTags = new ArrayList<>();
for (XmlAdaptedTag tag : tagged) {
taskTags.add(tag.toModelType());
}
final Title title = new Title(this.title);
final DateTime endDateTime = this.endDateTime.isEmpty() ? null : new DateTime(this.endDateTime);
final DateTime startDateTime = this.startDateTime.isEmpty() ? null : new DateTime(this.startDateTime);
final Location location = this.location.isEmpty() ? null : new Location(this.location);
final UniqueTagList tags = new UniqueTagList(taskTags);
return new Task(title, startDateTime, endDateTime, location, tags);
}
}
| src/main/java/seedu/geekeep/storage/XmlAdaptedTask.java | package seedu.geekeep.storage;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import seedu.geekeep.commons.exceptions.IllegalValueException;
import seedu.geekeep.model.tag.Tag;
import seedu.geekeep.model.tag.UniqueTagList;
import seedu.geekeep.model.task.DateTime;
import seedu.geekeep.model.task.Location;
import seedu.geekeep.model.task.ReadOnlyTask;
import seedu.geekeep.model.task.Task;
import seedu.geekeep.model.task.Title;
/**
* JAXB-friendly version of the Task.
*/
public class XmlAdaptedTask {
@XmlElement(required = true)
private String title;
@XmlElement(required = true)
private String startDateTime;
@XmlElement(required = true)
private String endDateTime;
@XmlElement(required = true)
private String location;
@XmlElement
private List<XmlAdaptedTag> tagged = new ArrayList<>();
/**
* Constructs an XmlAdaptedTask.
* This is the no-arg constructor that is required by JAXB.
*/
public XmlAdaptedTask() {}
/**
* Converts a given Task into this class for JAXB use.
*
* @param source future changes to this will not affect the created XmlAdaptedTask
*/
public XmlAdaptedTask(ReadOnlyTask source) {
title = source.getTitle().fullTitle;
endDateTime = source.getEndDateTime().value;
startDateTime = source.getStartDateTime().value;
location = source.getLocation().value;
tagged = new ArrayList<>();
for (Tag tag : source.getTags()) {
tagged.add(new XmlAdaptedTag(tag));
}
}
/**
* Converts this jaxb-friendly adapted task object into the model's Task object.
*
* @throws IllegalValueException if there were any data constraints violated in the adapted task
*/
public Task toModelType() throws IllegalValueException {
final List<Tag> taskTags = new ArrayList<>();
for (XmlAdaptedTag tag : tagged) {
taskTags.add(tag.toModelType());
}
final Title title = new Title(this.title);
final DateTime endDateTime = new DateTime(this.endDateTime);
final DateTime startDateTime = new DateTime(this.startDateTime);
final Location location = new Location(this.location);
final UniqueTagList tags = new UniqueTagList(taskTags);
return new Task(title, startDateTime, endDateTime, location, tags);
}
}
| Support null value in field of XmlAdaptedTask
| src/main/java/seedu/geekeep/storage/XmlAdaptedTask.java | Support null value in field of XmlAdaptedTask | <ide><path>rc/main/java/seedu/geekeep/storage/XmlAdaptedTask.java
<ide> */
<ide> public XmlAdaptedTask(ReadOnlyTask source) {
<ide> title = source.getTitle().fullTitle;
<del> endDateTime = source.getEndDateTime().value;
<del> startDateTime = source.getStartDateTime().value;
<del> location = source.getLocation().value;
<add> endDateTime = source.getEndDateTime() == null ? "" : source.getEndDateTime().value;
<add> startDateTime = source.getStartDateTime() == null ? "" : source.getStartDateTime().value;
<add> location = source.getLocation() == null ? "" : source.getLocation().value;
<ide> tagged = new ArrayList<>();
<ide> for (Tag tag : source.getTags()) {
<ide> tagged.add(new XmlAdaptedTag(tag));
<ide> taskTags.add(tag.toModelType());
<ide> }
<ide> final Title title = new Title(this.title);
<del> final DateTime endDateTime = new DateTime(this.endDateTime);
<del> final DateTime startDateTime = new DateTime(this.startDateTime);
<del> final Location location = new Location(this.location);
<add> final DateTime endDateTime = this.endDateTime.isEmpty() ? null : new DateTime(this.endDateTime);
<add> final DateTime startDateTime = this.startDateTime.isEmpty() ? null : new DateTime(this.startDateTime);
<add> final Location location = this.location.isEmpty() ? null : new Location(this.location);
<ide> final UniqueTagList tags = new UniqueTagList(taskTags);
<ide> return new Task(title, startDateTime, endDateTime, location, tags);
<ide> } |
|
Java | bsd-3-clause | f16887f6c2f77fefeee66bc1757ac81c581a3bee | 0 | pgesek/motech,pgesek/motech,pgesek/motech,pgesek/motech | package org.motechproject.tasks.service.impl;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.motechproject.commons.api.DataProvider;
import org.motechproject.commons.api.TasksEventParser;
import org.motechproject.event.MotechEvent;
import org.motechproject.event.listener.EventListener;
import org.motechproject.event.listener.EventListenerRegistryService;
import org.motechproject.event.listener.annotations.MotechListenerEventProxy;
import org.motechproject.tasks.constants.EventDataKeys;
import org.motechproject.tasks.domain.mds.task.FilterSet;
import org.motechproject.tasks.domain.mds.task.Task;
import org.motechproject.tasks.domain.mds.task.TaskActivity;
import org.motechproject.tasks.exception.TaskHandlerException;
import org.motechproject.tasks.service.TaskActivityService;
import org.motechproject.tasks.service.TaskService;
import org.motechproject.tasks.service.TriggerHandler;
import org.motechproject.tasks.service.util.TaskContext;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ReflectionUtils;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.motechproject.tasks.constants.EventDataKeys.TASK_ID;
import static org.motechproject.tasks.constants.TaskFailureCause.TRIGGER;
import static org.motechproject.tasks.service.util.HandlerPredicates.withServiceName;
/**
* The <code>TaskTriggerHandler</code> receives events and executes tasks for which the trigger
* event subject is the same as the received event subject.
*/
@Service("taskTriggerHandler")
public class TaskTriggerHandler implements TriggerHandler {
private static final String BEAN_NAME = "taskTriggerHandler";
private static final Logger LOGGER = LoggerFactory.getLogger(TaskTriggerHandler.class);
@Autowired
private TaskService taskService;
@Autowired
private TaskActivityService activityService;
@Autowired
private EventListenerRegistryService registryService;
@Autowired
private TaskActionExecutor executor;
@Autowired
private TasksPostExecutionHandler postExecutionHandler;
private Map<String, DataProvider> dataProviders;
private Set<Long> handledTasksId = new HashSet<>();
@PostConstruct
public void init() {
for (Task task : taskService.getAllTasks()) {
registerHandlerFor(task.getTrigger().getEffectiveListenerSubject());
if (task.isRetryTaskOnFailure()) {
registerHandlerFor(task.getTrigger().getEffectiveListenerRetrySubject(), true);
}
}
}
@PreDestroy
public void preDestroy() {
registryService.clearListenersForBean(BEAN_NAME);
}
@Override
public void registerHandlerFor(String subject) {
registerHandlerFor(subject, false);
}
@Override
public void registerHandlerFor(String subject, boolean isRetryHandler) {
LOGGER.info("Registering handler for {}", subject);
String methodName = isRetryHandler ? "handleRetry" : "handle";
Method method = ReflectionUtils.findMethod(this.getClass(), methodName, MotechEvent.class);
Object obj = CollectionUtils.find(
registryService.getListeners(subject), withServiceName(BEAN_NAME)
);
try {
if (method != null && obj == null) {
EventListener proxy = new MotechListenerEventProxy(BEAN_NAME, this, method);
registryService.registerListener(proxy, subject);
LOGGER.info(String.format("%s listens on subject %s", BEAN_NAME, subject));
}
} catch (RuntimeException exp) {
LOGGER.error(
String.format("%s can not listen on subject %s due to:", BEAN_NAME, subject),
exp
);
}
}
@Override
@Transactional
public void handle(MotechEvent event) {
LOGGER.info("Handling the motech event with subject: {}", event.getSubject());
// Look for custom event parser
Map<String, Object> eventParams = event.getParameters();
eventParams.putAll(event.getMetadata());
TasksEventParser parser = null;
if (eventParams != null) {
parser = taskService.findCustomParser((String) eventParams.get(TasksEventParser.CUSTOM_PARSER_EVENT_KEY));
}
// Use custom event parser, if it exists, to modify event
String triggerSubject = parser == null ? event.getSubject() : parser.parseEventSubject(event.getSubject(), eventParams);
Map<String, Object> parameters = parser == null ? eventParams : parser.parseEventParameters(event.getSubject(), eventParams);
List<Task> tasks = taskService.findActiveTasksForTriggerSubject(triggerSubject);
// Handle all tasks one by one
for (Task task : tasks) {
checkAndHandleTask(task, parameters);
}
}
@Override
@Transactional
public void handleRetry(MotechEvent event) {
LOGGER.info("Handling the motech event with subject: {} for task retry", event.getSubject());
Map<String, Object> eventParams = event.getParameters();
Map<String, Object> eventMetadata = event.getMetadata();
Task task = taskService.getTask((Long) eventMetadata.get(TASK_ID));
if(task != null && task.isEnabled()) {
checkAndHandleTask(task, eventParams);
}
}
@Override
@Transactional
public void retryTask(Long activityId) {
TaskActivity activity = activityService.getTaskActivityById(activityId);
handleTask(taskService.getTask(activity.getTask()), activity.getParameters());
}
private void handleTask(Task task, Map<String, Object> parameters) {
long activityId = activityService.addTaskStarted(task, parameters);
Map<String, Object> metadata = prepareTaskMetadata(task.getId(), activityId);
TaskContext taskContext = new TaskContext(task, parameters, metadata, activityService);
TaskInitializer initializer = new TaskInitializer(taskContext);
List<FilterSet> filterSetList = new ArrayList<>(task.getTaskConfig().getFilters());
boolean actionFilterResult = true;
int executedAndFilteredActions = 0;
int stepIndex = 0;
int actualFilterIndex = initializer.getActionFilters();
try {
LOGGER.info("Executing all actions from task: {}", task.getName());
if (initializer.evalConfigSteps(dataProviders)) {
while (executedAndFilteredActions< task.getActions().size()) {
if (isActionFilter(filterSetList, actualFilterIndex, stepIndex)) {
actionFilterResult = initializer.checkActionFilter(actualFilterIndex, filterSetList);
actualFilterIndex++;
stepIndex++;
}
if (actionFilterResult) {
executor.execute(task, task.getActions().get(executedAndFilteredActions), executedAndFilteredActions, taskContext, activityId);
executedAndFilteredActions++;
} else {
activityService.addFilteredExecution(activityId);
executedAndFilteredActions++;
}
stepIndex++;
actionFilterResult = true;
}
} else {
activityService.addTaskFiltered(activityId);
LOGGER.warn("Actions from task: {} weren't executed, because config steps didn't pass the evaluation", task.getName());
}
} catch (TaskHandlerException e) {
postExecutionHandler.handleError(parameters, metadata, task, e, activityId);
} catch (RuntimeException e) {
postExecutionHandler.handleError(parameters, metadata, task, new TaskHandlerException(TRIGGER, "task.error.unrecognizedError", e), activityId);
}
}
/**
* Checks if the given task is still running. If not the task will be handled.
*
* @param task the given task.
* @param eventParameters parameters from the given event
*/
private synchronized void checkAndHandleTask(Task task, Map<String, Object> eventParameters) {
if (!this.handledTasksId.contains(task.getId())) {
this.handledTasksId.add(task.getId());
handleTask(task, eventParameters);
this.handledTasksId.remove(task.getId());
} else {
LOGGER.warn("The task {} didn't execute, because the previous invocation is still running.", task.getName());
}
}
@Override
public void addDataProvider(DataProvider provider) {
if (dataProviders == null) {
dataProviders = new HashMap<>();
}
dataProviders.put(provider.getName(), provider);
}
@Override
public void removeDataProvider(String taskDataProviderId) {
if (MapUtils.isNotEmpty(dataProviders)) {
dataProviders.remove(taskDataProviderId);
}
}
private boolean isActionFilter(List<FilterSet> filterSetList, int index, int step) {
return index < filterSetList.size() && filterSetList.get(index).getActionFilterOrder() == step;
}
void setDataProviders(Map<String, DataProvider> dataProviders) {
this.dataProviders = dataProviders;
}
void setHandledTasksId(Set<Long> handledTasksId) {
this.handledTasksId = handledTasksId;
}
private Map<String, Object> prepareTaskMetadata(Long taskId, long activityId) {
Map<String, Object> metadata = new HashMap<>();
metadata.put(EventDataKeys.TASK_ID, taskId);
metadata.put(EventDataKeys.TASK_ACTIVITY_ID, activityId);
return metadata;
}
@Autowired
public void setBundleContext(BundleContext bundleContext) {
this.executor.setBundleContext(bundleContext);
}
}
| modules/tasks/tasks/src/main/java/org/motechproject/tasks/service/impl/TaskTriggerHandler.java | package org.motechproject.tasks.service.impl;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.motechproject.commons.api.DataProvider;
import org.motechproject.commons.api.TasksEventParser;
import org.motechproject.event.MotechEvent;
import org.motechproject.event.listener.EventListener;
import org.motechproject.event.listener.EventListenerRegistryService;
import org.motechproject.event.listener.annotations.MotechListenerEventProxy;
import org.motechproject.tasks.constants.EventDataKeys;
import org.motechproject.tasks.domain.mds.task.FilterSet;
import org.motechproject.tasks.domain.mds.task.Task;
import org.motechproject.tasks.domain.mds.task.TaskActivity;
import org.motechproject.tasks.exception.TaskHandlerException;
import org.motechproject.tasks.service.TaskActivityService;
import org.motechproject.tasks.service.TaskService;
import org.motechproject.tasks.service.TriggerHandler;
import org.motechproject.tasks.service.util.TaskContext;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ReflectionUtils;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.motechproject.tasks.constants.EventDataKeys.TASK_ID;
import static org.motechproject.tasks.constants.TaskFailureCause.TRIGGER;
import static org.motechproject.tasks.service.util.HandlerPredicates.withServiceName;
/**
* The <code>TaskTriggerHandler</code> receives events and executes tasks for which the trigger
* event subject is the same as the received event subject.
*/
@Service("taskTriggerHandler")
public class TaskTriggerHandler implements TriggerHandler {
private static final String BEAN_NAME = "taskTriggerHandler";
private static final Logger LOGGER = LoggerFactory.getLogger(TaskTriggerHandler.class);
@Autowired
private TaskService taskService;
@Autowired
private TaskActivityService activityService;
@Autowired
private EventListenerRegistryService registryService;
@Autowired
private TaskActionExecutor executor;
@Autowired
private TasksPostExecutionHandler postExecutionHandler;
private Map<String, DataProvider> dataProviders;
private Set<Long> handledTasksId = new HashSet<>();
@PostConstruct
public void init() {
for (Task task : taskService.getAllTasks()) {
registerHandlerFor(task.getTrigger().getEffectiveListenerSubject());
if (task.isRetryTaskOnFailure()) {
registerHandlerFor(task.getTrigger().getEffectiveListenerRetrySubject(), true);
}
}
}
@PreDestroy
public void preDestroy() {
registryService.clearListenersForBean(BEAN_NAME);
}
@Override
public void registerHandlerFor(String subject) {
registerHandlerFor(subject, false);
}
@Override
public void registerHandlerFor(String subject, boolean isRetryHandler) {
LOGGER.info("Registering handler for {}", subject);
String methodName = isRetryHandler ? "handleRetry" : "handle";
Method method = ReflectionUtils.findMethod(this.getClass(), methodName, MotechEvent.class);
Object obj = CollectionUtils.find(
registryService.getListeners(subject), withServiceName(BEAN_NAME)
);
try {
if (method != null && obj == null) {
EventListener proxy = new MotechListenerEventProxy(BEAN_NAME, this, method);
registryService.registerListener(proxy, subject);
LOGGER.info(String.format("%s listens on subject %s", BEAN_NAME, subject));
}
} catch (RuntimeException exp) {
LOGGER.error(
String.format("%s can not listen on subject %s due to:", BEAN_NAME, subject),
exp
);
}
}
@Override
@Transactional
public void handle(MotechEvent event) {
LOGGER.info("Handling the motech event with subject: {}", event.getSubject());
// Look for custom event parser
Map<String, Object> eventParams = event.getParameters();
eventParams.putAll(event.getMetadata());
TasksEventParser parser = null;
if (eventParams != null) {
parser = taskService.findCustomParser((String) eventParams.get(TasksEventParser.CUSTOM_PARSER_EVENT_KEY));
}
// Use custom event parser, if it exists, to modify event
String triggerSubject = parser == null ? event.getSubject() : parser.parseEventSubject(event.getSubject(), eventParams);
Map<String, Object> parameters = parser == null ? eventParams : parser.parseEventParameters(event.getSubject(), eventParams);
List<Task> tasks = taskService.findActiveTasksForTriggerSubject(triggerSubject);
// Handle all tasks one by one
for (Task task : tasks) {
checkAndHandleTask(task, parameters);
}
}
@Override
@Transactional
public void handleRetry(MotechEvent event) {
LOGGER.info("Handling the motech event with subject: {} for task retry", event.getSubject());
Map<String, Object> eventParams = event.getParameters();
Map<String, Object> eventMetadata = event.getMetadata();
Task task = taskService.getTask((Long) eventMetadata.get(TASK_ID));
if(task != null && task.isEnabled()) {
checkAndHandleTask(task, eventParams);
}
}
@Override
@Transactional
public void retryTask(Long activityId) {
TaskActivity activity = activityService.getTaskActivityById(activityId);
handleTask(taskService.getTask(activity.getTask()), activity.getParameters());
}
private void handleTask(Task task, Map<String, Object> parameters) {
long activityId = activityService.addTaskStarted(task, parameters);
Map<String, Object> metadata = prepareTaskMetadata(task.getId(), activityId);
TaskContext taskContext = new TaskContext(task, parameters, metadata, activityService);
TaskInitializer initializer = new TaskInitializer(taskContext);
List<FilterSet> filterSetList = new ArrayList<>(task.getTaskConfig().getFilters());
boolean actionFilterResult = true;
int executedAndFilteredActions = 0;
int stepIndex = 0;
int actualFilterIndex = initializer.getActionFilters();
try {
LOGGER.info("Executing all actions from task: {}", task.getName());
if (initializer.evalConfigSteps(dataProviders)) {
while (executedAndFilteredActions< task.getActions().size()) {
if (isActionFilter(filterSetList, actualFilterIndex, stepIndex)) {
actionFilterResult = initializer.checkActionFilter(actualFilterIndex, filterSetList);
actualFilterIndex++;
stepIndex++;
}
if (actionFilterResult) {
executor.execute(task, task.getActions().get(executedAndFilteredActions), executedAndFilteredActions, taskContext, activityId);
executedAndFilteredActions++;
} else {
activityService.addFilteredExecution(activityId);
executedAndFilteredActions++;
}
stepIndex++;
actionFilterResult = true;
}
} else {
activityService.addTaskFiltered(activityId);
LOGGER.warn("Actions from task: {} weren't executed, because config steps didn't pass the evaluation", task.getName());
}
} catch (TaskHandlerException e) {
postExecutionHandler.handleError(parameters, metadata, task, e, activityId);
} catch (RuntimeException e) {
postExecutionHandler.handleError(parameters, metadata, task, new TaskHandlerException(TRIGGER, "task.error.unrecognizedError", e), activityId);
}
}
/**
* Checks if the given task is still running. If not the task will be handled.
*
* @param task the given task.
* @param eventParameters parameters from the given event
*/
private void checkAndHandleTask(Task task, Map<String, Object> eventParameters) {
if (!isTaskHandled(task)) {
addTaskHandled(task);
handleTask(task, eventParameters);
removeTaskHandled(task);
} else {
LOGGER.warn("The task {} didn't execute, because the previous invocation is still running.", task.getName());
}
}
@Override
public void addDataProvider(DataProvider provider) {
if (dataProviders == null) {
dataProviders = new HashMap<>();
}
dataProviders.put(provider.getName(), provider);
}
@Override
public void removeDataProvider(String taskDataProviderId) {
if (MapUtils.isNotEmpty(dataProviders)) {
dataProviders.remove(taskDataProviderId);
}
}
private boolean isActionFilter(List<FilterSet> filterSetList, int index, int step) {
return index < filterSetList.size() && filterSetList.get(index).getActionFilterOrder() == step;
}
void setDataProviders(Map<String, DataProvider> dataProviders) {
this.dataProviders = dataProviders;
}
void setHandledTasksId(Set<Long> handledTasksId) {
this.handledTasksId = handledTasksId;
}
private Map<String, Object> prepareTaskMetadata(Long taskId, long activityId) {
Map<String, Object> metadata = new HashMap<>();
metadata.put(EventDataKeys.TASK_ID, taskId);
metadata.put(EventDataKeys.TASK_ACTIVITY_ID, activityId);
return metadata;
}
private void addTaskHandled(Task task) {
this.handledTasksId.add(task.getId());
}
private void removeTaskHandled(Task task) {
this.handledTasksId.remove(task.getId());
}
private boolean isTaskHandled(Task task) {
return this.handledTasksId.contains(task.getId()) ? true : false;
}
@Autowired
public void setBundleContext(BundleContext bundleContext) {
this.executor.setBundleContext(bundleContext);
}
}
| MOTECH-3138: Fixed multiple handling one task.
| modules/tasks/tasks/src/main/java/org/motechproject/tasks/service/impl/TaskTriggerHandler.java | MOTECH-3138: Fixed multiple handling one task. | <ide><path>odules/tasks/tasks/src/main/java/org/motechproject/tasks/service/impl/TaskTriggerHandler.java
<ide> * @param task the given task.
<ide> * @param eventParameters parameters from the given event
<ide> */
<del> private void checkAndHandleTask(Task task, Map<String, Object> eventParameters) {
<del> if (!isTaskHandled(task)) {
<del> addTaskHandled(task);
<add> private synchronized void checkAndHandleTask(Task task, Map<String, Object> eventParameters) {
<add> if (!this.handledTasksId.contains(task.getId())) {
<add> this.handledTasksId.add(task.getId());
<ide>
<ide> handleTask(task, eventParameters);
<ide>
<del> removeTaskHandled(task);
<add> this.handledTasksId.remove(task.getId());
<ide> } else {
<ide> LOGGER.warn("The task {} didn't execute, because the previous invocation is still running.", task.getName());
<ide> }
<ide> return metadata;
<ide> }
<ide>
<del> private void addTaskHandled(Task task) {
<del> this.handledTasksId.add(task.getId());
<del> }
<del>
<del> private void removeTaskHandled(Task task) {
<del> this.handledTasksId.remove(task.getId());
<del> }
<del>
<del> private boolean isTaskHandled(Task task) {
<del> return this.handledTasksId.contains(task.getId()) ? true : false;
<del> }
<del>
<ide> @Autowired
<ide> public void setBundleContext(BundleContext bundleContext) {
<ide> this.executor.setBundleContext(bundleContext); |
|
Java | apache-2.0 | 13ebf1eee3fa27f8e0cc47729cd60fca3bbd05c6 | 0 | passion1014/metaworks_framework,cengizhanozcan/BroadleafCommerce,trombka/blc-tmp,caosg/BroadleafCommerce,liqianggao/BroadleafCommerce,caosg/BroadleafCommerce,zhaorui1/BroadleafCommerce,cloudbearings/BroadleafCommerce,shopizer/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,wenmangbo/BroadleafCommerce,rawbenny/BroadleafCommerce,sanlingdd/broadleaf,lgscofield/BroadleafCommerce,cloudbearings/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,rawbenny/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,macielbombonato/BroadleafCommerce,sitexa/BroadleafCommerce,caosg/BroadleafCommerce,bijukunjummen/BroadleafCommerce,cogitoboy/BroadleafCommerce,sitexa/BroadleafCommerce,daniellavoie/BroadleafCommerce,ljshj/BroadleafCommerce,liqianggao/BroadleafCommerce,cloudbearings/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,liqianggao/BroadleafCommerce,sitexa/BroadleafCommerce,bijukunjummen/BroadleafCommerce,ljshj/BroadleafCommerce,TouK/BroadleafCommerce,shopizer/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,TouK/BroadleafCommerce,shopizer/BroadleafCommerce,passion1014/metaworks_framework,udayinfy/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,cogitoboy/BroadleafCommerce,lgscofield/BroadleafCommerce,macielbombonato/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,gengzhengtao/BroadleafCommerce,alextiannus/BroadleafCommerce,udayinfy/BroadleafCommerce,wenmangbo/BroadleafCommerce,macielbombonato/BroadleafCommerce,zhaorui1/BroadleafCommerce,wenmangbo/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,sanlingdd/broadleaf,alextiannus/BroadleafCommerce,zhaorui1/BroadleafCommerce,trombka/blc-tmp,daniellavoie/BroadleafCommerce,passion1014/metaworks_framework,alextiannus/BroadleafCommerce,cogitoboy/BroadleafCommerce,gengzhengtao/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,daniellavoie/BroadleafCommerce,bijukunjummen/BroadleafCommerce,ljshj/BroadleafCommerce,trombka/blc-tmp,gengzhengtao/BroadleafCommerce,rawbenny/BroadleafCommerce,udayinfy/BroadleafCommerce,lgscofield/BroadleafCommerce,TouK/BroadleafCommerce | /*
* #%L
* BroadleafCommerce Common Libraries
* %%
* Copyright (C) 2009 - 2013 Broadleaf Commerce
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.broadleafcommerce.common.util;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Convenience methods for interacting with collections.
*
* @author Andre Azzolini (apazzolini)
*/
public class BLCCollectionUtils {
/**
* Delegates to {@link CollectionUtils#collect(Collection, Transformer)}, but performs the necessary type coercion
* to allow the returned collection to be correctly casted based on the TypedTransformer.
*
* @param inputCollection
* @param transformer
* @return the typed, collected Collection
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> Collection<T> collect(Collection inputCollection, TypedTransformer<T> transformer) {
return CollectionUtils.collect(inputCollection, transformer);
}
/**
* The same as {@link #collect(Collection, TypedTransformer)} but returns an ArrayList
* @param inputCollection
* @param transformer
* @return
*/
@SuppressWarnings("rawtypes")
public static <T> List<T> collectList(Collection inputCollection, TypedTransformer<T> transformer) {
List<T> returnList = new ArrayList<T>();
for (Object obj : inputCollection) {
T transformed = transformer.transform(obj);
returnList.add(transformed);
}
return returnList;
}
/**
* The same as {@link #collect(Collection, TypedTransformer)} but returns an array
* @param inputCollection
* @param transformer
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T[] collectArray(Collection inputCollection, TypedTransformer<T> transformer) {
T[] returnArray = (T[]) new Object[inputCollection.size()];
int i = 0;
for (Object obj : inputCollection) {
T transformed = transformer.transform(obj);
returnArray[i++] = transformed;
}
return returnArray;
}
/**
* Delegates to {@link CollectionUtils#select(Collection, org.apache.commons.collections.Predicate)}, but will
* force the return type to be a List<T>.
*
* @param inputCollection
* @param predicate
* @return
*/
public static <T> List<T> selectList(Collection<T> inputCollection, TypedPredicate<T> predicate) {
ArrayList<T> answer = new ArrayList<T>(inputCollection.size());
CollectionUtils.select(inputCollection, predicate, answer);
return answer;
}
}
| common/src/main/java/org/broadleafcommerce/common/util/BLCCollectionUtils.java | /*
* #%L
* BroadleafCommerce Common Libraries
* %%
* Copyright (C) 2009 - 2013 Broadleaf Commerce
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.broadleafcommerce.common.util;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Convenience methods for interacting with collections.
*
* @author Andre Azzolini (apazzolini)
*/
public class BLCCollectionUtils {
/**
* Delegates to {@link CollectionUtils#collect(Collection, Transformer)}, but performs the necessary type coercion
* to allow the returned collection to be correctly casted based on the TypedTransformer.
*
* @param inputCollection
* @param transformer
* @return the typed, collected Collection
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> Collection<T> collect(Collection inputCollection, TypedTransformer<T> transformer) {
return CollectionUtils.collect(inputCollection, transformer);
}
@SuppressWarnings("rawtypes")
public static <T> List<T> collectList(Collection inputCollection, TypedTransformer<T> transformer) {
List<T> returnList = new ArrayList<T>();
for (Object obj : inputCollection) {
T transformed = transformer.transform(obj);
returnList.add(transformed);
}
return returnList;
}
/**
* Delegates to {@link CollectionUtils#select(Collection, org.apache.commons.collections.Predicate)}, but will
* force the return type to be a List<T>.
*
* @param inputCollection
* @param predicate
* @return
*/
public static <T> List<T> selectList(Collection<T> inputCollection, TypedPredicate<T> predicate) {
ArrayList<T> answer = new ArrayList<T>(inputCollection.size());
CollectionUtils.select(inputCollection, predicate, answer);
return answer;
}
}
| Add collectArray method
| common/src/main/java/org/broadleafcommerce/common/util/BLCCollectionUtils.java | Add collectArray method | <ide><path>ommon/src/main/java/org/broadleafcommerce/common/util/BLCCollectionUtils.java
<ide> return CollectionUtils.collect(inputCollection, transformer);
<ide> }
<ide>
<add> /**
<add> * The same as {@link #collect(Collection, TypedTransformer)} but returns an ArrayList
<add> * @param inputCollection
<add> * @param transformer
<add> * @return
<add> */
<ide> @SuppressWarnings("rawtypes")
<ide> public static <T> List<T> collectList(Collection inputCollection, TypedTransformer<T> transformer) {
<ide> List<T> returnList = new ArrayList<T>();
<ide> returnList.add(transformed);
<ide> }
<ide> return returnList;
<add> }
<add>
<add> /**
<add> * The same as {@link #collect(Collection, TypedTransformer)} but returns an array
<add> * @param inputCollection
<add> * @param transformer
<add> * @return
<add> */
<add> @SuppressWarnings({ "rawtypes", "unchecked" })
<add> public static <T> T[] collectArray(Collection inputCollection, TypedTransformer<T> transformer) {
<add> T[] returnArray = (T[]) new Object[inputCollection.size()];
<add> int i = 0;
<add> for (Object obj : inputCollection) {
<add> T transformed = transformer.transform(obj);
<add> returnArray[i++] = transformed;
<add> }
<add> return returnArray;
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | e1d36c75cba9411753a18c5705683890ca423ca9 | 0 | idea4bsd/idea4bsd,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,slisson/intellij-community,da1z/intellij-community,robovm/robovm-studio,allotria/intellij-community,kdwink/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,signed/intellij-community,caot/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,kool79/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,caot/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,asedunov/intellij-community,caot/intellij-community,ibinti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,caot/intellij-community,blademainer/intellij-community,semonte/intellij-community,semonte/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,allotria/intellij-community,jagguli/intellij-community,hurricup/intellij-community,jagguli/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,vladmm/intellij-community,allotria/intellij-community,ibinti/intellij-community,dslomov/intellij-community,caot/intellij-community,slisson/intellij-community,vvv1559/intellij-community,caot/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,signed/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,slisson/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,samthor/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,holmes/intellij-community,gnuhub/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,supersven/intellij-community,adedayo/intellij-community,blademainer/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,retomerz/intellij-community,FHannes/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,signed/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,ryano144/intellij-community,samthor/intellij-community,semonte/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,vladmm/intellij-community,ryano144/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,kool79/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,caot/intellij-community,kdwink/intellij-community,slisson/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,suncycheng/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,apixandru/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,kdwink/intellij-community,diorcety/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,FHannes/intellij-community,holmes/intellij-community,slisson/intellij-community,kool79/intellij-community,apixandru/intellij-community,hurricup/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,FHannes/intellij-community,asedunov/intellij-community,supersven/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,signed/intellij-community,supersven/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,semonte/intellij-community,da1z/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,allotria/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,signed/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,adedayo/intellij-community,slisson/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,xfournet/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,izonder/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,dslomov/intellij-community,fitermay/intellij-community,allotria/intellij-community,ahb0327/intellij-community,semonte/intellij-community,ibinti/intellij-community,jagguli/intellij-community,petteyg/intellij-community,clumsy/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,asedunov/intellij-community,adedayo/intellij-community,robovm/robovm-studio,caot/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,signed/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,izonder/intellij-community,allotria/intellij-community,retomerz/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,holmes/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,blademainer/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,akosyakov/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,diorcety/intellij-community,robovm/robovm-studio,holmes/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,samthor/intellij-community,da1z/intellij-community,izonder/intellij-community,signed/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,da1z/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,caot/intellij-community,kool79/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,kdwink/intellij-community,diorcety/intellij-community,xfournet/intellij-community,adedayo/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,semonte/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,petteyg/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,supersven/intellij-community,supersven/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,samthor/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,clumsy/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,xfournet/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,clumsy/intellij-community,hurricup/intellij-community,izonder/intellij-community,vladmm/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,supersven/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,fnouama/intellij-community,allotria/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,asedunov/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,blademainer/intellij-community,asedunov/intellij-community,vladmm/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,retomerz/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,xfournet/intellij-community,caot/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,slisson/intellij-community,signed/intellij-community,slisson/intellij-community,FHannes/intellij-community,fnouama/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,dslomov/intellij-community,kool79/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,asedunov/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,da1z/intellij-community,suncycheng/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,slisson/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,semonte/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,caot/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,izonder/intellij-community,fnouama/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,gnuhub/intellij-community,semonte/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,allotria/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,supersven/intellij-community,fnouama/intellij-community,robovm/robovm-studio,supersven/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,clumsy/intellij-community,amith01994/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,signed/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,hurricup/intellij-community,kdwink/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,signed/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,adedayo/intellij-community,caot/intellij-community,jagguli/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,izonder/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,kdwink/intellij-community,FHannes/intellij-community,diorcety/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,da1z/intellij-community,da1z/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,vladmm/intellij-community,signed/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,FHannes/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,diorcety/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,holmes/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.find.impl;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.intellij.find.FindBundle;
import com.intellij.find.FindModel;
import com.intellij.find.ngrams.TrigramIndex;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectCoreUtil;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.text.TrigramBuilder;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileFilter;
import com.intellij.psi.*;
import com.intellij.psi.impl.cache.CacheManager;
import com.intellij.psi.impl.cache.impl.id.IdIndex;
import com.intellij.psi.impl.search.PsiSearchHelperImpl;
import com.intellij.psi.search.*;
import com.intellij.usageView.UsageInfo;
import com.intellij.usages.FindUsagesProcessPresentation;
import com.intellij.usages.UsageLimitUtil;
import com.intellij.usages.impl.UsageViewManagerImpl;
import com.intellij.util.CommonProcessors;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.FileBasedIndex;
import com.intellij.util.indexing.FileBasedIndexImpl;
import gnu.trove.TIntHashSet;
import gnu.trove.TIntIterator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.regex.Pattern;
/**
* @author peter
*/
class FindInProjectTask {
private static final Logger LOG = Logger.getInstance("#com.intellij.find.impl.FindInProjectTask");
private static final int FILES_SIZE_LIMIT = 70 * 1024 * 1024; // megabytes.
private static final int SINGLE_FILE_SIZE_LIMIT = 5 * 1024 * 1024; // megabytes.
private final FindModel myFindModel;
private final Project myProject;
private final PsiManager myPsiManager;
@Nullable private final PsiDirectory myPsiDirectory;
private final FileIndex myFileIndex;
private final Condition<VirtualFile> myFileMask;
private final ProgressIndicator myProgress;
@Nullable private final Module myModule;
private final Set<PsiFile> myLargeFiles = ContainerUtil.newTroveSet();
private boolean myWarningShown;
FindInProjectTask(@NotNull final FindModel findModel,
@NotNull final Project project,
@Nullable final PsiDirectory psiDirectory) {
myFindModel = findModel;
myProject = project;
myPsiDirectory = psiDirectory;
myPsiManager = PsiManager.getInstance(project);
final String moduleName = findModel.getModuleName();
myModule = moduleName == null ? null : ApplicationManager.getApplication().runReadAction(new Computable<Module>() {
@Override
public Module compute() {
return ModuleManager.getInstance(project).findModuleByName(moduleName);
}
});
myFileIndex = myModule == null ?
ProjectRootManager.getInstance(project).getFileIndex() :
ModuleRootManager.getInstance(myModule).getFileIndex();
final String filter = findModel.getFileFilter();
final Pattern pattern = FindInProjectUtil.createFileMaskRegExp(filter);
//noinspection unchecked
myFileMask = pattern == null ? Condition.TRUE : new Condition<VirtualFile>() {
@Override
public boolean value(VirtualFile file) {
return file != null && pattern.matcher(file.getName()).matches();
}
};
final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
myProgress = progress != null ? progress : new EmptyProgressIndicator();
}
public void findUsages(@NotNull final Processor<UsageInfo> consumer, @NotNull FindUsagesProcessPresentation processPresentation) {
try {
myProgress.setIndeterminate(true);
myProgress.setText("Scanning indexed files...");
final Set<PsiFile> filesForFastWordSearch = getFilesForFastWordSearch();
myProgress.setIndeterminate(false);
searchInFiles(consumer, processPresentation, filesForFastWordSearch);
myProgress.setIndeterminate(true);
myProgress.setText("Scanning non-indexed files...");
boolean skipIndexed = canRelyOnIndices();
final Collection<PsiFile> otherFiles = collectFilesInScope(filesForFastWordSearch, skipIndexed);
myProgress.setIndeterminate(false);
long start = System.currentTimeMillis();
searchInFiles(consumer, processPresentation, otherFiles);
if (skipIndexed && otherFiles.size() > 1000) {
logStats(otherFiles, start);
}
}
catch (ProcessCanceledException e) {
// fine
}
if (!myLargeFiles.isEmpty()) {
processPresentation.setLargeFilesWereNotScanned(myLargeFiles);
}
if (!myProgress.isCanceled()) {
myProgress.setText(FindBundle.message("find.progress.search.completed"));
}
}
private static void logStats(Collection<PsiFile> otherFiles, long start) {
long time = System.currentTimeMillis() - start;
final Multiset<String> stats = HashMultiset.create();
for (PsiFile file : otherFiles) {
stats.add(StringUtil.notNullize(file.getViewProvider().getVirtualFile().getExtension()).toLowerCase());
}
List<String> extensions = ContainerUtil.newArrayList(stats.elementSet());
Collections.sort(extensions, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return stats.count(o2) - stats.count(o1);
}
});
String message = "Search in " + otherFiles.size() + " files with unknown types took " + time + "ms.\n" +
"Mapping their extensions to an existing file type (e.g. Plain Text) might speed up the search.\n" +
"Most frequent non-indexed file extensions: ";
for (int i = 0; i < Math.min(10, extensions.size()); i++) {
String extension = extensions.get(i);
message += extension + "(" + stats.count(extension) + ") ";
}
LOG.info(message);
}
private void searchInFiles(Processor<UsageInfo> consumer, FindUsagesProcessPresentation processPresentation, Collection<PsiFile> psiFiles) {
int i = 0;
long totalFilesSize = 0;
int count = 0;
for (final PsiFile psiFile : psiFiles) {
final VirtualFile virtualFile = psiFile.getVirtualFile();
final int index = i++;
if (virtualFile == null) continue;
long fileLength = UsageViewManagerImpl.getFileLength(virtualFile);
if (fileLength == -1) continue; // Binary or invalid
if (ProjectCoreUtil.isProjectOrWorkspaceFile(virtualFile) && !Registry.is("find.search.in.project.files")) continue;
if (fileLength > SINGLE_FILE_SIZE_LIMIT) {
myLargeFiles.add(psiFile);
continue;
}
myProgress.checkCanceled();
myProgress.setFraction((double)index / psiFiles.size());
String text = FindBundle.message("find.searching.for.string.in.file.progress",
myFindModel.getStringToFind(), virtualFile.getPresentableUrl());
myProgress.setText(text);
myProgress.setText2(FindBundle.message("find.searching.for.string.in.file.occurrences.progress", count));
int countInFile = FindInProjectUtil.processUsagesInFile(psiFile, myFindModel, consumer);
count += countInFile;
if (countInFile > 0) {
totalFilesSize += fileLength;
if (totalFilesSize > FILES_SIZE_LIMIT && !myWarningShown) {
myWarningShown = true;
String message = FindBundle.message("find.excessive.total.size.prompt",
UsageViewManagerImpl.presentableSize(totalFilesSize),
ApplicationNamesInfo.getInstance().getProductName());
UsageLimitUtil.showAndCancelIfAborted(myProject, message, processPresentation.getUsageViewPresentation());
}
}
}
}
@NotNull
private Collection<PsiFile> collectFilesInScope(@NotNull final Set<PsiFile> alreadySearched, final boolean skipIndexed) {
SearchScope customScope = myFindModel.getCustomScope();
final GlobalSearchScope globalCustomScope = toGlobal(customScope);
class EnumContentIterator implements ContentIterator {
final Set<PsiFile> myFiles = new LinkedHashSet<PsiFile>();
@Override
public boolean processFile(@NotNull final VirtualFile virtualFile) {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
ProgressManager.checkCanceled();
if (virtualFile.isDirectory() || !virtualFile.isValid() ||
!myFileMask.value(virtualFile) ||
(globalCustomScope != null && !globalCustomScope.contains(virtualFile))) {
return;
}
if (skipIndexed && isCoveredByIdIndex(virtualFile)) {
return;
}
PsiFile psiFile = myPsiManager.findFile(virtualFile);
if (psiFile != null && !(psiFile instanceof PsiBinaryFile) && !alreadySearched.contains(psiFile)) {
PsiFile sourceFile = (PsiFile)psiFile.getNavigationElement();
if (sourceFile != null) psiFile = sourceFile;
myFiles.add(psiFile);
}
}
});
return true;
}
@NotNull
private Collection<PsiFile> getFiles() {
return myFiles;
}
}
EnumContentIterator iterator = new EnumContentIterator();
if (customScope instanceof LocalSearchScope) {
for (VirtualFile file : getLocalScopeFiles((LocalSearchScope)customScope)) {
iterator.processFile(file);
}
}
else if (myPsiDirectory != null) {
myFileIndex.iterateContentUnderDirectory(myPsiDirectory.getVirtualFile(), iterator);
}
else {
boolean success = myFileIndex.iterateContent(iterator);
if (success && globalCustomScope != null && globalCustomScope.isSearchInLibraries()) {
final VirtualFile[] librarySources = ApplicationManager.getApplication().runReadAction(new Computable<VirtualFile[]>() {
@Override
public VirtualFile[] compute() {
OrderEnumerator enumerator = myModule == null ? OrderEnumerator.orderEntries(myProject) : OrderEnumerator.orderEntries(myModule);
return enumerator.withoutModuleSourceEntries().withoutDepModules().getSourceRoots();
}
});
iterateAll(librarySources, globalCustomScope, iterator);
}
}
return iterator.getFiles();
}
private static boolean isCoveredByIdIndex(VirtualFile file) {
return IdIndex.isIndexable(FileBasedIndexImpl.getFileType(file)) &&
((FileBasedIndexImpl)FileBasedIndex.getInstance()).isIndexingCandidate(file, IdIndex.NAME);
}
private static boolean iterateAll(@NotNull VirtualFile[] files, @NotNull final GlobalSearchScope searchScope, @NotNull final ContentIterator iterator) {
final FileTypeManager fileTypeManager = FileTypeManager.getInstance();
final VirtualFileFilter contentFilter = new VirtualFileFilter() {
@Override
public boolean accept(@NotNull final VirtualFile file) {
return file.isDirectory() ||
!fileTypeManager.isFileIgnored(file) && !file.getFileType().isBinary() && searchScope.contains(file);
}
};
for (VirtualFile file : files) {
if (!VfsUtilCore.iterateChildrenRecursively(file, contentFilter, iterator)) return false;
}
return true;
}
@Nullable
private GlobalSearchScope toGlobal(@Nullable final SearchScope scope) {
if (scope instanceof GlobalSearchScope || scope == null) {
return (GlobalSearchScope)scope;
}
return ApplicationManager.getApplication().runReadAction(new Computable<GlobalSearchScope>() {
@Override
public GlobalSearchScope compute() {
return GlobalSearchScope.filesScope(myProject, getLocalScopeFiles((LocalSearchScope)scope));
}
});
}
@NotNull
private static Set<VirtualFile> getLocalScopeFiles(@NotNull LocalSearchScope scope) {
Set<VirtualFile> files = new LinkedHashSet<VirtualFile>();
for (PsiElement element : scope.getScope()) {
PsiFile file = element.getContainingFile();
if (file != null) {
ContainerUtil.addIfNotNull(files, file.getVirtualFile());
}
}
return files;
}
private boolean canRelyOnIndices() {
if (DumbService.isDumb(myProject)) return false;
if (myFindModel.isRegularExpressions()) return false;
// a local scope may be over a non-indexed file
if (myFindModel.getCustomScope() instanceof LocalSearchScope) return false;
String text = myFindModel.getStringToFind();
if (StringUtil.isEmptyOrSpaces(text)) return false;
if (TrigramIndex.ENABLED) return !TrigramBuilder.buildTrigram(text).isEmpty();
// $ is used to separate words when indexing plain-text files but not when indexing
// Java identifiers, so we can't consistently break a string containing $ characters into words
return myFindModel.isWholeWordsOnly() && text.indexOf('$') < 0 && !StringUtil.getWordsInStringLongestFirst(text).isEmpty();
}
@NotNull
private Set<PsiFile> getFilesForFastWordSearch() {
String stringToFind = myFindModel.getStringToFind();
if (stringToFind.isEmpty() || DumbService.getInstance(myProject).isDumb()) {
return Collections.emptySet();
}
SearchScope customScope = myFindModel.getCustomScope();
GlobalSearchScope scope = myPsiDirectory != null
? GlobalSearchScopesCore.directoryScope(myPsiDirectory, true)
: myModule != null
? myModule.getModuleContentScope()
: customScope instanceof GlobalSearchScope
? (GlobalSearchScope)customScope
: toGlobal(customScope);
if (scope == null) {
scope = ProjectScope.getContentScope(myProject);
}
final Set<PsiFile> resultFiles = new LinkedHashSet<PsiFile>();
if (TrigramIndex.ENABLED) {
Set<Integer> keys = ContainerUtil.newTroveSet();
TIntHashSet trigrams = TrigramBuilder.buildTrigram(stringToFind);
TIntIterator it = trigrams.iterator();
while (it.hasNext()) {
keys.add(it.next());
}
if (!keys.isEmpty()) {
List<VirtualFile> hits = new ArrayList<VirtualFile>();
FileBasedIndex.getInstance().getFilesWithKey(TrigramIndex.INDEX_ID, keys, new CommonProcessors.CollectProcessor<VirtualFile>(hits), scope);
for (VirtualFile hit : hits) {
if (myFileMask.value(hit)) {
resultFiles.add(findFile(hit));
}
}
return resultFiles;
}
}
PsiSearchHelperImpl helper = (PsiSearchHelperImpl)PsiSearchHelper.SERVICE.getInstance(myProject);
helper.processFilesWithText(scope, UsageSearchContext.ANY, myFindModel.isCaseSensitive(), stringToFind, new Processor<VirtualFile>() {
@Override
public boolean process(VirtualFile file) {
if (myFileMask.value(file)) {
ContainerUtil.addIfNotNull(resultFiles, findFile(file));
}
return true;
}
});
// in case our word splitting is incorrect
for (PsiFile file : CacheManager.SERVICE.getInstance(myProject)
.getFilesWithWord(stringToFind, UsageSearchContext.ANY, scope, myFindModel.isCaseSensitive())) {
if (myFileMask.value(file.getVirtualFile())) {
resultFiles.add(file);
}
}
return resultFiles;
}
private PsiFile findFile(@NotNull final VirtualFile virtualFile) {
return ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() {
@Override
public PsiFile compute() {
return myPsiManager.findFile(virtualFile);
}
});
}
}
| platform/lang-impl/src/com/intellij/find/impl/FindInProjectTask.java | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.find.impl;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.intellij.find.FindBundle;
import com.intellij.find.FindModel;
import com.intellij.find.ngrams.TrigramIndex;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectCoreUtil;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.text.TrigramBuilder;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileFilter;
import com.intellij.psi.*;
import com.intellij.psi.impl.cache.CacheManager;
import com.intellij.psi.impl.cache.impl.id.IdIndex;
import com.intellij.psi.impl.search.PsiSearchHelperImpl;
import com.intellij.psi.search.*;
import com.intellij.usageView.UsageInfo;
import com.intellij.usages.FindUsagesProcessPresentation;
import com.intellij.usages.UsageLimitUtil;
import com.intellij.usages.impl.UsageViewManagerImpl;
import com.intellij.util.CommonProcessors;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.FileBasedIndex;
import com.intellij.util.indexing.FileBasedIndexImpl;
import gnu.trove.TIntHashSet;
import gnu.trove.TIntIterator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.regex.Pattern;
/**
* @author peter
*/
class FindInProjectTask {
private static final Logger LOG = Logger.getInstance("#com.intellij.find.impl.FindInProjectTask");
private static final int FILES_SIZE_LIMIT = 70 * 1024 * 1024; // megabytes.
private static final int SINGLE_FILE_SIZE_LIMIT = 5 * 1024 * 1024; // megabytes.
private final FindModel myFindModel;
private final Project myProject;
private final PsiManager myPsiManager;
@Nullable private final PsiDirectory myPsiDirectory;
private final FileIndex myFileIndex;
private final Condition<VirtualFile> myFileMask;
private final ProgressIndicator myProgress;
@Nullable private final Module myModule;
private final Set<PsiFile> myLargeFiles = ContainerUtil.newTroveSet();
private boolean myWarningShown;
FindInProjectTask(@NotNull final FindModel findModel,
@NotNull final Project project,
@Nullable final PsiDirectory psiDirectory) {
myFindModel = findModel;
myProject = project;
myPsiDirectory = psiDirectory;
myPsiManager = PsiManager.getInstance(project);
final String moduleName = findModel.getModuleName();
myModule = moduleName == null ? null : ApplicationManager.getApplication().runReadAction(new Computable<Module>() {
@Override
public Module compute() {
return ModuleManager.getInstance(project).findModuleByName(moduleName);
}
});
myFileIndex = myModule == null ?
ProjectRootManager.getInstance(project).getFileIndex() :
ModuleRootManager.getInstance(myModule).getFileIndex();
final String filter = findModel.getFileFilter();
final Pattern pattern = FindInProjectUtil.createFileMaskRegExp(filter);
//noinspection unchecked
myFileMask = pattern == null ? Condition.TRUE : new Condition<VirtualFile>() {
@Override
public boolean value(VirtualFile file) {
return file != null && pattern.matcher(file.getName()).matches();
}
};
final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
myProgress = progress != null ? progress : new EmptyProgressIndicator();
}
public void findUsages(@NotNull final Processor<UsageInfo> consumer, @NotNull FindUsagesProcessPresentation processPresentation) {
try {
myProgress.setIndeterminate(true);
myProgress.setText("Scanning indexed files...");
final Set<PsiFile> filesForFastWordSearch = getFilesForFastWordSearch();
myProgress.setIndeterminate(false);
searchInFiles(consumer, processPresentation, filesForFastWordSearch);
myProgress.setIndeterminate(true);
myProgress.setText("Scanning non-indexed files...");
final Collection<PsiFile> otherFiles = collectFilesInScope(filesForFastWordSearch);
myProgress.setIndeterminate(false);
long start = System.currentTimeMillis();
searchInFiles(consumer, processPresentation, otherFiles);
if (otherFiles.size() > 1000) {
logStats(otherFiles, start);
}
}
catch (ProcessCanceledException e) {
// fine
}
if (!myLargeFiles.isEmpty()) {
processPresentation.setLargeFilesWereNotScanned(myLargeFiles);
}
if (!myProgress.isCanceled()) {
myProgress.setText(FindBundle.message("find.progress.search.completed"));
}
}
private static void logStats(Collection<PsiFile> otherFiles, long start) {
long time = System.currentTimeMillis() - start;
final Multiset<String> stats = HashMultiset.create();
for (PsiFile file : otherFiles) {
stats.add(StringUtil.notNullize(file.getViewProvider().getVirtualFile().getExtension()).toLowerCase());
}
List<String> extensions = ContainerUtil.newArrayList(stats.elementSet());
Collections.sort(extensions, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return stats.count(o2) - stats.count(o1);
}
});
String message = "Search in " + otherFiles.size() + " files with unknown types took " + time + "ms.\n" +
"Mapping their extensions to an existing file type (e.g. Plain Text) might speed up the search.\n" +
"Most frequent unknown extensions: ";
for (int i = 0; i < Math.min(10, extensions.size()); i++) {
String extension = extensions.get(i);
message += extension + "(" + stats.count(extension) + ") ";
}
LOG.info(message);
}
private void searchInFiles(Processor<UsageInfo> consumer, FindUsagesProcessPresentation processPresentation, Collection<PsiFile> psiFiles) {
int i = 0;
long totalFilesSize = 0;
int count = 0;
for (final PsiFile psiFile : psiFiles) {
final VirtualFile virtualFile = psiFile.getVirtualFile();
final int index = i++;
if (virtualFile == null) continue;
long fileLength = UsageViewManagerImpl.getFileLength(virtualFile);
if (fileLength == -1) continue; // Binary or invalid
if (ProjectCoreUtil.isProjectOrWorkspaceFile(virtualFile) && !Registry.is("find.search.in.project.files")) continue;
if (fileLength > SINGLE_FILE_SIZE_LIMIT) {
myLargeFiles.add(psiFile);
continue;
}
myProgress.checkCanceled();
myProgress.setFraction((double)index / psiFiles.size());
String text = FindBundle.message("find.searching.for.string.in.file.progress",
myFindModel.getStringToFind(), virtualFile.getPresentableUrl());
myProgress.setText(text);
myProgress.setText2(FindBundle.message("find.searching.for.string.in.file.occurrences.progress", count));
int countInFile = FindInProjectUtil.processUsagesInFile(psiFile, myFindModel, consumer);
count += countInFile;
if (countInFile > 0) {
totalFilesSize += fileLength;
if (totalFilesSize > FILES_SIZE_LIMIT && !myWarningShown) {
myWarningShown = true;
String message = FindBundle.message("find.excessive.total.size.prompt",
UsageViewManagerImpl.presentableSize(totalFilesSize),
ApplicationNamesInfo.getInstance().getProductName());
UsageLimitUtil.showAndCancelIfAborted(myProject, message, processPresentation.getUsageViewPresentation());
}
}
}
}
@NotNull
private Collection<PsiFile> collectFilesInScope(@NotNull final Set<PsiFile> alreadySearched) {
SearchScope customScope = myFindModel.getCustomScope();
final GlobalSearchScope globalCustomScope = toGlobal(customScope);
final boolean skipIndexed = canRelyOnIndices();
class EnumContentIterator implements ContentIterator {
final Set<PsiFile> myFiles = new LinkedHashSet<PsiFile>();
@Override
public boolean processFile(@NotNull final VirtualFile virtualFile) {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
ProgressManager.checkCanceled();
if (virtualFile.isDirectory() || !virtualFile.isValid() ||
!myFileMask.value(virtualFile) ||
(globalCustomScope != null && !globalCustomScope.contains(virtualFile))) {
return;
}
if (skipIndexed && isCoveredByIdIndex(virtualFile)) {
return;
}
PsiFile psiFile = myPsiManager.findFile(virtualFile);
if (psiFile != null && !(psiFile instanceof PsiBinaryFile) && !alreadySearched.contains(psiFile)) {
PsiFile sourceFile = (PsiFile)psiFile.getNavigationElement();
if (sourceFile != null) psiFile = sourceFile;
myFiles.add(psiFile);
}
}
});
return true;
}
@NotNull
private Collection<PsiFile> getFiles() {
return myFiles;
}
}
EnumContentIterator iterator = new EnumContentIterator();
if (customScope instanceof LocalSearchScope) {
for (VirtualFile file : getLocalScopeFiles((LocalSearchScope)customScope)) {
iterator.processFile(file);
}
}
else if (myPsiDirectory != null) {
myFileIndex.iterateContentUnderDirectory(myPsiDirectory.getVirtualFile(), iterator);
}
else {
boolean success = myFileIndex.iterateContent(iterator);
if (success && globalCustomScope != null && globalCustomScope.isSearchInLibraries()) {
final VirtualFile[] librarySources = ApplicationManager.getApplication().runReadAction(new Computable<VirtualFile[]>() {
@Override
public VirtualFile[] compute() {
OrderEnumerator enumerator = myModule == null ? OrderEnumerator.orderEntries(myProject) : OrderEnumerator.orderEntries(myModule);
return enumerator.withoutModuleSourceEntries().withoutDepModules().getSourceRoots();
}
});
iterateAll(librarySources, globalCustomScope, iterator);
}
}
return iterator.getFiles();
}
private static boolean isCoveredByIdIndex(VirtualFile file) {
return IdIndex.isIndexable(FileBasedIndexImpl.getFileType(file)) &&
((FileBasedIndexImpl)FileBasedIndex.getInstance()).isIndexingCandidate(file, IdIndex.NAME);
}
private static boolean iterateAll(@NotNull VirtualFile[] files, @NotNull final GlobalSearchScope searchScope, @NotNull final ContentIterator iterator) {
final FileTypeManager fileTypeManager = FileTypeManager.getInstance();
final VirtualFileFilter contentFilter = new VirtualFileFilter() {
@Override
public boolean accept(@NotNull final VirtualFile file) {
return file.isDirectory() ||
!fileTypeManager.isFileIgnored(file) && !file.getFileType().isBinary() && searchScope.contains(file);
}
};
for (VirtualFile file : files) {
if (!VfsUtilCore.iterateChildrenRecursively(file, contentFilter, iterator)) return false;
}
return true;
}
@Nullable
private GlobalSearchScope toGlobal(@Nullable final SearchScope scope) {
if (scope instanceof GlobalSearchScope || scope == null) {
return (GlobalSearchScope)scope;
}
return ApplicationManager.getApplication().runReadAction(new Computable<GlobalSearchScope>() {
@Override
public GlobalSearchScope compute() {
return GlobalSearchScope.filesScope(myProject, getLocalScopeFiles((LocalSearchScope)scope));
}
});
}
@NotNull
private static Set<VirtualFile> getLocalScopeFiles(@NotNull LocalSearchScope scope) {
Set<VirtualFile> files = new LinkedHashSet<VirtualFile>();
for (PsiElement element : scope.getScope()) {
PsiFile file = element.getContainingFile();
if (file != null) {
ContainerUtil.addIfNotNull(files, file.getVirtualFile());
}
}
return files;
}
private boolean canRelyOnIndices() {
if (DumbService.isDumb(myProject)) return false;
if (myFindModel.isRegularExpressions()) return false;
// a local scope may be over a non-indexed file
if (myFindModel.getCustomScope() instanceof LocalSearchScope) return false;
String text = myFindModel.getStringToFind();
if (StringUtil.isEmptyOrSpaces(text)) return false;
if (TrigramIndex.ENABLED) return !TrigramBuilder.buildTrigram(text).isEmpty();
// $ is used to separate words when indexing plain-text files but not when indexing
// Java identifiers, so we can't consistently break a string containing $ characters into words
return myFindModel.isWholeWordsOnly() && text.indexOf('$') < 0 && !StringUtil.getWordsInStringLongestFirst(text).isEmpty();
}
@NotNull
private Set<PsiFile> getFilesForFastWordSearch() {
String stringToFind = myFindModel.getStringToFind();
if (stringToFind.isEmpty() || DumbService.getInstance(myProject).isDumb()) {
return Collections.emptySet();
}
SearchScope customScope = myFindModel.getCustomScope();
GlobalSearchScope scope = myPsiDirectory != null
? GlobalSearchScopesCore.directoryScope(myPsiDirectory, true)
: myModule != null
? myModule.getModuleContentScope()
: customScope instanceof GlobalSearchScope
? (GlobalSearchScope)customScope
: toGlobal(customScope);
if (scope == null) {
scope = ProjectScope.getContentScope(myProject);
}
final Set<PsiFile> resultFiles = new LinkedHashSet<PsiFile>();
if (TrigramIndex.ENABLED) {
Set<Integer> keys = ContainerUtil.newTroveSet();
TIntHashSet trigrams = TrigramBuilder.buildTrigram(stringToFind);
TIntIterator it = trigrams.iterator();
while (it.hasNext()) {
keys.add(it.next());
}
if (!keys.isEmpty()) {
List<VirtualFile> hits = new ArrayList<VirtualFile>();
FileBasedIndex.getInstance().getFilesWithKey(TrigramIndex.INDEX_ID, keys, new CommonProcessors.CollectProcessor<VirtualFile>(hits), scope);
for (VirtualFile hit : hits) {
if (myFileMask.value(hit)) {
resultFiles.add(findFile(hit));
}
}
return resultFiles;
}
}
PsiSearchHelperImpl helper = (PsiSearchHelperImpl)PsiSearchHelper.SERVICE.getInstance(myProject);
helper.processFilesWithText(scope, UsageSearchContext.ANY, myFindModel.isCaseSensitive(), stringToFind, new Processor<VirtualFile>() {
@Override
public boolean process(VirtualFile file) {
if (myFileMask.value(file)) {
ContainerUtil.addIfNotNull(resultFiles, findFile(file));
}
return true;
}
});
// in case our word splitting is incorrect
for (PsiFile file : CacheManager.SERVICE.getInstance(myProject)
.getFilesWithWord(stringToFind, UsageSearchContext.ANY, scope, myFindModel.isCaseSensitive())) {
if (myFileMask.value(file.getVirtualFile())) {
resultFiles.add(file);
}
}
return resultFiles;
}
private PsiFile findFile(@NotNull final VirtualFile virtualFile) {
return ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() {
@Override
public PsiFile compute() {
return myPsiManager.findFile(virtualFile);
}
});
}
}
| log most frequent unknown extensions only if indices were used (IDEA-121444)
| platform/lang-impl/src/com/intellij/find/impl/FindInProjectTask.java | log most frequent unknown extensions only if indices were used (IDEA-121444) | <ide><path>latform/lang-impl/src/com/intellij/find/impl/FindInProjectTask.java
<ide>
<ide> myProgress.setIndeterminate(true);
<ide> myProgress.setText("Scanning non-indexed files...");
<del> final Collection<PsiFile> otherFiles = collectFilesInScope(filesForFastWordSearch);
<add> boolean skipIndexed = canRelyOnIndices();
<add> final Collection<PsiFile> otherFiles = collectFilesInScope(filesForFastWordSearch, skipIndexed);
<ide> myProgress.setIndeterminate(false);
<ide>
<ide> long start = System.currentTimeMillis();
<ide> searchInFiles(consumer, processPresentation, otherFiles);
<del> if (otherFiles.size() > 1000) {
<add> if (skipIndexed && otherFiles.size() > 1000) {
<ide> logStats(otherFiles, start);
<ide> }
<ide> }
<ide>
<ide> String message = "Search in " + otherFiles.size() + " files with unknown types took " + time + "ms.\n" +
<ide> "Mapping their extensions to an existing file type (e.g. Plain Text) might speed up the search.\n" +
<del> "Most frequent unknown extensions: ";
<add> "Most frequent non-indexed file extensions: ";
<ide> for (int i = 0; i < Math.min(10, extensions.size()); i++) {
<ide> String extension = extensions.get(i);
<ide> message += extension + "(" + stats.count(extension) + ") ";
<ide> }
<ide>
<ide> @NotNull
<del> private Collection<PsiFile> collectFilesInScope(@NotNull final Set<PsiFile> alreadySearched) {
<add> private Collection<PsiFile> collectFilesInScope(@NotNull final Set<PsiFile> alreadySearched, final boolean skipIndexed) {
<ide> SearchScope customScope = myFindModel.getCustomScope();
<ide> final GlobalSearchScope globalCustomScope = toGlobal(customScope);
<del>
<del> final boolean skipIndexed = canRelyOnIndices();
<ide>
<ide> class EnumContentIterator implements ContentIterator {
<ide> final Set<PsiFile> myFiles = new LinkedHashSet<PsiFile>(); |
|
Java | lgpl-2.1 | f3a0cf90ad4e7e76088e008f219953ad00fe5adf | 0 | SimonKagstrom/cibyl,SimonKagstrom/cibyl,SimonKagstrom/cibyl,SimonKagstrom/cibyl,SimonKagstrom/cibyl | /* From the optimized fread by Ehud Shabtai */
public static final int NOPH_InputStream_read_into(int obj, int ptr, int size, int eof_addr) throws Exception
{
InputStream is = (InputStream)CRunTime.objectRepository[obj];
int count = 0;
byte[] buff = new byte[size];
try {
int r = is.read(buff);
if (r < 0) throw new EOFException();
CRunTime.memcpy(ptr, buff, 0, r);
count += r;
}
catch(EOFException e) {
CRunTime.memoryWriteWord( eof_addr, 1 );
}
buff = null;
return count;
}
| syscalls/java/implementation/NOPH_InputStream_read_into.java | /* From the optimized fread by Ehud Shabtai */
public static final int NOPH_InputStream_read_into(int obj, int ptr, int size, int eof_addr) throws Exception
{
InputStream is = (InputStream)CRunTime.objectRepository[__obj];
int count = 0;
byte[] buff = new byte[size];
try {
int r = is.read(buff);
if (r < 0) throw new EOFException();
if (r > 0) CRunTime.memcpy(ptr, buff, 0, r);
buff = null;
}
catch(EOFException) {
CRunTime.memoryWriteWord( addr_stdout, 1 );
}
return r;
}
| Compile fixes, return count
| syscalls/java/implementation/NOPH_InputStream_read_into.java | Compile fixes, return count | <ide><path>yscalls/java/implementation/NOPH_InputStream_read_into.java
<ide> /* From the optimized fread by Ehud Shabtai */
<ide> public static final int NOPH_InputStream_read_into(int obj, int ptr, int size, int eof_addr) throws Exception
<ide> {
<del> InputStream is = (InputStream)CRunTime.objectRepository[__obj];
<add> InputStream is = (InputStream)CRunTime.objectRepository[obj];
<ide> int count = 0;
<ide>
<ide> byte[] buff = new byte[size];
<ide> try {
<ide> int r = is.read(buff);
<ide> if (r < 0) throw new EOFException();
<del> if (r > 0) CRunTime.memcpy(ptr, buff, 0, r);
<del> buff = null;
<add> CRunTime.memcpy(ptr, buff, 0, r);
<add> count += r;
<ide> }
<del> catch(EOFException) {
<del> CRunTime.memoryWriteWord( addr_stdout, 1 );
<add> catch(EOFException e) {
<add> CRunTime.memoryWriteWord( eof_addr, 1 );
<ide> }
<add> buff = null;
<ide>
<del> return r;
<add> return count;
<ide> } |
|
JavaScript | mit | 5d128ec4c4a6c0a0cd25bd6571e28afecaef7a7c | 0 | redaktor/rdflib.js,timbl/rdflib.js,ariutta/rdflib.js,redaktor/rdflib.js,nicola/rdflib.js,ariutta/rdflib.js,timbl/rdflib.js,nicola/rdflib.js,timbl/rdflib.js,ariutta/rdflib.js | /**
* @fileoverview
* RDF/XML PARSER
*
* Version 0.1
* Parser believed to be in full positive RDF/XML parsing compliance
* with the possible exception of handling deprecated RDF attributes
* appropriately. Parser is believed to comply fully with other W3C
* and industry standards where appropriate (DOM, ECMAScript, &c.)
*
* Author: David Sheets <[email protected]>
*
* W3C® SOFTWARE NOTICE AND LICENSE
* http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
* This work (and included software, documentation such as READMEs, or
* other related items) is being provided by the copyright holders under
* the following license. By obtaining, using and/or copying this work,
* you (the licensee) agree that you have read, understood, and will
* comply with the following terms and conditions.
*
* Permission to copy, modify, and distribute this software and its
* documentation, with or without modification, for any purpose and
* without fee or royalty is hereby granted, provided that you include
* the following on ALL copies of the software and documentation or
* portions thereof, including modifications:
*
* 1. The full text of this NOTICE in a location viewable to users of
* the redistributed or derivative work.
* 2. Any pre-existing intellectual property disclaimers, notices, or terms and
* conditions. If none exist, the W3C Software Short Notice should be
* included (hypertext is preferred, text is permitted) within the body
* of any redistributed or derivative code.
* 3. Notice of any changes or modifications to the files, including the
* date changes were made. (We recommend you provide URIs to the location
* from which the code is derived.)
*
* THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT
* HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS
* FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR
* DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
* TRADEMARKS OR OTHER RIGHTS.
*
* COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL
* OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR
* DOCUMENTATION.
*
* The name and trademarks of copyright holders may NOT be used in
* advertising or publicity pertaining to the software without specific,
* written prior permission. Title to copyright in this software and any
* associated documentation will at all times remain with copyright
* holders.
*/
/**
* @class Class defining an RDFParser resource object tied to an RDFStore
*
* @author David Sheets <[email protected]>
* @version 0.1
*
* @constructor
* @param {RDFStore} store An RDFStore object
*/
$rdf.RDFParser = function(store){
var RDFParser = {};
/** Standard namespaces that we know how to handle @final
* @member RDFParser
*/
RDFParser.ns = {'RDF': "http://www.w3.org/1999/02/22-rdf-syntax-ns#", 'RDFS': "http://www.w3.org/2000/01/rdf-schema#"};
/** DOM Level 2 node type magic numbers @final
* @member RDFParser
*/
RDFParser.nodeType = {'ELEMENT': 1, 'ATTRIBUTE': 2, 'TEXT': 3,
'CDATA_SECTION': 4, 'ENTITY_REFERENCE': 5,
'ENTITY': 6, 'PROCESSING_INSTRUCTION': 7,
'COMMENT': 8, 'DOCUMENT': 9, 'DOCUMENT_TYPE': 10,
'DOCUMENT_FRAGMENT': 11, 'NOTATION': 12};
/**
* Frame class for namespace and base URI lookups
* Base lookups will always resolve because the parser knows
* the default base.
*
* @private
*/
this.frameFactory = function(parser, parent, element){
return {'NODE': 1, 'ARC': 2, 'parent': parent, 'parser': parser, 'store': parser.store, 'element': element,
'lastChild': 0, 'base': null, 'lang': null, 'node': null, 'nodeType': null, 'listIndex': 1, 'rdfid': null, 'datatype': null, 'collection': false, /** Terminate the frame and notify the store that we're done */
'terminateFrame': function(){
if (this.collection){
this.node.close();
}
}
, /** Add a symbol of a certain type to the this frame */'addSymbol': function(type, uri){
uri = $rdf.Util.uri.join(uri, this.base);
this.node = this.store.sym(uri);
this.nodeType = type;
}
, /** Load any constructed triples into the store */'loadTriple': function(){
if (this.parent.parent.collection){
this.parent.parent.node.append(this.node);
}
else {
this.store.add(this.parent.parent.node, this.parent.node, this.node, this.parser.why);
}
if (this.parent.rdfid != null){
// reify
var triple = this.store.sym($rdf.Util.uri.join("#" + this.parent.rdfid, this.base));
this.store.add(triple, this.store.sym(RDFParser.ns.RDF + "type"), this.store.sym(RDFParser.ns.RDF + "Statement"), this.parser.why);
this.store.add(triple, this.store.sym(RDFParser.ns.RDF + "subject"), this.parent.parent.node, this.parser.why);
this.store.add(triple, this.store.sym(RDFParser.ns.RDF + "predicate"), this.parent.node, this.parser.why);
this.store.add(triple, this.store.sym(RDFParser.ns.RDF + "object"), this.node, this.parser.why);
}
}
, /** Check if it's OK to load a triple */'isTripleToLoad': function(){
return (this.parent != null && this.parent.parent != null && this.nodeType === this.NODE && this.parent.nodeType ===
this.ARC && this.parent.parent.nodeType === this.NODE);
}
, /** Add a symbolic node to this frame */'addNode': function(uri){
this.addSymbol(this.NODE, uri);
if (this.isTripleToLoad()){
this.loadTriple();
}
}
, /** Add a collection node to this frame */'addCollection': function(){
this.nodeType = this.NODE;
this.node = this.store.collection();
this.collection = true;
if (this.isTripleToLoad()){
this.loadTriple();
}
}
, /** Add a collection arc to this frame */'addCollectionArc': function(){
this.nodeType = this.ARC;
}
, /** Add a bnode to this frame */'addBNode': function(id){
if (id != null){
if (this.parser.bnodes[id] != null){
this.node = this.parser.bnodes[id];
}
else {
this.node = this.parser.bnodes[id] = this.store.bnode();
}
}
else {
this.node = this.store.bnode();
}
this.nodeType = this.NODE;
if (this.isTripleToLoad()){
this.loadTriple();
}
}
, /** Add an arc or property to this frame */'addArc': function(uri){
if (uri === RDFParser.ns.RDF + "li"){
uri = RDFParser.ns.RDF + "_" + this.parent.listIndex;
this.parent.listIndex++;
}
this.addSymbol(this.ARC, uri);
}
, /** Add a literal to this frame */'addLiteral': function(value){
if (this.parent.datatype){
this.node = this.store.literal(value, "", this.store.sym(this.parent.datatype));
}
else {
this.node = this.store.literal(value, this.lang);
}
this.nodeType = this.NODE;
if (this.isTripleToLoad()){
this.loadTriple();
}
}
};
};
//from the OpenLayers source .. needed to get around IE problems.
this.getAttributeNodeNS = function(node, uri, name){
var attributeNode = null;
if (node.getAttributeNodeNS){
attributeNode = node.getAttributeNodeNS(uri, name);
}
else {
var attributes = node.attributes;
var potentialNode, fullName;
for (var i = 0;i < attributes.length; ++ i){
potentialNode = attributes[i];
if (potentialNode.namespaceURI === uri){
fullName = (potentialNode.prefix) ? (potentialNode.prefix +":" + name): name;
if (fullName === potentialNode.nodeName){
attributeNode = potentialNode;
break;
}
}
}
}
return attributeNode;
};
/** Our triple store reference @private */
this.store = store;/** Our identified blank nodes @private */
this.bnodes = {};/** A context for context-aware stores @private */
this.why = null;/** Reification flag */
this.reify = false;
/**
* Build our initial scope frame and parse the DOM into triples
* @param {DOMTree} document The DOM to parse
* @param {String} base The base URL to use
* @param {Object} why The context to which this resource belongs
*/
this.parse = function(document, base, why){
var children = document.childNodes;// clean up for the next run
this.cleanParser();// figure out the root element
var root;
if (document.nodeType === RDFParser.nodeType.DOCUMENT){
for (var c = 0;c < children.length;c++){
if (children[c].nodeType === RDFParser.nodeType.ELEMENT){
root = children[c];
break;
}
}
}
else if (document.nodeType === RDFParser.nodeType.ELEMENT){
root = document;
}
else {
throw new Error("RDFParser: can't find root in " + base +". Halting. ");
// return false;
}
this.why = why;// our topmost frame
var f = this.frameFactory(this);
this.base = base;
f.base = base;
f.lang = '';
this.parseDOM(this.buildFrame(f, root));
return true;
};
this.parseDOM = function(frame){
// a DOM utility function used in parsing
var rdfid;
var elementURI = function(el){
var result = "";
if (el.namespaceURI == null){
throw new Error("RDF/XML syntax error: No namespace for " + el.localName + " in " + this.base);
}
if (el.namespaceURI){
result = result + el.namespaceURI;
}
if (el.localName){
result = result + el.localName;
}
else if (el.nodeName){
if (el.nodeName.indexOf(":") >= 0)result = result + el.nodeName.split(":")[1];
else result = result + el.nodeName;
}
return result;
}.bind(this);
var dig = true;// if we'll dig down in the tree on the next iter
while (frame.parent){
var dom = frame.element;
var attrs = dom.attributes;
if (dom.nodeType === RDFParser.nodeType.TEXT || dom.nodeType === RDFParser.nodeType.CDATA_SECTION){
//we have a literal
frame.addLiteral(dom.nodeValue);
}
else if (elementURI(dom)!== RDFParser.ns.RDF + "RDF"){
// not root
if (frame.parent && frame.parent.collection){
// we're a collection element
frame.addCollectionArc();
frame = this.buildFrame(frame, frame.element);
frame.parent.element = null;
}
if ( ! frame.parent || ! frame.parent.nodeType || frame.parent.nodeType === frame.ARC){
// we need a node
var about = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "about");
rdfid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "ID");
if (about && rdfid){
throw new Error("RDFParser: " + dom.nodeName + " has both rdf:id and rdf:about." +
" Halting. Only one of these" + " properties may be specified on a" + " node.");
}
if (!about && rdfid){
frame.addNode("#" + rdfid.nodeValue);
dom.removeAttributeNode(rdfid);
}
else if (about == null && rdfid == null){
var bnid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "nodeID");
if (bnid){
frame.addBNode(bnid.nodeValue);
dom.removeAttributeNode(bnid);
}
else {
frame.addBNode();
}
}
else {
frame.addNode(about.nodeValue);
dom.removeAttributeNode(about);
}
// Typed nodes
var rdftype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "type");
if (RDFParser.ns.RDF + "Description" !== elementURI(dom)){
rdftype = {'nodeValue': elementURI(dom)};
}
if (rdftype != null){
this.store.add(frame.node, this.store.sym(RDFParser.ns.RDF + "type"), this.store.sym($rdf.Util.uri.join(rdftype.nodeValue,
frame.base)), this.why);
if (rdftype.nodeName){
dom.removeAttributeNode(rdftype);
}
}
// Property Attributes
for (var x = attrs.length - 1;x >= 0;x--){
this.store.add(frame.node, this.store.sym(elementURI(attrs[x])), this.store.literal(attrs[x].nodeValue,
frame.lang), this.why);
}
}
else {
// we should add an arc (or implicit bnode+arc)
frame.addArc(elementURI(dom));// save the arc's rdf:ID if it has one
if (this.reify){
rdfid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "ID");
if (rdfid){
frame.rdfid = rdfid.nodeValue;
dom.removeAttributeNode(rdfid);
}
}
var parsetype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "parseType");
var datatype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "datatype");
if (datatype){
frame.datatype = datatype.nodeValue;
dom.removeAttributeNode(datatype);
}
if (parsetype){
var nv = parsetype.nodeValue;
if (nv === "Literal"){
frame.datatype = RDFParser.ns.RDF + "XMLLiteral";// (this.buildFrame(frame)).addLiteral(dom)
// should work but doesn't
frame = this.buildFrame(frame);
frame.addLiteral(dom);
dig = false;
}
else if (nv === "Resource"){
frame = this.buildFrame(frame, frame.element);
frame.parent.element = null;
frame.addBNode();
}
else if (nv === "Collection"){
frame = this.buildFrame(frame, frame.element);
frame.parent.element = null;
frame.addCollection();
}
dom.removeAttributeNode(parsetype);
}
if (attrs.length !== 0){
var resource = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "resource");
var bnid2 = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "nodeID");
frame = this.buildFrame(frame);
if (resource){
frame.addNode(resource.nodeValue);
dom.removeAttributeNode(resource);
}
else {
if (bnid2){
frame.addBNode(bnid2.nodeValue);
dom.removeAttributeNode(bnid2);
}
else {
frame.addBNode();
}
}
for (var x1 = attrs.length - 1; x1 >= 0; x1--){
var f = this.buildFrame(frame);
f.addArc(elementURI(attrs[x1]));
if (elementURI(attrs[x1])=== RDFParser.ns.RDF + "type"){
(this.buildFrame(f)).addNode(attrs[x1].nodeValue);
}
else {
(this.buildFrame(f)).addLiteral(attrs[x1].nodeValue);
}
}
}
else if (dom.childNodes.length === 0){
(this.buildFrame(frame)).addLiteral("");
}
}
}// rdf:RDF
// dig dug
dom = frame.element;
while (frame.parent){
var pframe = frame;
while (dom == null){
frame = frame.parent;
dom = frame.element;
}
var candidate = dom.childNodes && dom.childNodes[frame.lastChild];
if (!candidate || ! dig){
frame.terminateFrame();
if ( ! (frame = frame.parent)){
break;
}// done
dom = frame.element;
dig = true;
}
else if ((candidate.nodeType !== RDFParser.nodeType.ELEMENT &&
candidate.nodeType !== RDFParser.nodeType.TEXT &&
candidate.nodeType !== RDFParser.nodeType.CDATA_SECTION) ||
((candidate.nodeType === RDFParser.nodeType.TEXT ||
candidate.nodeType === RDFParser.nodeType.CDATA_SECTION) &&
dom.childNodes.length !== 1)){
frame.lastChild++;
}
else {
// not a leaf
frame.lastChild++;
frame = this.buildFrame(pframe, dom.childNodes[frame.lastChild - 1]);
break;
}
}
}// while
};
/**
* Cleans out state from a previous parse run
* @private
*/
this.cleanParser = function(){
this.bnodes = {};
this.why = null;
};
/**
* Builds scope frame
* @private
*/
this.buildFrame = function(parent, element){
var frame = this.frameFactory(this, parent, element);
if (parent){
frame.base = parent.base;
frame.lang = parent.lang;
}
if (!element || element.nodeType === RDFParser.nodeType.TEXT ||
element.nodeType === RDFParser.nodeType.CDATA_SECTION){
return frame;
}
var attrs = element.attributes;
var base = element.getAttributeNode("xml:base");
if (base != null){
frame.base = base.nodeValue;
element.removeAttribute("xml:base");
}
var lang = element.getAttributeNode("xml:lang");
if (lang != null){
frame.lang = lang.nodeValue;
element.removeAttribute("xml:lang");
}
// remove all extraneous xml and xmlns attributes
for (var x = attrs.length - 1;x >= 0;x--){
if (attrs[x].nodeName.substr(0, 3) === "xml"){
if (attrs[x].name.slice(0, 6) === 'xmlns:'){
var uri = attrs[x].nodeValue;// alert('base for namespac attr:'+this.base);
if (this.base) uri = $rdf.Util.uri.join(uri, this.base);
this.store.setPrefixForURI(attrs[x].name.slice(6), uri);
}
// alert('rdfparser: xml atribute: '+attrs[x].name) //@@
element.removeAttributeNode(attrs[x]);
}
}
return frame;
};
};
| rdfparser.js | /**
* @fileoverview
* RDF/XML PARSER
*
* Version 0.1
* Parser believed to be in full positive RDF/XML parsing compliance
* with the possible exception of handling deprecated RDF attributes
* appropriately. Parser is believed to comply fully with other W3C
* and industry standards where appropriate (DOM, ECMAScript, &c.)
*
* Author: David Sheets <[email protected]>
*
* W3C® SOFTWARE NOTICE AND LICENSE
* http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
* This work (and included software, documentation such as READMEs, or
* other related items) is being provided by the copyright holders under
* the following license. By obtaining, using and/or copying this work,
* you (the licensee) agree that you have read, understood, and will
* comply with the following terms and conditions.
*
* Permission to copy, modify, and distribute this software and its
* documentation, with or without modification, for any purpose and
* without fee or royalty is hereby granted, provided that you include
* the following on ALL copies of the software and documentation or
* portions thereof, including modifications:
*
* 1. The full text of this NOTICE in a location viewable to users of
* the redistributed or derivative work.
* 2. Any pre-existing intellectual property disclaimers, notices, or terms and
* conditions. If none exist, the W3C Software Short Notice should be
* included (hypertext is preferred, text is permitted) within the body
* of any redistributed or derivative code.
* 3. Notice of any changes or modifications to the files, including the
* date changes were made. (We recommend you provide URIs to the location
* from which the code is derived.)
*
* THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT
* HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS
* FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR
* DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
* TRADEMARKS OR OTHER RIGHTS.
*
* COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL
* OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR
* DOCUMENTATION.
*
* The name and trademarks of copyright holders may NOT be used in
* advertising or publicity pertaining to the software without specific,
* written prior permission. Title to copyright in this software and any
* associated documentation will at all times remain with copyright
* holders.
*/
/**
* @class Class defining an RDFParser resource object tied to an RDFStore
*
* @author David Sheets <[email protected]>
* @version 0.1
*
* @constructor
* @param {RDFStore} store An RDFStore object
*/
$rdf.RDFParser = function(store){
var RDFParser = {};
/** Standard namespaces that we know how to handle @final
* @member RDFParser
*/
RDFParser.ns = {'RDF': "http://www.w3.org/1999/02/22-rdf-syntax-ns#", 'RDFS': "http://www.w3.org/2000/01/rdf-schema#"};
/** DOM Level 2 node type magic numbers @final
* @member RDFParser
*/
RDFParser.nodeType = {'ELEMENT': 1, 'ATTRIBUTE': 2, 'TEXT': 3,
'CDATA_SECTION': 4, 'ENTITY_REFERENCE': 5,
'ENTITY': 6, 'PROCESSING_INSTRUCTION': 7,
'COMMENT': 8, 'DOCUMENT': 9, 'DOCUMENT_TYPE': 10,
'DOCUMENT_FRAGMENT': 11, 'NOTATION': 12};
/**
* Frame class for namespace and base URI lookups
* Base lookups will always resolve because the parser knows
* the default base.
*
* @private
*/
this.frameFactory = function(parser, parent, element){
return {'NODE': 1, 'ARC': 2, 'parent': parent, 'parser': parser, 'store': parser.store, 'element': element,
'lastChild': 0, 'base': null, 'lang': null, 'node': null, 'nodeType': null, 'listIndex': 1, 'rdfid': null, 'datatype': null, 'collection': false, /** Terminate the frame and notify the store that we're done */
'terminateFrame': function(){
if (this.collection){
this.node.close();
}
}
, /** Add a symbol of a certain type to the this frame */'addSymbol': function(type, uri){
uri = $rdf.Util.uri.join(uri, this.base);
this.node = this.store.sym(uri);
this.nodeType = type;
}
, /** Load any constructed triples into the store */'loadTriple': function(){
if (this.parent.parent.collection){
this.parent.parent.node.append(this.node);
}
else {
this.store.add(this.parent.parent.node, this.parent.node, this.node, this.parser.why);
}
if (this.parent.rdfid != null){
// reify
var triple = this.store.sym($rdf.Util.uri.join("#" + this.parent.rdfid, this.base));
this.store.add(triple, this.store.sym(RDFParser.ns.RDF + "type"), this.store.sym(RDFParser.ns.RDF + "Statement"), this.parser.why);
this.store.add(triple, this.store.sym(RDFParser.ns.RDF + "subject"), this.parent.parent.node, this.parser.why);
this.store.add(triple, this.store.sym(RDFParser.ns.RDF + "predicate"), this.parent.node, this.parser.why);
this.store.add(triple, this.store.sym(RDFParser.ns.RDF + "object"), this.node, this.parser.why);
}
}
, /** Check if it's OK to load a triple */'isTripleToLoad': function(){
return (this.parent != null && this.parent.parent != null && this.nodeType === this.NODE && this.parent.nodeType ===
this.ARC && this.parent.parent.nodeType === this.NODE);
}
, /** Add a symbolic node to this frame */'addNode': function(uri){
this.addSymbol(this.NODE, uri);
if (this.isTripleToLoad()){
this.loadTriple();
}
}
, /** Add a collection node to this frame */'addCollection': function(){
this.nodeType = this.NODE;
this.node = this.store.collection();
this.collection = true;
if (this.isTripleToLoad()){
this.loadTriple();
}
}
, /** Add a collection arc to this frame */'addCollectionArc': function(){
this.nodeType = this.ARC;
}
, /** Add a bnode to this frame */'addBNode': function(id){
if (id != null){
if (this.parser.bnodes[id] != null){
this.node = this.parser.bnodes[id];
}
else {
this.node = this.parser.bnodes[id] = this.store.bnode();
}
}
else {
this.node = this.store.bnode();
}
this.nodeType = this.NODE;
if (this.isTripleToLoad()){
this.loadTriple();
}
}
, /** Add an arc or property to this frame */'addArc': function(uri){
if (uri === RDFParser.ns.RDF + "li"){
uri = RDFParser.ns.RDF + "_" + this.parent.listIndex;
this.parent.listIndex++;
}
this.addSymbol(this.ARC, uri);
}
, /** Add a literal to this frame */'addLiteral': function(value){
if (this.parent.datatype){
this.node = this.store.literal(value, "", this.store.sym(this.parent.datatype));
}
else {
this.node = this.store.literal(value, this.lang);
}
this.nodeType = this.NODE;
if (this.isTripleToLoad()){
this.loadTriple();
}
}
};
};
//from the OpenLayers source .. needed to get around IE problems.
this.getAttributeNodeNS = function(node, uri, name){
var attributeNode = null;
if (node.getAttributeNodeNS){
attributeNode = node.getAttributeNodeNS(uri, name);
}
else {
var attributes = node.attributes;
var potentialNode, fullName;
for (var i = 0;i < attributes.length; ++ i){
potentialNode = attributes[i];
if (potentialNode.namespaceURI === uri){
fullName = (potentialNode.prefix) ? (potentialNode.prefix +":" + name): name;
if (fullName === potentialNode.nodeName){
attributeNode = potentialNode;
break;
}
}
}
}
return attributeNode;
};
/** Our triple store reference @private */
this.store = store;/** Our identified blank nodes @private */
this.bnodes = {};/** A context for context-aware stores @private */
this.why = null;/** Reification flag */
this.reify = false;
/**
* Build our initial scope frame and parse the DOM into triples
* @param {DOMTree} document The DOM to parse
* @param {String} base The base URL to use
* @param {Object} why The context to which this resource belongs
*/
this.parse = function(document, base, why){
var children = document.childNodes;// clean up for the next run
this.cleanParser();// figure out the root element
var root;
if (document.nodeType === RDFParser.nodeType.DOCUMENT){
for (var c = 0;c < children.length;c++){
if (children[c].nodeType === RDFParser.nodeType.ELEMENT){
root = children[c];
break;
}
}
}
else if (document.nodeType === RDFParser.nodeType.ELEMENT){
root = document;
}
else {
throw new Error("RDFParser: can't find root in " + base +". Halting. ");
// return false;
}
this.why = why;// our topmost frame
var f = this.frameFactory(this);
this.base = base;
f.base = base;
f.lang = '';
this.parseDOM(this.buildFrame(f, root));
return true;
};
this.parseDOM = function(frame){
// a DOM utility function used in parsing
var rdfid;
var elementURI = function(el){
var result = "";
if (el.namespaceURI == null){
throw new Error("RDF/XML syntax error: No namespace for " + el.localName + " in " + this.base);
}
if (el.namespaceURI){
result = result + el.namespaceURI;
}
if (el.localName){
result = result + el.localName;
}
else if (el.nodeName){
if (el.nodeName.indexOf(":") >= 0)result = result + el.nodeName.split(":")[1];
else result = result + el.nodeName;
}
return result;
}.bind(this);
var dig = true;// if we'll dig down in the tree on the next iter
while (frame.parent){
var dom = frame.element;
var attrs = dom.attributes;
if (dom.nodeType === RDFParser.nodeType.TEXT || dom.nodeType === RDFParser.nodeType.CDATA_SECTION){
//we have a literal
frame.addLiteral(dom.nodeValue);
}
else if (elementURI(dom)!== RDFParser.ns.RDF + "RDF"){
// not root
if (frame.parent && frame.parent.collection){
// we're a collection element
frame.addCollectionArc();
frame = this.buildFrame(frame, frame.element);
frame.parent.element = null;
}
if ( ! frame.parent || ! frame.parent.nodeType || frame.parent.nodeType === frame.ARC){
// we need a node
var about = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "about");
rdfid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "ID");
if (about && rdfid){
throw new Error("RDFParser: " + dom.nodeName + " has both rdf:id and rdf:about." +
" Halting. Only one of these" + " properties may be specified on a" + " node.");
}
if (!about && rdfid){
frame.addNode("#" + rdfid.nodeValue);
dom.removeAttributeNode(rdfid);
}
else if (about == null && rdfid == null){
var bnid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "nodeID");
if (bnid){
frame.addBNode(bnid.nodeValue);
dom.removeAttributeNode(bnid);
}
else {
frame.addBNode();
}
}
else {
frame.addNode(about.nodeValue);
dom.removeAttributeNode(about);
}
// Typed nodes
var rdftype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "type");
if (RDFParser.ns.RDF + "Description" !== elementURI(dom)){
rdftype = {'nodeValue': elementURI(dom)};
}
if (rdftype != null){
this.store.add(frame.node, this.store.sym(RDFParser.ns.RDF + "type"), this.store.sym($rdf.Util.uri.join(rdftype.nodeValue,
frame.base)), this.why);
if (rdftype.nodeName){
dom.removeAttributeNode(rdftype);
}
}
// Property Attributes
for (var x = attrs.length - 1;x >= 0;x--){
this.store.add(frame.node, this.store.sym(elementURI(attrs[x])), this.store.literal(attrs[x].nodeValue,
frame.lang), this.why);
}
}
else {
// we should add an arc (or implicit bnode+arc)
frame.addArc(elementURI(dom));// save the arc's rdf:ID if it has one
if (this.reify){
rdfid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "ID");
if (rdfid){
frame.rdfid = rdfid.nodeValue;
dom.removeAttributeNode(rdfid);
}
}
var parsetype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "parseType");
var datatype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "datatype");
if (datatype){
frame.datatype = datatype.nodeValue;
dom.removeAttributeNode(datatype);
}
if (parsetype){
var nv = parsetype.nodeValue;
if (nv === "Literal"){
frame.datatype = RDFParser.ns.RDF + "XMLLiteral";// (this.buildFrame(frame)).addLiteral(dom)
// should work but doesn't
frame = this.buildFrame(frame);
frame.addLiteral(dom);
dig = false;
}
else if (nv === "Resource"){
frame = this.buildFrame(frame, frame.element);
frame.parent.element = null;
frame.addBNode();
}
else if (nv === "Collection"){
frame = this.buildFrame(frame, frame.element);
frame.parent.element = null;
frame.addCollection();
}
dom.removeAttributeNode(parsetype);
}
if (attrs.length !== 0){
var resource = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "resource");
var bnid2 = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, "nodeID");
frame = this.buildFrame(frame);
if (resource){
frame.addNode(resource.nodeValue);
dom.removeAttributeNode(resource);
}
else {
if (bnid2){
frame.addBNode(bnid2.nodeValue);
dom.removeAttributeNode(bnid2);
}
else {
frame.addBNode();
}
}
for (var x1 = attrs.length - 1; x1 >= 0; x1--){
var f = this.buildFrame(frame);
f.addArc(elementURI(attrs[x1]));
if (elementURI(attrs[x1])=== RDFParser.ns.RDF + "type"){
(this.buildFrame(f)).addNode(attrs[x1].nodeValue);
}
else {
(this.buildFrame(f)).addLiteral(attrs[x1].nodeValue);
}
}
}
else if (dom.childNodes.length === 0){
(this.buildFrame(frame)).addLiteral("");
}
}
}// rdf:RDF
// dig dug
dom = frame.element;
while (frame.parent){
var pframe = frame;
while (dom == null){
frame = frame.parent;
dom = frame.element;
}
var candidate = dom.childNodes[frame.lastChild];
if (!candidate || ! dig){
frame.terminateFrame();
if ( ! (frame = frame.parent)){
break;
}// done
dom = frame.element;
dig = true;
}
else if ((candidate.nodeType !== RDFParser.nodeType.ELEMENT &&
candidate.nodeType !== RDFParser.nodeType.TEXT &&
candidate.nodeType !== RDFParser.nodeType.CDATA_SECTION) ||
((candidate.nodeType === RDFParser.nodeType.TEXT ||
candidate.nodeType === RDFParser.nodeType.CDATA_SECTION) &&
dom.childNodes.length !== 1)){
frame.lastChild++;
}
else {
// not a leaf
frame.lastChild++;
frame = this.buildFrame(pframe, dom.childNodes[frame.lastChild - 1]);
break;
}
}
}// while
};
/**
* Cleans out state from a previous parse run
* @private
*/
this.cleanParser = function(){
this.bnodes = {};
this.why = null;
};
/**
* Builds scope frame
* @private
*/
this.buildFrame = function(parent, element){
var frame = this.frameFactory(this, parent, element);
if (parent){
frame.base = parent.base;
frame.lang = parent.lang;
}
if (!element || element.nodeType === RDFParser.nodeType.TEXT ||
element.nodeType === RDFParser.nodeType.CDATA_SECTION){
return frame;
}
var attrs = element.attributes;
var base = element.getAttributeNode("xml:base");
if (base != null){
frame.base = base.nodeValue;
element.removeAttribute("xml:base");
}
var lang = element.getAttributeNode("xml:lang");
if (lang != null){
frame.lang = lang.nodeValue;
element.removeAttribute("xml:lang");
}
// remove all extraneous xml and xmlns attributes
for (var x = attrs.length - 1;x >= 0;x--){
if (attrs[x].nodeName.substr(0, 3) === "xml"){
if (attrs[x].name.slice(0, 6) === 'xmlns:'){
var uri = attrs[x].nodeValue;// alert('base for namespac attr:'+this.base);
if (this.base) uri = $rdf.Util.uri.join(uri, this.base);
this.store.setPrefixForURI(attrs[x].name.slice(6), uri);
}
// alert('rdfparser: xml atribute: '+attrs[x].name) //@@
element.removeAttributeNode(attrs[x]);
}
}
return frame;
};
};
| Support the DOM tree generated by the node.js package xmldom
| rdfparser.js | Support the DOM tree generated by the node.js package xmldom | <ide><path>dfparser.js
<ide> frame = frame.parent;
<ide> dom = frame.element;
<ide> }
<del> var candidate = dom.childNodes[frame.lastChild];
<add> var candidate = dom.childNodes && dom.childNodes[frame.lastChild];
<ide> if (!candidate || ! dig){
<ide> frame.terminateFrame();
<ide> if ( ! (frame = frame.parent)){ |
|
Java | bsd-3-clause | 5c889b41dd9390989e56b959745df94125de6fdc | 0 | irfanah/jbehave-core,mestihudson/jbehave-core,gmandnepr/jbehave-core,donsenior/jbehave-core,kops/jbehave-core,skundrik/jbehave-core,jbehave/jbehave-core,codehaus/jbehave-core,donsenior/jbehave-core,mestihudson/jbehave-core,bsaylor/jbehave-core,pocamin/jbehave-core,eugen-eugen/eugensjbehave,kops/jbehave-core,bsaylor/jbehave-core,mestihudson/jbehave-core,skundrik/jbehave-core,valfirst/jbehave-core,jeremiehuchet/jbehave-core,codehaus/jbehave-core,sischnei/jbehave-core,kops/jbehave-core,valfirst/jbehave-core,eugen-eugen/eugensjbehave,eugen-eugen/eugensjbehave,pocamin/jbehave-core,irfanah/jbehave-core,skundrik/jbehave-core,valfirst/jbehave-core,valfirst/jbehave-core,eugen-eugen/eugensjbehave,eugen-eugen/eugensjbehave,codehaus/jbehave-core,donsenior/jbehave-core,gmandnepr/jbehave-core,gmandnepr/jbehave-core,irfanah/jbehave-core,jbehave/jbehave-core,irfanah/jbehave-core,irfanah/jbehave-core,codehaus/jbehave-core,mestihudson/jbehave-core,jbehave/jbehave-core,bsaylor/jbehave-core,eugen-eugen/eugensjbehave,sischnei/jbehave-core,jeremiehuchet/jbehave-core,mestihudson/jbehave-core,pocamin/jbehave-core,sischnei/jbehave-core,jbehave/jbehave-core,sischnei/jbehave-core,mhariri/jbehave-core,jeremiehuchet/jbehave-core,mhariri/jbehave-core,sischnei/jbehave-core,codehaus/jbehave-core,mhariri/jbehave-core | package org.jbehave.core.reporters;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.jbehave.core.configuration.Keywords;
import org.jbehave.core.failures.UUIDExceptionWrapper;
import org.jbehave.core.model.ExamplesTable;
import org.jbehave.core.model.GivenStories;
import org.jbehave.core.model.GivenStory;
import org.jbehave.core.model.Meta;
import org.jbehave.core.model.Narrative;
import org.jbehave.core.model.OutcomesTable;
import org.jbehave.core.model.OutcomesTable.Outcome;
import org.jbehave.core.model.Scenario;
import org.jbehave.core.model.Story;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;
import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
import static org.apache.commons.lang.StringEscapeUtils.escapeXml;
import static org.jbehave.core.steps.StepCreator.PARAMETER_VALUE_END;
import static org.jbehave.core.steps.StepCreator.PARAMETER_VALUE_NEWLINE;
import static org.jbehave.core.steps.StepCreator.PARAMETER_VALUE_START;
/**
* <p>
* Abstract story reporter that outputs to a PrintStream.
* </p>
* <p>
* The output of the reported event is configurable via:
* <ul>
* <li>custom output patterns, providing only the patterns that differ from
* default</li>
* <li>keywords localised for different languages, providing the i18n Locale</li>
* <li>flag to report failure trace</li>
* </ul>
* </p>
* <p>
* Let's look at example of providing custom output patterns, e.g. for the
* failed event. <br/>
* we'd need to provide the custom pattern, say we want to have something like
* "(step being executed) <<< FAILED", keyed on the method name:
*
* <pre>
* Properties patterns = new Properties();
* patterns.setProperty("failed", "{0} <<< {1}");
* </pre>
*
* The pattern is by default processed and formatted by the
* {@link MessageFormat}. Both the {@link #format(String key, String defaultPattern, Object... args)} and
* {@link #lookupPattern(String key, String defaultPattern)} methods are override-able and a different formatter
* or pattern lookup can be used by subclasses.
* </p>
* <p>
* If the keyword "FAILED" (or any other keyword used by the reporter) needs to
* be expressed in a different language, all we need to do is to provide an
* instance of {@link org.jbehave.core.i18n.LocalizedKeywords} using the appropriate {@link Locale}, e.g.
*
* <pre>
* Keywords keywords = new LocalizedKeywords(new Locale("it"));
* </pre>
*
* </p>
*/
public abstract class PrintStreamOutput implements StoryReporter {
private static final String EMPTY = "";
public enum Format { TXT, HTML, XML }
private final Format format;
private final PrintStream output;
private final Properties outputPatterns;
private final Keywords keywords;
private boolean reportFailureTrace;
private Throwable cause;
protected PrintStreamOutput(Format format, PrintStream output, Properties outputPatterns,
Keywords keywords, boolean reportFailureTrace) {
this.format = format;
this.output = output;
this.outputPatterns = outputPatterns;
this.keywords = keywords;
this.reportFailureTrace = reportFailureTrace;
}
public void successful(String step) {
print(format("successful", "{0}\n", step));
}
public void ignorable(String step) {
print(format("ignorable", "{0}\n", step));
}
public void pending(String step) {
print(format("pending", "{0} ({1})\n", step, keywords.pending()));
}
public void notPerformed(String step) {
print(format("notPerformed", "{0} ({1})\n", step, keywords.notPerformed()));
}
public void failed(String step, Throwable storyFailure) {
// storyFailure be used if a subclass has rewritten the "failed" pattern to have a {3} as WebDriverHtmlOutput (jbehave-web) does.
if (storyFailure instanceof UUIDExceptionWrapper) {
this.cause = storyFailure.getCause();
print(format("failed", "{0} ({1})\n({2})\n", step, keywords.failed(), storyFailure.getCause(), ((UUIDExceptionWrapper) storyFailure).getUUID()));
} else {
throw new ClassCastException(storyFailure +" should be an instance of UUIDExceptionWrapper");
}
}
public void failedOutcomes(String step, OutcomesTable table) {
failed(step, table.failureCause());
print(table);
}
private void print(OutcomesTable table) {
print(format("outcomesTableStart", "\n"));
List<Outcome<?>> rows = table.getOutcomes();
print(format("outcomesTableHeadStart", "|"));
//TODO i18n outcome fields
for (String field : table.getOutcomeFields()) {
print(format("outcomesTableHeadCell", "{0}|", field));
}
print(format("outcomesTableHeadEnd", "\n"));
print(format("outcomesTableBodyStart", EMPTY));
for (Outcome<?> outcome : rows) {
print(format("outcomesTableRowStart", "|", outcome.isVerified()?"verified":"notVerified"));
print(format("outcomesTableCell", "{0}|", outcome.getDescription()));
print(format("outcomesTableCell", "{0}|", outcome.getValue()));
print(format("outcomesTableCell", "{0}|", outcome.getMatcher()));
print(format("outcomesTableCell", "{0}|", outcome.isVerified()));
print(format("outcomesTableRowEnd", "\n"));
}
print(format("outcomesTableBodyEnd", "\n"));
print(format("outcomesTableEnd", "\n"));
}
public void storyNotAllowed(Story story, String filter) {
print(format("filter", "{0}\n", filter));
}
public void beforeStory(Story story, boolean givenStory) {
print(format("beforeStory", "{0}\n({1})\n", story.getDescription().asString(), story.getPath()));
if (!story.getMeta().isEmpty()) {
Meta meta = story.getMeta();
print(meta);
}
}
public void narrative(Narrative narrative) {
if (!narrative.isEmpty()) {
print(format("narrative", "{0}\n{1} {2}\n{3} {4}\n{5} {6}\n", keywords.narrative(), keywords.inOrderTo(),
narrative.inOrderTo(), keywords.asA(), narrative.asA(), keywords.iWantTo(), narrative.iWantTo()));
}
}
private void print(Meta meta) {
print(format("metaStart", "{0}\n", keywords.meta()));
for (String name : meta.getPropertyNames() ){
print(format("metaProperty", "{0}{1} {2}", keywords.metaProperty(), name, meta.getProperty(name)));
}
print(format("metaEnd", "\n"));
}
public void afterStory(boolean givenStory) {
print(format("afterStory", "\n"));
}
public void givenStories(GivenStories givenStories) {
print(format("givenStoriesStart", "{0}\n", keywords.givenStories()));
for (GivenStory givenStory : givenStories.getStories()) {
print(format("givenStory", "{0} {1}\n", givenStory.asString(), (givenStory.hasAnchor() ? givenStory.getParameters() : "")));
}
print(format("givenStoriesEnd", "\n"));
}
public void givenStories(List<String> storyPaths) {
givenStories(new GivenStories(StringUtils.join(storyPaths, ",")));
}
public void scenarioNotAllowed(Scenario scenario, String filter) {
print(format("filter", "{0}\n", filter));
}
public void beforeScenario(String title) {
cause = null;
print(format("beforeScenario", "{0} {1}\n", keywords.scenario(), title));
}
public void scenarioMeta(Meta meta) {
if (!meta.isEmpty()) {
print(meta);
}
}
public void afterScenario() {
if (cause != null && reportFailureTrace) {
print(format("afterScenarioWithFailure", "\n{0}\n", stackTrace(cause)));
} else {
print(format("afterScenario", "\n"));
}
}
private static class Replacement {
private final Pattern from;
private final String to;
private Replacement(Pattern from, String to) {
this.from = from;
this.to = to;
}
}
private static Replacement[] REPLACEMENTS = new Replacement[]{
new Replacement(
Pattern.compile(
"\\tat sun.reflect.NativeMethodAccessorImpl.invoke0\\(Native Method\\)\\n" +
"\\tat sun.reflect.NativeMethodAccessorImpl.invoke\\(NativeMethodAccessorImpl.java:\\d+\\)\\n" +
"\\tat sun.reflect.DelegatingMethodAccessorImpl.invoke\\(DelegatingMethodAccessorImpl.java:\\d+\\)\\n" +
"\\tat java.lang.reflect.Method.invoke\\(Method.java:\\d+\\)"),
"\t(reflection-invoke)"),
new Replacement(
Pattern.compile(
"\\tat org.codehaus.groovy.reflection.CachedMethod.invoke\\(CachedMethod.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.metaclass.ClosureMetaMethod.invoke\\(ClosureMetaMethod.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite\\$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke\\(PojoMetaMethodSite.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call\\(PojoMetaMethodSite.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall\\(CallSiteArray.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.call\\(AbstractCallSite.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.call\\(AbstractCallSite.java:\\d+\\)"),
"\t(groovy-closure-invoke)"),
new Replacement(
Pattern.compile(
"\\tat org.codehaus.groovy.reflection.CachedMethod.invoke\\(CachedMethod.java:\\d+\\)\\n" +
"\\tat groovy.lang.MetaMethod.doMethodInvoke\\(MetaMethod.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod\\(ClosureMetaClass.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnCurrentN\\(ScriptBytecodeAdapter.java:\\d+\\)"),
"\t(groovy-instance-method-invoke)"),
new Replacement(
Pattern.compile(
"\\tat org.codehaus.groovy.reflection.CachedMethod.invoke\\(CachedMethod.java:\\d+\\)\n" +
"\\tat org.codehaus.groovy.runtime.metaclass.ClosureMetaMethod.invoke\\(ClosureMetaMethod.java:\\d+\\)\n" +
"\\tat org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite\\$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke\\(PojoMetaMethodSite.java:\\d+\\)\n" +
"\\tat org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call\\(PojoMetaMethodSite.java:\\d+\\)\n" +
"\\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.call\\(AbstractCallSite.java:\\d+\\)"),
"\t(groovy-abstract-method-invoke)"),
new Replacement(
Pattern.compile(
"\\tat org.codehaus.groovy.reflection.CachedMethod.invoke\\(CachedMethod.java:\\d+\\)\\n" +
"\\tat groovy.lang.MetaMethod.doMethodInvoke\\(MetaMethod.java:\\d+\\)\\n" +
"\\tat groovy.lang.MetaClassImpl.invokeStaticMethod\\(MetaClassImpl.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.InvokerHelper.invokeStaticMethod\\(InvokerHelper.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeStaticMethodN\\(ScriptBytecodeAdapter.java:\\d+\\)"),
"\t(groovy-static-method-invoke)"),
// This one last.
new Replacement(
Pattern.compile(
"\\t\\(reflection\\-invoke\\)\\n" +
"\\t\\(groovy\\-"),
"\t(groovy-")
};
private String stackTrace(Throwable cause) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
cause.printStackTrace(new PrintStream(out));
return stackTrace(out.toString());
}
protected String stackTrace(String stackTrace) {
// don't print past certain parts of the stack. Try them even though they may be redundant.
stackTrace = cutOff(stackTrace, "org.jbehave.core.embedder.");
stackTrace = cutOff(stackTrace, "org.junit.runners.");
stackTrace = cutOff(stackTrace, "org.apache.maven.surefire.");
//System.out.println("=====before>" + stackTrace + "<==========");
// replace whole series of lines with '\t(summary)' The end-user will thank us.
for (Replacement replacement : REPLACEMENTS) {
stackTrace = replacement.from.matcher(stackTrace).replaceAll(replacement.to);
}
return stackTrace;
}
private String cutOff(String stackTrace, String at) {
if (stackTrace.indexOf(at) > -1) {
int ix = stackTrace.indexOf(at);
ix = stackTrace.indexOf("\n", ix);
if (ix != -1) {
stackTrace = stackTrace.substring(0,ix);
}
}
return stackTrace;
}
public void beforeExamples(List<String> steps, ExamplesTable table) {
print(format("beforeExamples", "{0}\n", keywords.examplesTable()));
for (String step : steps) {
print(format("examplesStep", "{0}\n", step));
}
print(table);
}
private void print(ExamplesTable table) {
print(format("examplesTableStart", "\n"));
List<Map<String, String>> rows = table.getRows();
List<String> headers = table.getHeaders();
print(format("examplesTableHeadStart", "|"));
for (String header : headers) {
print(format("examplesTableHeadCell", "{0}|", header));
}
print(format("examplesTableHeadEnd", "\n"));
print(format("examplesTableBodyStart", EMPTY));
for (Map<String, String> row : rows) {
print(format("examplesTableRowStart", "|"));
for (String header : headers) {
print(format("examplesTableCell", "{0}|", row.get(header)));
}
print(format("examplesTableRowEnd", "\n"));
}
print(format("examplesTableBodyEnd", "\n"));
print(format("examplesTableEnd", "\n"));
}
public void example(Map<String, String> tableRow) {
print(format("example", "\n{0} {1}\n", keywords.examplesTableRow(), tableRow));
}
public void afterExamples() {
print(format("afterExamples", "\n"));
}
public void dryRun() {
print(format("dryRun", "{0}\n", keywords.dryRun()));
}
/**
* Formats event output by key, usually equal to the method name.
*
* @param key the event key
* @param defaultPattern the default pattern to return if a custom pattern
* is not found
* @param args the args used to format output
* @return A formatted event output
*/
protected String format(String key, String defaultPattern, Object... args) {
return MessageFormat.format(lookupPattern(key, escape(defaultPattern)), escapeAll(args));
}
private String escape(String defaultPattern) {
return (String) escapeAll(defaultPattern)[0];
}
private Object[] escapeAll(Object... args) {
return escape(format, args);
}
/**
* Escapes args' string values according to format
*
* @param format the Format used by the PrintStream
* @param args the array of args to escape
* @return The cloned and escaped array of args
*/
protected Object[] escape(final Format format, Object... args) {
// Transformer that escapes HTML and XML strings
Transformer escapingTransformer = new Transformer( ) {
public Object transform(Object object) {
switch ( format ){
case HTML: return escapeHtml(asString(object));
case XML: return escapeXml(asString(object));
default: return object;
}
}
private String asString(Object object) {
return ( object != null ? object.toString() : EMPTY );
}
};
List<?> list = Arrays.asList( ArrayUtils.clone( args ) );
CollectionUtils.transform( list, escapingTransformer );
return list.toArray();
}
/**
* Looks up the format pattern for the event output by key, conventionally
* equal to the method name. The pattern is used by the
* {#format(String,String,Object...)} method and by default is formatted
* using the {@link MessageFormat#format(String, Object...)} method. If no pattern is found
* for key or needs to be overridden, the default pattern should be
* returned.
*
* @param key the format pattern key
* @param defaultPattern the default pattern if no pattern is
* @return The format patter for the given key
*/
protected String lookupPattern(String key, String defaultPattern) {
if (outputPatterns.containsKey(key)) {
return outputPatterns.getProperty(key);
}
return defaultPattern;
}
public PrintStreamOutput doReportFailureTrace(boolean reportFailureTrace){
this.reportFailureTrace = reportFailureTrace;
return this;
}
/**
* Prints text to output stream, replacing parameter start and end placeholders
*
* @param text the String to print
*/
protected void print(String text) {
output.print(text.replace(format(PARAMETER_VALUE_START, PARAMETER_VALUE_START), format("parameterValueStart", EMPTY))
.replace(format(PARAMETER_VALUE_END, PARAMETER_VALUE_END), format("parameterValueEnd", EMPTY))
.replace(format(PARAMETER_VALUE_NEWLINE, PARAMETER_VALUE_NEWLINE), format("parameterValueNewline", "\n")));
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
protected void overwritePattern(String key, String pattern) {
outputPatterns.put(key, pattern);
}
}
| jbehave-core/src/main/java/org/jbehave/core/reporters/PrintStreamOutput.java | package org.jbehave.core.reporters;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.jbehave.core.configuration.Keywords;
import org.jbehave.core.failures.UUIDExceptionWrapper;
import org.jbehave.core.model.ExamplesTable;
import org.jbehave.core.model.GivenStories;
import org.jbehave.core.model.GivenStory;
import org.jbehave.core.model.Meta;
import org.jbehave.core.model.Narrative;
import org.jbehave.core.model.OutcomesTable;
import org.jbehave.core.model.OutcomesTable.Outcome;
import org.jbehave.core.model.Scenario;
import org.jbehave.core.model.Story;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;
import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
import static org.apache.commons.lang.StringEscapeUtils.escapeXml;
import static org.jbehave.core.steps.StepCreator.PARAMETER_VALUE_END;
import static org.jbehave.core.steps.StepCreator.PARAMETER_VALUE_NEWLINE;
import static org.jbehave.core.steps.StepCreator.PARAMETER_VALUE_START;
/**
* <p>
* Abstract story reporter that outputs to a PrintStream.
* </p>
* <p>
* The output of the reported event is configurable via:
* <ul>
* <li>custom output patterns, providing only the patterns that differ from
* default</li>
* <li>keywords localised for different languages, providing the i18n Locale</li>
* <li>flag to report failure trace</li>
* </ul>
* </p>
* <p>
* Let's look at example of providing custom output patterns, e.g. for the
* failed event. <br/>
* we'd need to provide the custom pattern, say we want to have something like
* "(step being executed) <<< FAILED", keyed on the method name:
*
* <pre>
* Properties patterns = new Properties();
* patterns.setProperty("failed", "{0} <<< {1}");
* </pre>
*
* The pattern is by default processed and formatted by the
* {@link MessageFormat}. Both the {@link #format(String key, String defaultPattern, Object... args)} and
* {@link #lookupPattern(String key, String defaultPattern)} methods are override-able and a different formatter
* or pattern lookup can be used by subclasses.
* </p>
* <p>
* If the keyword "FAILED" (or any other keyword used by the reporter) needs to
* be expressed in a different language, all we need to do is to provide an
* instance of {@link org.jbehave.core.i18n.LocalizedKeywords} using the appropriate {@link Locale}, e.g.
*
* <pre>
* Keywords keywords = new LocalizedKeywords(new Locale("it"));
* </pre>
*
* </p>
*/
public abstract class PrintStreamOutput implements StoryReporter {
private static final String EMPTY = "";
public enum Format { TXT, HTML, XML }
private final Format format;
private final PrintStream output;
private final Properties outputPatterns;
private final Keywords keywords;
private boolean reportFailureTrace;
private Throwable cause;
protected PrintStreamOutput(Format format, PrintStream output, Properties outputPatterns,
Keywords keywords, boolean reportFailureTrace) {
this.format = format;
this.output = output;
this.outputPatterns = outputPatterns;
this.keywords = keywords;
this.reportFailureTrace = reportFailureTrace;
}
public void successful(String step) {
print(format("successful", "{0}\n", step));
}
public void ignorable(String step) {
print(format("ignorable", "{0}\n", step));
}
public void pending(String step) {
print(format("pending", "{0} ({1})\n", step, keywords.pending()));
}
public void notPerformed(String step) {
print(format("notPerformed", "{0} ({1})\n", step, keywords.notPerformed()));
}
public void failed(String step, Throwable storyFailure) {
// storyFailure be used if a subclass has rewritten the "failed" pattern to have a {3} as WebDriverHtmlOutput (jbehave-web) does.
if (storyFailure instanceof UUIDExceptionWrapper) {
this.cause = storyFailure.getCause();
print(format("failed", "{0} ({1})\n({2})\n", step, keywords.failed(), storyFailure.getCause(), ((UUIDExceptionWrapper) storyFailure).getUUID()));
} else {
throw new ClassCastException("field storyFailure should be an instance of UUIDExceptionWrapper, but is not.");
}
}
public void failedOutcomes(String step, OutcomesTable table) {
failed(step, table.failureCause());
print(table);
}
private void print(OutcomesTable table) {
print(format("outcomesTableStart", "\n"));
List<Outcome<?>> rows = table.getOutcomes();
print(format("outcomesTableHeadStart", "|"));
//TODO i18n outcome fields
for (String field : table.getOutcomeFields()) {
print(format("outcomesTableHeadCell", "{0}|", field));
}
print(format("outcomesTableHeadEnd", "\n"));
print(format("outcomesTableBodyStart", EMPTY));
for (Outcome<?> outcome : rows) {
print(format("outcomesTableRowStart", "|", outcome.isVerified()?"verified":"notVerified"));
print(format("outcomesTableCell", "{0}|", outcome.getDescription()));
print(format("outcomesTableCell", "{0}|", outcome.getValue()));
print(format("outcomesTableCell", "{0}|", outcome.getMatcher()));
print(format("outcomesTableCell", "{0}|", outcome.isVerified()));
print(format("outcomesTableRowEnd", "\n"));
}
print(format("outcomesTableBodyEnd", "\n"));
print(format("outcomesTableEnd", "\n"));
}
public void storyNotAllowed(Story story, String filter) {
print(format("filter", "{0}\n", filter));
}
public void beforeStory(Story story, boolean givenStory) {
print(format("beforeStory", "{0}\n({1})\n", story.getDescription().asString(), story.getPath()));
if (!story.getMeta().isEmpty()) {
Meta meta = story.getMeta();
print(meta);
}
}
public void narrative(Narrative narrative) {
if (!narrative.isEmpty()) {
print(format("narrative", "{0}\n{1} {2}\n{3} {4}\n{5} {6}\n", keywords.narrative(), keywords.inOrderTo(),
narrative.inOrderTo(), keywords.asA(), narrative.asA(), keywords.iWantTo(), narrative.iWantTo()));
}
}
private void print(Meta meta) {
print(format("metaStart", "{0}\n", keywords.meta()));
for (String name : meta.getPropertyNames() ){
print(format("metaProperty", "{0}{1} {2}", keywords.metaProperty(), name, meta.getProperty(name)));
}
print(format("metaEnd", "\n"));
}
public void afterStory(boolean givenStory) {
print(format("afterStory", "\n"));
}
public void givenStories(GivenStories givenStories) {
print(format("givenStoriesStart", "{0}\n", keywords.givenStories()));
for (GivenStory givenStory : givenStories.getStories()) {
print(format("givenStory", "{0} {1}\n", givenStory.asString(), (givenStory.hasAnchor() ? givenStory.getParameters() : "")));
}
print(format("givenStoriesEnd", "\n"));
}
public void givenStories(List<String> storyPaths) {
givenStories(new GivenStories(StringUtils.join(storyPaths, ",")));
}
public void scenarioNotAllowed(Scenario scenario, String filter) {
print(format("filter", "{0}\n", filter));
}
public void beforeScenario(String title) {
cause = null;
print(format("beforeScenario", "{0} {1}\n", keywords.scenario(), title));
}
public void scenarioMeta(Meta meta) {
if (!meta.isEmpty()) {
print(meta);
}
}
public void afterScenario() {
if (cause != null && reportFailureTrace) {
print(format("afterScenarioWithFailure", "\n{0}\n", stackTrace(cause)));
} else {
print(format("afterScenario", "\n"));
}
}
private static class Replacement {
private final Pattern from;
private final String to;
private Replacement(Pattern from, String to) {
this.from = from;
this.to = to;
}
}
private static Replacement[] REPLACEMENTS = new Replacement[]{
new Replacement(
Pattern.compile(
"\\tat sun.reflect.NativeMethodAccessorImpl.invoke0\\(Native Method\\)\\n" +
"\\tat sun.reflect.NativeMethodAccessorImpl.invoke\\(NativeMethodAccessorImpl.java:\\d+\\)\\n" +
"\\tat sun.reflect.DelegatingMethodAccessorImpl.invoke\\(DelegatingMethodAccessorImpl.java:\\d+\\)\\n" +
"\\tat java.lang.reflect.Method.invoke\\(Method.java:\\d+\\)"),
"\t(reflection-invoke)"),
new Replacement(
Pattern.compile(
"\\tat org.codehaus.groovy.reflection.CachedMethod.invoke\\(CachedMethod.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.metaclass.ClosureMetaMethod.invoke\\(ClosureMetaMethod.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite\\$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke\\(PojoMetaMethodSite.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call\\(PojoMetaMethodSite.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall\\(CallSiteArray.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.call\\(AbstractCallSite.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.call\\(AbstractCallSite.java:\\d+\\)"),
"\t(groovy-closure-invoke)"),
new Replacement(
Pattern.compile(
"\\tat org.codehaus.groovy.reflection.CachedMethod.invoke\\(CachedMethod.java:\\d+\\)\\n" +
"\\tat groovy.lang.MetaMethod.doMethodInvoke\\(MetaMethod.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod\\(ClosureMetaClass.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnCurrentN\\(ScriptBytecodeAdapter.java:\\d+\\)"),
"\t(groovy-instance-method-invoke)"),
new Replacement(
Pattern.compile(
"\\tat org.codehaus.groovy.reflection.CachedMethod.invoke\\(CachedMethod.java:\\d+\\)\n" +
"\\tat org.codehaus.groovy.runtime.metaclass.ClosureMetaMethod.invoke\\(ClosureMetaMethod.java:\\d+\\)\n" +
"\\tat org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite\\$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke\\(PojoMetaMethodSite.java:\\d+\\)\n" +
"\\tat org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call\\(PojoMetaMethodSite.java:\\d+\\)\n" +
"\\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.call\\(AbstractCallSite.java:\\d+\\)"),
"\t(groovy-abstract-method-invoke)"),
new Replacement(
Pattern.compile(
"\\tat org.codehaus.groovy.reflection.CachedMethod.invoke\\(CachedMethod.java:\\d+\\)\\n" +
"\\tat groovy.lang.MetaMethod.doMethodInvoke\\(MetaMethod.java:\\d+\\)\\n" +
"\\tat groovy.lang.MetaClassImpl.invokeStaticMethod\\(MetaClassImpl.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.InvokerHelper.invokeStaticMethod\\(InvokerHelper.java:\\d+\\)\\n" +
"\\tat org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeStaticMethodN\\(ScriptBytecodeAdapter.java:\\d+\\)"),
"\t(groovy-static-method-invoke)"),
// This one last.
new Replacement(
Pattern.compile(
"\\t\\(reflection\\-invoke\\)\\n" +
"\\t\\(groovy\\-"),
"\t(groovy-")
};
private String stackTrace(Throwable cause) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
cause.printStackTrace(new PrintStream(out));
return stackTrace(out.toString());
}
protected String stackTrace(String stackTrace) {
// don't print past certain parts of the stack. Try them even though they may be redundant.
stackTrace = cutOff(stackTrace, "org.jbehave.core.embedder.");
stackTrace = cutOff(stackTrace, "org.junit.runners.");
stackTrace = cutOff(stackTrace, "org.apache.maven.surefire.");
//System.out.println("=====before>" + stackTrace + "<==========");
// replace whole series of lines with '\t(summary)' The end-user will thank us.
for (Replacement replacement : REPLACEMENTS) {
stackTrace = replacement.from.matcher(stackTrace).replaceAll(replacement.to);
}
return stackTrace;
}
private String cutOff(String stackTrace, String at) {
if (stackTrace.indexOf(at) > -1) {
int ix = stackTrace.indexOf(at);
ix = stackTrace.indexOf("\n", ix);
if (ix != -1) {
stackTrace = stackTrace.substring(0,ix);
}
}
return stackTrace;
}
public void beforeExamples(List<String> steps, ExamplesTable table) {
print(format("beforeExamples", "{0}\n", keywords.examplesTable()));
for (String step : steps) {
print(format("examplesStep", "{0}\n", step));
}
print(table);
}
private void print(ExamplesTable table) {
print(format("examplesTableStart", "\n"));
List<Map<String, String>> rows = table.getRows();
List<String> headers = table.getHeaders();
print(format("examplesTableHeadStart", "|"));
for (String header : headers) {
print(format("examplesTableHeadCell", "{0}|", header));
}
print(format("examplesTableHeadEnd", "\n"));
print(format("examplesTableBodyStart", EMPTY));
for (Map<String, String> row : rows) {
print(format("examplesTableRowStart", "|"));
for (String header : headers) {
print(format("examplesTableCell", "{0}|", row.get(header)));
}
print(format("examplesTableRowEnd", "\n"));
}
print(format("examplesTableBodyEnd", "\n"));
print(format("examplesTableEnd", "\n"));
}
public void example(Map<String, String> tableRow) {
print(format("example", "\n{0} {1}\n", keywords.examplesTableRow(), tableRow));
}
public void afterExamples() {
print(format("afterExamples", "\n"));
}
public void dryRun() {
print(format("dryRun", "{0}\n", keywords.dryRun()));
}
/**
* Formats event output by key, usually equal to the method name.
*
* @param key the event key
* @param defaultPattern the default pattern to return if a custom pattern
* is not found
* @param args the args used to format output
* @return A formatted event output
*/
protected String format(String key, String defaultPattern, Object... args) {
return MessageFormat.format(lookupPattern(key, escape(defaultPattern)), escapeAll(args));
}
private String escape(String defaultPattern) {
return (String) escapeAll(defaultPattern)[0];
}
private Object[] escapeAll(Object... args) {
return escape(format, args);
}
/**
* Escapes args' string values according to format
*
* @param format the Format used by the PrintStream
* @param args the array of args to escape
* @return The cloned and escaped array of args
*/
protected Object[] escape(final Format format, Object... args) {
// Transformer that escapes HTML and XML strings
Transformer escapingTransformer = new Transformer( ) {
public Object transform(Object object) {
switch ( format ){
case HTML: return escapeHtml(asString(object));
case XML: return escapeXml(asString(object));
default: return object;
}
}
private String asString(Object object) {
return ( object != null ? object.toString() : EMPTY );
}
};
List<?> list = Arrays.asList( ArrayUtils.clone( args ) );
CollectionUtils.transform( list, escapingTransformer );
return list.toArray();
}
/**
* Looks up the format pattern for the event output by key, conventionally
* equal to the method name. The pattern is used by the
* {#format(String,String,Object...)} method and by default is formatted
* using the {@link MessageFormat#format(String, Object...)} method. If no pattern is found
* for key or needs to be overridden, the default pattern should be
* returned.
*
* @param key the format pattern key
* @param defaultPattern the default pattern if no pattern is
* @return The format patter for the given key
*/
protected String lookupPattern(String key, String defaultPattern) {
if (outputPatterns.containsKey(key)) {
return outputPatterns.getProperty(key);
}
return defaultPattern;
}
public PrintStreamOutput doReportFailureTrace(boolean reportFailureTrace){
this.reportFailureTrace = reportFailureTrace;
return this;
}
/**
* Prints text to output stream, replacing parameter start and end placeholders
*
* @param text the String to print
*/
protected void print(String text) {
output.print(text.replace(format(PARAMETER_VALUE_START, PARAMETER_VALUE_START), format("parameterValueStart", EMPTY))
.replace(format(PARAMETER_VALUE_END, PARAMETER_VALUE_END), format("parameterValueEnd", EMPTY))
.replace(format(PARAMETER_VALUE_NEWLINE, PARAMETER_VALUE_NEWLINE), format("parameterValueNewline", "\n")));
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
protected void overwritePattern(String key, String pattern) {
outputPatterns.put(key, pattern);
}
}
| Updated class cast exception message to include the type of the wrong story failure.
| jbehave-core/src/main/java/org/jbehave/core/reporters/PrintStreamOutput.java | Updated class cast exception message to include the type of the wrong story failure. | <ide><path>behave-core/src/main/java/org/jbehave/core/reporters/PrintStreamOutput.java
<ide> this.cause = storyFailure.getCause();
<ide> print(format("failed", "{0} ({1})\n({2})\n", step, keywords.failed(), storyFailure.getCause(), ((UUIDExceptionWrapper) storyFailure).getUUID()));
<ide> } else {
<del> throw new ClassCastException("field storyFailure should be an instance of UUIDExceptionWrapper, but is not.");
<add> throw new ClassCastException(storyFailure +" should be an instance of UUIDExceptionWrapper");
<ide> }
<ide> }
<ide> |
|
Java | bsd-3-clause | 6184e3879f2a7eddc7078e86f480bec3f7d4d1d3 | 0 | NCIP/cananolab,NCIP/cananolab,NCIP/cananolab | package gov.nih.nci.cananolab.service.customsearch.helper;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import gov.nih.nci.cananolab.restful.customsearch.bean.CustomSearchBean;
import gov.nih.nci.cananolab.service.BaseServiceHelper;
import gov.nih.nci.cananolab.service.protocol.ProtocolService;
import gov.nih.nci.cananolab.service.protocol.impl.ProtocolServiceLocalImpl;
import gov.nih.nci.cananolab.service.publication.PublicationService;
import gov.nih.nci.cananolab.service.publication.impl.PublicationServiceLocalImpl;
import gov.nih.nci.cananolab.service.sample.SampleService;
import gov.nih.nci.cananolab.service.sample.impl.SampleServiceLocalImpl;
import gov.nih.nci.cananolab.service.security.SecurityService;
import gov.nih.nci.cananolab.service.security.UserBean;
import gov.nih.nci.cananolab.util.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.FSDirectory;
public class CustomSearchServiceHelper extends BaseServiceHelper {
private static Logger logger = Logger
.getLogger(CustomSearchServiceHelper.class);
SecurityService securityService = getSecurityService();
public CustomSearchServiceHelper() {
super();
}
public CustomSearchServiceHelper(UserBean user) {
super(user);
}
public CustomSearchServiceHelper(SecurityService securityService) {
super(securityService);
}
public List<CustomSearchBean> customSearchByKeywordByProtocol(HttpServletRequest httpRequest, String keyword) {
List<CustomSearchBean> results = null;
UserBean user = (UserBean) (httpRequest.getSession().getAttribute("user"));
try {
ProtocolService protocolService = getProtocolServiceInSession(httpRequest, securityService);
results = new ArrayList<CustomSearchBean>();
IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File("indexDir"))));
QueryParser parser = new QueryParser("content", new StandardAnalyzer());
Query query = parser.parse(keyword);
TopDocs topDocs = searcher.search(query, 1000);
ScoreDoc[] hits = topDocs.scoreDocs;
for (int i = 0; i < hits.length; i++) {
Document doc = searcher.doc(hits[i].doc);
CustomSearchBean searchBean = new CustomSearchBean();
searchBean.setId(doc.get("protocolId"));
searchBean.setName(doc.get("protocolName"));
searchBean.setType("protocol");
searchBean.setDescription(doc.get("protocolFileDesc"));
searchBean.setFileId(doc.get("protocolFileId"));
searchBean.setCreatedDate(doc.get("createdDate"));
if(user!=null){
if(user.isCurator()){
searchBean.setEditable(true);
}
else{
List<String> protoIds = protocolService.findProtocolIdsByOwner(user.getLoginName());
if((searchBean.getId()!=null)&&(StringUtils.containsIgnoreCase(protoIds,
searchBean.getId()))){
searchBean.setEditable(true);
}else{
searchBean.setEditable(false);
}
}
}
results.add(searchBean);
}
}catch(Exception e){
e.printStackTrace();
}
return results;
}
public List<CustomSearchBean> customSearchByKeywordBySample(HttpServletRequest httpRequest, String keyword) {
List<CustomSearchBean> results = null;
UserBean user = (UserBean) (httpRequest.getSession().getAttribute("user"));
try {
SampleService sampleService = this.getSampleServiceInSession(httpRequest, securityService);
results = new ArrayList<CustomSearchBean>();
IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File("indexDir"))));
QueryParser parser = new QueryParser("content", new StandardAnalyzer());
Query query = parser.parse(keyword);
TopDocs topDocs = searcher.search(query, 100);
ScoreDoc[] hits = topDocs.scoreDocs;
for (int i = 0; i < hits.length; i++) {
Document doc = searcher.doc(hits[i].doc);
CustomSearchBean searchBean = new CustomSearchBean();
searchBean.setId(doc.get("sampleId"));
searchBean.setName(doc.get("sampleName"));
searchBean.setType("sample");
searchBean.setDescription(doc.get("nanoEntityDesc"));
searchBean.setCreatedDate(doc.get("createdDate"));
if(user!=null){
if(user.isCurator()){
searchBean.setEditable(true);
}
else{
List<String> sampleIds = sampleService.findSampleIdsByOwner(user.getLoginName());
if((searchBean.getId()!=null)&&(StringUtils.containsIgnoreCase(sampleIds,
searchBean.getId()))){
searchBean.setEditable(true);
}else{
searchBean.setEditable(false);
}
}
}
results.add(searchBean);
}
}catch(Exception e){
e.printStackTrace();
}
return results;
}
public List<CustomSearchBean> customSearchByKeywordByPub(HttpServletRequest httpRequest, String keyword) {
List<CustomSearchBean> results = null;
UserBean user = (UserBean) (httpRequest.getSession().getAttribute("user"));
try {
PublicationService publicationService = this.getPublicationServiceInSession(httpRequest, securityService);
results = new ArrayList<CustomSearchBean>();
IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File("indexDir"))));
QueryParser parser = new QueryParser("content", new StandardAnalyzer());
Query query = parser.parse(keyword);
TopDocs topDocs = searcher.search(query, 100);
ScoreDoc[] hits = topDocs.scoreDocs;
for (int i = 0; i < hits.length; i++) {
Document doc = searcher.doc(hits[i].doc);
CustomSearchBean searchBean = new CustomSearchBean();
searchBean.setId(doc.get("publicationId"));
searchBean.setName(doc.get("pubTitle"));
searchBean.setType("publication");
searchBean.setDescription(doc.get("pubDesc"));
searchBean.setPubmedId(doc.get("pubmedId"));
searchBean.setCreatedDate(doc.get("createdDate"));
if(user!=null){
if(user.isCurator()){
searchBean.setEditable(true);
}
else{
List<String> publicationIds = publicationService.findPublicationIdsByOwner(user.getLoginName());
if((searchBean.getId()!=null)&&(StringUtils.containsIgnoreCase(publicationIds,
searchBean.getId()))){
searchBean.setEditable(true);
}else{
searchBean.setEditable(false);
}
}
}
results.add(searchBean);
}
}catch(Exception e){
e.printStackTrace();
}
return results;
}
private SampleService getSampleServiceInSession(HttpServletRequest request, SecurityService securityService) {
SampleService sampleService = (SampleService)request.getSession().getAttribute("sampleService");
if (sampleService == null) {
sampleService = new SampleServiceLocalImpl(securityService);
request.getSession().setAttribute("sampleService", sampleService);
}
return sampleService;
}
private PublicationService getPublicationServiceInSession(HttpServletRequest request, SecurityService securityService)
throws Exception {
PublicationService publicationService = (PublicationService)request.getSession().getAttribute("publicationService");
if (publicationService == null) {
publicationService = new PublicationServiceLocalImpl(securityService);
request.getSession().setAttribute("publicationService", publicationService);
}
return publicationService;
}
private ProtocolService getProtocolServiceInSession(HttpServletRequest request, SecurityService securityService)
throws Exception {
ProtocolService protocolService = (ProtocolService)request.getSession().getAttribute("protocolService");
if (protocolService == null) {
protocolService = new ProtocolServiceLocalImpl(securityService);
request.getSession().setAttribute("protocolService", protocolService);
}
return protocolService;
}
}
| software/cananolab-webapp/src/gov/nih/nci/cananolab/service/customsearch/helper/CustomSearchServiceHelper.java | package gov.nih.nci.cananolab.service.customsearch.helper;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import gov.nih.nci.cananolab.restful.customsearch.bean.CustomSearchBean;
import gov.nih.nci.cananolab.service.BaseServiceHelper;
import gov.nih.nci.cananolab.service.security.SecurityService;
import gov.nih.nci.cananolab.service.security.UserBean;
import gov.nih.nci.cananolab.util.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.FSDirectory;
public class CustomSearchServiceHelper extends BaseServiceHelper {
private static Logger logger = Logger
.getLogger(CustomSearchServiceHelper.class);
public CustomSearchServiceHelper() {
super();
}
public CustomSearchServiceHelper(UserBean user) {
super(user);
}
public CustomSearchServiceHelper(SecurityService securityService) {
super(securityService);
}
public List<CustomSearchBean> customSearchByKeywordByProtocol(HttpServletRequest httpRequest, String keyword) {
List<CustomSearchBean> results = null;
UserBean user = (UserBean) (httpRequest.getSession().getAttribute("user"));
try {
results = new ArrayList<CustomSearchBean>();
IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File("indexDir"))));
QueryParser parser = new QueryParser("content", new StandardAnalyzer());
Query query = parser.parse(keyword);
TopDocs topDocs = searcher.search(query, 1000);
ScoreDoc[] hits = topDocs.scoreDocs;
for (int i = 0; i < hits.length; i++) {
Document doc = searcher.doc(hits[i].doc);
CustomSearchBean searchBean = new CustomSearchBean();
searchBean.setId(doc.get("protocolId"));
searchBean.setName(doc.get("protocolName"));
searchBean.setType("protocol");
searchBean.setDescription(doc.get("protocolFileDesc"));
searchBean.setFileId(doc.get("protocolFileId"));
searchBean.setCreatedDate(doc.get("createdDate"));
if((user!=null)&&(user.isCurator())){
searchBean.setEditable(true);
}
results.add(searchBean);
}
}catch(Exception e){
e.printStackTrace();
}
return results;
}
public List<CustomSearchBean> customSearchByKeywordBySample(HttpServletRequest httpRequest, String keyword) {
List<CustomSearchBean> results = null;
UserBean user = (UserBean) (httpRequest.getSession().getAttribute("user"));
try {
results = new ArrayList<CustomSearchBean>();
IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File("indexDir"))));
QueryParser parser = new QueryParser("content", new StandardAnalyzer());
Query query = parser.parse(keyword);
TopDocs topDocs = searcher.search(query, 100);
ScoreDoc[] hits = topDocs.scoreDocs;
for (int i = 0; i < hits.length; i++) {
Document doc = searcher.doc(hits[i].doc);
CustomSearchBean searchBean = new CustomSearchBean();
searchBean.setId(doc.get("sampleId"));
searchBean.setName(doc.get("sampleName"));
searchBean.setType("sample");
searchBean.setDescription(doc.get("nanoEntityDesc"));
searchBean.setCreatedDate(doc.get("createdDate"));
if((user!=null)&&(user.isCurator())){
searchBean.setEditable(true);
}
results.add(searchBean);
}
}catch(Exception e){
e.printStackTrace();
}
return results;
}
public List<CustomSearchBean> customSearchByKeywordByPub(HttpServletRequest httpRequest, String keyword) {
List<CustomSearchBean> results = null;
UserBean user = (UserBean) (httpRequest.getSession().getAttribute("user"));
try {
results = new ArrayList<CustomSearchBean>();
IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File("indexDir"))));
QueryParser parser = new QueryParser("content", new StandardAnalyzer());
Query query = parser.parse(keyword);
TopDocs topDocs = searcher.search(query, 100);
ScoreDoc[] hits = topDocs.scoreDocs;
for (int i = 0; i < hits.length; i++) {
Document doc = searcher.doc(hits[i].doc);
CustomSearchBean searchBean = new CustomSearchBean();
searchBean.setId(doc.get("publicationId"));
searchBean.setName(doc.get("pubTitle"));
searchBean.setType("publication");
searchBean.setDescription(doc.get("pubDesc"));
searchBean.setPubmedId(doc.get("pubmedId"));
searchBean.setCreatedDate(doc.get("createdDate"));
if((user!=null)&&(user.isCurator())){
searchBean.setEditable(true);
}
results.add(searchBean);
}
}catch(Exception e){
e.printStackTrace();
}
return results;
}
}
| Google like search changes to add View/Edit functionality for
Researchers | software/cananolab-webapp/src/gov/nih/nci/cananolab/service/customsearch/helper/CustomSearchServiceHelper.java | Google like search changes to add View/Edit functionality for Researchers | <ide><path>oftware/cananolab-webapp/src/gov/nih/nci/cananolab/service/customsearch/helper/CustomSearchServiceHelper.java
<ide>
<ide> import gov.nih.nci.cananolab.restful.customsearch.bean.CustomSearchBean;
<ide> import gov.nih.nci.cananolab.service.BaseServiceHelper;
<add>import gov.nih.nci.cananolab.service.protocol.ProtocolService;
<add>import gov.nih.nci.cananolab.service.protocol.impl.ProtocolServiceLocalImpl;
<add>import gov.nih.nci.cananolab.service.publication.PublicationService;
<add>import gov.nih.nci.cananolab.service.publication.impl.PublicationServiceLocalImpl;
<add>import gov.nih.nci.cananolab.service.sample.SampleService;
<add>import gov.nih.nci.cananolab.service.sample.impl.SampleServiceLocalImpl;
<ide> import gov.nih.nci.cananolab.service.security.SecurityService;
<ide> import gov.nih.nci.cananolab.service.security.UserBean;
<ide> import gov.nih.nci.cananolab.util.StringUtils;
<ide> public class CustomSearchServiceHelper extends BaseServiceHelper {
<ide> private static Logger logger = Logger
<ide> .getLogger(CustomSearchServiceHelper.class);
<add> SecurityService securityService = getSecurityService();
<ide>
<ide> public CustomSearchServiceHelper() {
<ide> super();
<ide> List<CustomSearchBean> results = null;
<ide> UserBean user = (UserBean) (httpRequest.getSession().getAttribute("user"));
<ide> try {
<add> ProtocolService protocolService = getProtocolServiceInSession(httpRequest, securityService);
<add>
<ide> results = new ArrayList<CustomSearchBean>();
<ide>
<ide> IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File("indexDir"))));
<ide> searchBean.setType("protocol");
<ide> searchBean.setDescription(doc.get("protocolFileDesc"));
<ide> searchBean.setFileId(doc.get("protocolFileId"));
<del> searchBean.setCreatedDate(doc.get("createdDate"));
<del> if((user!=null)&&(user.isCurator())){
<del> searchBean.setEditable(true);
<add> searchBean.setCreatedDate(doc.get("createdDate"));
<add> if(user!=null){
<add> if(user.isCurator()){
<add> searchBean.setEditable(true);
<add> }
<add> else{
<add> List<String> protoIds = protocolService.findProtocolIdsByOwner(user.getLoginName());
<add> if((searchBean.getId()!=null)&&(StringUtils.containsIgnoreCase(protoIds,
<add> searchBean.getId()))){
<add> searchBean.setEditable(true);
<add> }else{
<add> searchBean.setEditable(false);
<add> }
<add> }
<ide> }
<ide> results.add(searchBean);
<ide> }
<ide> List<CustomSearchBean> results = null;
<ide> UserBean user = (UserBean) (httpRequest.getSession().getAttribute("user"));
<ide> try {
<add> SampleService sampleService = this.getSampleServiceInSession(httpRequest, securityService);
<ide> results = new ArrayList<CustomSearchBean>();
<ide>
<ide> IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File("indexDir"))));
<ide> searchBean.setType("sample");
<ide> searchBean.setDescription(doc.get("nanoEntityDesc"));
<ide> searchBean.setCreatedDate(doc.get("createdDate"));
<del> if((user!=null)&&(user.isCurator())){
<del> searchBean.setEditable(true);
<add> if(user!=null){
<add> if(user.isCurator()){
<add> searchBean.setEditable(true);
<add> }
<add> else{
<add> List<String> sampleIds = sampleService.findSampleIdsByOwner(user.getLoginName());
<add> if((searchBean.getId()!=null)&&(StringUtils.containsIgnoreCase(sampleIds,
<add> searchBean.getId()))){
<add> searchBean.setEditable(true);
<add> }else{
<add> searchBean.setEditable(false);
<add> }
<add> }
<ide> }
<ide> results.add(searchBean);
<ide> }
<ide> public List<CustomSearchBean> customSearchByKeywordByPub(HttpServletRequest httpRequest, String keyword) {
<ide> List<CustomSearchBean> results = null;
<ide> UserBean user = (UserBean) (httpRequest.getSession().getAttribute("user"));
<add>
<ide> try {
<add>
<add> PublicationService publicationService = this.getPublicationServiceInSession(httpRequest, securityService);
<ide> results = new ArrayList<CustomSearchBean>();
<ide>
<ide> IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(FSDirectory.open(new File("indexDir"))));
<ide> searchBean.setDescription(doc.get("pubDesc"));
<ide> searchBean.setPubmedId(doc.get("pubmedId"));
<ide> searchBean.setCreatedDate(doc.get("createdDate"));
<del> if((user!=null)&&(user.isCurator())){
<del> searchBean.setEditable(true);
<add> if(user!=null){
<add> if(user.isCurator()){
<add> searchBean.setEditable(true);
<add> }
<add> else{
<add> List<String> publicationIds = publicationService.findPublicationIdsByOwner(user.getLoginName());
<add> if((searchBean.getId()!=null)&&(StringUtils.containsIgnoreCase(publicationIds,
<add> searchBean.getId()))){
<add> searchBean.setEditable(true);
<add> }else{
<add> searchBean.setEditable(false);
<add> }
<add> }
<ide> }
<ide> results.add(searchBean);
<ide> }
<ide> }
<ide> return results;
<ide> }
<add>
<add> private SampleService getSampleServiceInSession(HttpServletRequest request, SecurityService securityService) {
<add>
<add> SampleService sampleService = (SampleService)request.getSession().getAttribute("sampleService");
<add> if (sampleService == null) {
<add> sampleService = new SampleServiceLocalImpl(securityService);
<add> request.getSession().setAttribute("sampleService", sampleService);
<add> }
<add> return sampleService;
<add>
<add> }
<add>
<add> private PublicationService getPublicationServiceInSession(HttpServletRequest request, SecurityService securityService)
<add> throws Exception {
<add> PublicationService publicationService = (PublicationService)request.getSession().getAttribute("publicationService");
<add>
<add> if (publicationService == null) {
<add> publicationService = new PublicationServiceLocalImpl(securityService);
<add> request.getSession().setAttribute("publicationService", publicationService);
<add> }
<add> return publicationService;
<add> }
<add>
<add> private ProtocolService getProtocolServiceInSession(HttpServletRequest request, SecurityService securityService)
<add> throws Exception {
<add>
<add> ProtocolService protocolService = (ProtocolService)request.getSession().getAttribute("protocolService");
<add> if (protocolService == null) {
<add> protocolService = new ProtocolServiceLocalImpl(securityService);
<add> request.getSession().setAttribute("protocolService", protocolService);
<add> }
<add> return protocolService;
<add> }
<ide> } |
|
Java | apache-2.0 | 063b72ad19b7e196d90d1c6ce70bd6230345174e | 0 | caot/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,joewalnes/idea-community,ernestp/consulo,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,joewalnes/idea-community,kool79/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,allotria/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,signed/intellij-community,hurricup/intellij-community,signed/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ernestp/consulo,jagguli/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,slisson/intellij-community,kool79/intellij-community,Lekanich/intellij-community,samthor/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,diorcety/intellij-community,signed/intellij-community,blademainer/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,slisson/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,xfournet/intellij-community,caot/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,idea4bsd/idea4bsd,FHannes/intellij-community,ibinti/intellij-community,ernestp/consulo,apixandru/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,jexp/idea2,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,retomerz/intellij-community,caot/intellij-community,diorcety/intellij-community,slisson/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,kool79/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,ibinti/intellij-community,hurricup/intellij-community,FHannes/intellij-community,blademainer/intellij-community,supersven/intellij-community,asedunov/intellij-community,consulo/consulo,kdwink/intellij-community,gnuhub/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,jagguli/intellij-community,kdwink/intellij-community,kool79/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,jexp/idea2,akosyakov/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,vladmm/intellij-community,izonder/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,fitermay/intellij-community,samthor/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,allotria/intellij-community,allotria/intellij-community,caot/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,caot/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,jexp/idea2,Lekanich/intellij-community,ryano144/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,petteyg/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,clumsy/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,kdwink/intellij-community,robovm/robovm-studio,hurricup/intellij-community,kool79/intellij-community,tmpgit/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,consulo/consulo,supersven/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,fnouama/intellij-community,da1z/intellij-community,allotria/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,kdwink/intellij-community,hurricup/intellij-community,ryano144/intellij-community,joewalnes/idea-community,blademainer/intellij-community,signed/intellij-community,amith01994/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,da1z/intellij-community,wreckJ/intellij-community,supersven/intellij-community,slisson/intellij-community,amith01994/intellij-community,robovm/robovm-studio,hurricup/intellij-community,blademainer/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,xfournet/intellij-community,joewalnes/idea-community,joewalnes/idea-community,muntasirsyed/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,retomerz/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,da1z/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,dslomov/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,signed/intellij-community,apixandru/intellij-community,signed/intellij-community,robovm/robovm-studio,consulo/consulo,mglukhikh/intellij-community,vladmm/intellij-community,izonder/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,semonte/intellij-community,izonder/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,fnouama/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,apixandru/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,fitermay/intellij-community,adedayo/intellij-community,robovm/robovm-studio,holmes/intellij-community,holmes/intellij-community,adedayo/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,apixandru/intellij-community,da1z/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,da1z/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,da1z/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,semonte/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,samthor/intellij-community,fitermay/intellij-community,izonder/intellij-community,joewalnes/idea-community,diorcety/intellij-community,clumsy/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,blademainer/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,caot/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,holmes/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,akosyakov/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,kool79/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,allotria/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,clumsy/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,tmpgit/intellij-community,izonder/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,da1z/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,samthor/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,adedayo/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,robovm/robovm-studio,FHannes/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,slisson/intellij-community,vladmm/intellij-community,ibinti/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,adedayo/intellij-community,diorcety/intellij-community,signed/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,allotria/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,izonder/intellij-community,ernestp/consulo,vvv1559/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,retomerz/intellij-community,holmes/intellij-community,caot/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,consulo/consulo,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,dslomov/intellij-community,clumsy/intellij-community,retomerz/intellij-community,slisson/intellij-community,vladmm/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,signed/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,FHannes/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,fnouama/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,kool79/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,diorcety/intellij-community,jagguli/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,jexp/idea2,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,vladmm/intellij-community,petteyg/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,da1z/intellij-community,kool79/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,ahb0327/intellij-community,caot/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,signed/intellij-community,petteyg/intellij-community,slisson/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,ibinti/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,jexp/idea2,semonte/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,caot/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,wreckJ/intellij-community,fitermay/intellij-community,allotria/intellij-community,clumsy/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,slisson/intellij-community,suncycheng/intellij-community,holmes/intellij-community,xfournet/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,fitermay/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,jexp/idea2,orekyuu/intellij-community,samthor/intellij-community,semonte/intellij-community,ernestp/consulo,michaelgallacher/intellij-community,hurricup/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,samthor/intellij-community,dslomov/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,jexp/idea2,youdonghai/intellij-community,caot/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,jexp/idea2,muntasirsyed/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,joewalnes/idea-community,ryano144/intellij-community,clumsy/intellij-community,samthor/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,blademainer/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,semonte/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,ibinti/intellij-community | /*
* Copyright 2000-2005 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.svn.update;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vcs.AbstractVcsHelper;
import com.intellij.openapi.vcs.FilePath;
import org.jetbrains.idea.svn.SvnBundle;
import org.jetbrains.idea.svn.SvnConfiguration;
import org.jetbrains.idea.svn.SvnVcs;
import org.jetbrains.idea.svn.dialogs.SelectLocationDialog;
import org.jetbrains.idea.svn.history.SvnChangeList;
import org.jetbrains.idea.svn.history.SvnCommittedChangesProvider;
import org.tmatesoft.svn.core.wc.SVNRevision;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SvnUpdateRootOptionsPanel implements SvnPanel{
private TextFieldWithBrowseButton myURLText;
private JCheckBox myRevisionBox;
private TextFieldWithBrowseButton myRevisionText;
private final SvnVcs myVcs;
private JPanel myPanel;
private FilePath myRoot;
private JCheckBox myUpdateToSpecificUrl;
public SvnUpdateRootOptionsPanel(FilePath root, final SvnVcs vcs) {
myRoot = root;
myVcs = vcs;
myURLText.setEditable(true);
myURLText.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
chooseUrl();
}
});
myUpdateToSpecificUrl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (myUpdateToSpecificUrl.isSelected()) {
myURLText.setEnabled(true);
chooseUrl();
} else {
myURLText.setEnabled(false);
}
}
});
myRevisionBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == myRevisionBox) {
myRevisionText.setEnabled(myRevisionBox.isSelected());
if (myRevisionBox.isSelected()) {
if ("".equals(myRevisionText.getText().trim())) {
myRevisionText.setText("HEAD");
}
myRevisionText.getTextField().selectAll();
myRevisionText.requestFocus();
}
}
}
});
myRevisionText.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final Project project = vcs.getProject();
final SvnChangeList repositoryVersion =
AbstractVcsHelper.getInstance(project).chooseCommittedChangeList(new SvnCommittedChangesProvider(project, myURLText.getText()));
if (repositoryVersion != null) {
myRevisionText.setText(String.valueOf(repositoryVersion.getNumber()));
}
}
});
myRevisionText.setText(SVNRevision.HEAD.toString());
myRevisionText.getTextField().selectAll();
myRevisionText.setEnabled(myRevisionBox.isSelected());
myURLText.setEnabled(myUpdateToSpecificUrl.isSelected());
}
private void chooseUrl() {
SelectLocationDialog dialog = new SelectLocationDialog(myVcs.getProject(), myURLText.getText());
dialog.show();
if (dialog.isOK()) {
String selected = dialog.getSelectedURL();
if (selected != null) {
myURLText.setText(selected);
}
}
}
public JPanel getPanel() {
return myPanel;
}
public void reset(final SvnConfiguration configuration) {
final UpdateRootInfo rootInfo = configuration.getUpdateRootInfo(myRoot.getIOFile(), myVcs);
myURLText.setText(rootInfo.getUrlAsString());
myRevisionBox.setSelected(rootInfo.isUpdateToRevision());
myRevisionText.setText(rootInfo.getRevision().getName());
myUpdateToSpecificUrl.setSelected(false);
myRevisionText.setEnabled(myRevisionBox.isSelected());
myURLText.setEnabled(myUpdateToSpecificUrl.isSelected());
}
public void apply(final SvnConfiguration configuration) throws ConfigurationException {
final UpdateRootInfo rootInfo = configuration.getUpdateRootInfo(myRoot.getIOFile(), myVcs);
rootInfo.setUrl(myURLText.getText());
rootInfo.setUpdateToRevision(myRevisionBox.isSelected());
final SVNRevision revision = SVNRevision.parse(myRevisionText.getText());
if (!revision.isValid()) {
throw new ConfigurationException(SvnBundle.message("invalid.svn.revision.error.message", myRevisionText.getText()));
}
rootInfo.setRevision(revision);
}
public boolean canApply() {
return true;
}
}
| plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnUpdateRootOptionsPanel.java | /*
* Copyright 2000-2005 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.svn.update;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vcs.AbstractVcsHelper;
import com.intellij.openapi.vcs.FilePath;
import org.jetbrains.idea.svn.SvnBundle;
import org.jetbrains.idea.svn.SvnConfiguration;
import org.jetbrains.idea.svn.SvnVcs;
import org.jetbrains.idea.svn.dialogs.SelectLocationDialog;
import org.jetbrains.idea.svn.history.SvnChangeList;
import org.jetbrains.idea.svn.history.SvnCommittedChangesProvider;
import org.tmatesoft.svn.core.wc.SVNRevision;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SvnUpdateRootOptionsPanel implements SvnPanel{
private TextFieldWithBrowseButton myURLText;
private JCheckBox myRevisionBox;
private TextFieldWithBrowseButton myRevisionText;
private final SvnVcs myVcs;
private JPanel myPanel;
private FilePath myRoot;
private JCheckBox myUpdateToSpecificUrl;
public SvnUpdateRootOptionsPanel(FilePath root, final SvnVcs vcs) {
myRoot = root;
myVcs = vcs;
myURLText.setEditable(true);
myURLText.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
chooseUrl();
}
});
myUpdateToSpecificUrl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (myUpdateToSpecificUrl.isSelected()) {
myURLText.setEnabled(true);
chooseUrl();
} else {
myURLText.setEnabled(false);
}
}
});
myRevisionBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == myRevisionBox) {
myRevisionText.setEnabled(myRevisionBox.isSelected());
if (myRevisionBox.isSelected()) {
if ("".equals(myRevisionText.getText().trim())) {
myRevisionText.setText("HEAD");
}
myRevisionText.getTextField().selectAll();
myRevisionText.requestFocus();
}
}
}
});
myRevisionText.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final Project project = vcs.getProject();
final SvnChangeList repositoryVersion =
AbstractVcsHelper.getInstance(project).chooseCommittedChangeList(new SvnCommittedChangesProvider(project, myURLText.getText()));
if (repositoryVersion != null) {
myRevisionText.setText(String.valueOf(repositoryVersion.getNumber()));
}
}
});
myRevisionText.setText(SVNRevision.HEAD.toString());
myRevisionText.getTextField().selectAll();
myRevisionText.setEnabled(myRevisionBox.isSelected());
myURLText.setEnabled(false);
}
private void chooseUrl() {
SelectLocationDialog dialog = new SelectLocationDialog(myVcs.getProject(), myURLText.getText());
dialog.show();
if (dialog.isOK()) {
String selected = dialog.getSelectedURL();
if (selected != null) {
myURLText.setText(selected);
}
}
}
public JPanel getPanel() {
return myPanel;
}
public void reset(final SvnConfiguration configuration) {
final UpdateRootInfo rootInfo = configuration.getUpdateRootInfo(myRoot.getIOFile(), myVcs);
myURLText.setText(rootInfo.getUrlAsString());
myRevisionBox.setSelected(rootInfo.isUpdateToRevision());
myRevisionText.setText(rootInfo.getRevision().getName());
myUpdateToSpecificUrl.setSelected(false);
myURLText.setEnabled(false);
}
public void apply(final SvnConfiguration configuration) throws ConfigurationException {
final UpdateRootInfo rootInfo = configuration.getUpdateRootInfo(myRoot.getIOFile(), myVcs);
rootInfo.setUrl(myURLText.getText());
rootInfo.setUpdateToRevision(myRevisionBox.isSelected());
final SVNRevision revision = SVNRevision.parse(myRevisionText.getText());
if (!revision.isValid()) {
throw new ConfigurationException(SvnBundle.message("invalid.svn.revision.error.message", myRevisionText.getText()));
}
rootInfo.setRevision(revision);
}
public boolean canApply() {
return true;
}
}
| enable field correctly (IDEADEV-12513) | plugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnUpdateRootOptionsPanel.java | enable field correctly (IDEADEV-12513) | <ide><path>lugins/svn4idea/src/org/jetbrains/idea/svn/update/SvnUpdateRootOptionsPanel.java
<ide> myRevisionText.setText(SVNRevision.HEAD.toString());
<ide> myRevisionText.getTextField().selectAll();
<ide> myRevisionText.setEnabled(myRevisionBox.isSelected());
<del> myURLText.setEnabled(false);
<add> myURLText.setEnabled(myUpdateToSpecificUrl.isSelected());
<ide> }
<ide>
<ide> private void chooseUrl() {
<ide> myRevisionBox.setSelected(rootInfo.isUpdateToRevision());
<ide> myRevisionText.setText(rootInfo.getRevision().getName());
<ide> myUpdateToSpecificUrl.setSelected(false);
<del> myURLText.setEnabled(false);
<add> myRevisionText.setEnabled(myRevisionBox.isSelected());
<add> myURLText.setEnabled(myUpdateToSpecificUrl.isSelected());
<ide> }
<ide>
<ide> public void apply(final SvnConfiguration configuration) throws ConfigurationException { |
|
Java | apache-2.0 | b5630397cf440e7bee3a3b836fa546a537602b1d | 0 | akira-baruah/bazel,davidzchen/bazel,katre/bazel,davidzchen/bazel,perezd/bazel,katre/bazel,perezd/bazel,ButterflyNetwork/bazel,aehlig/bazel,twitter-forks/bazel,perezd/bazel,safarmer/bazel,dslomov/bazel,safarmer/bazel,twitter-forks/bazel,cushon/bazel,dslomov/bazel,ulfjack/bazel,werkt/bazel,akira-baruah/bazel,twitter-forks/bazel,werkt/bazel,safarmer/bazel,cushon/bazel,safarmer/bazel,dslomov/bazel,meteorcloudy/bazel,dslomov/bazel-windows,dslomov/bazel,meteorcloudy/bazel,akira-baruah/bazel,safarmer/bazel,aehlig/bazel,meteorcloudy/bazel,dslomov/bazel-windows,werkt/bazel,perezd/bazel,perezd/bazel,aehlig/bazel,akira-baruah/bazel,ulfjack/bazel,dslomov/bazel,perezd/bazel,davidzchen/bazel,davidzchen/bazel,bazelbuild/bazel,werkt/bazel,ulfjack/bazel,werkt/bazel,dslomov/bazel,aehlig/bazel,werkt/bazel,dslomov/bazel,meteorcloudy/bazel,ButterflyNetwork/bazel,ButterflyNetwork/bazel,aehlig/bazel,bazelbuild/bazel,bazelbuild/bazel,safarmer/bazel,bazelbuild/bazel,meteorcloudy/bazel,twitter-forks/bazel,twitter-forks/bazel,ulfjack/bazel,meteorcloudy/bazel,bazelbuild/bazel,cushon/bazel,davidzchen/bazel,meteorcloudy/bazel,perezd/bazel,davidzchen/bazel,ButterflyNetwork/bazel,dslomov/bazel-windows,akira-baruah/bazel,davidzchen/bazel,dslomov/bazel-windows,aehlig/bazel,aehlig/bazel,dslomov/bazel-windows,twitter-forks/bazel,cushon/bazel,katre/bazel,akira-baruah/bazel,ulfjack/bazel,cushon/bazel,bazelbuild/bazel,ulfjack/bazel,katre/bazel,ButterflyNetwork/bazel,ButterflyNetwork/bazel,ulfjack/bazel,katre/bazel,cushon/bazel,dslomov/bazel-windows,twitter-forks/bazel,katre/bazel | // Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.buildjar.javac.plugins.dependency;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Iterables.getOnlyElement;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.buildjar.JarOwner;
import com.google.devtools.build.buildjar.javac.plugins.BlazeJavaCompilerPlugin;
import com.google.devtools.build.buildjar.javac.plugins.dependency.DependencyModule.StrictJavaDeps;
import com.google.devtools.build.buildjar.javac.statistics.BlazeJavacStatistics;
import com.google.devtools.build.lib.view.proto.Deps;
import com.google.devtools.build.lib.view.proto.Deps.Dependency;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Kinds;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeInfo;
import com.sun.tools.javac.tree.TreeScanner;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Log.WriterKind;
import com.sun.tools.javac.util.Name;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.util.SimpleAnnotationValueVisitor8;
import javax.tools.JavaFileObject;
/**
* A plugin for BlazeJavaCompiler that checks for types referenced directly in the source, but
* included through transitive dependencies. To get this information, we hook into the type
* attribution phase of the BlazeJavaCompiler (thus the overhead is another tree scan with the
* classic visitor). The constructor takes a map from jar names to target names, only for the jars
* that come from transitive dependencies (Blaze computes this information).
*/
public final class StrictJavaDepsPlugin extends BlazeJavaCompilerPlugin {
private static final Attributes.Name TARGET_LABEL = new Attributes.Name("Target-Label");
private static final Attributes.Name INJECTING_RULE_KIND =
new Attributes.Name("Injecting-Rule-Kind");
private ImplicitDependencyExtractor implicitDependencyExtractor;
private CheckingTreeScanner checkingTreeScanner;
private final DependencyModule dependencyModule;
/** Marks seen compilation toplevels and their import sections */
private final Set<JCTree.JCCompilationUnit> toplevels;
/** Marks seen ASTs */
private final Set<JCTree> trees;
/** Computed missing dependencies */
private final Set<JarOwner> missingTargets;
/** Strict deps diagnostics. */
private final List<SjdDiagnostic> diagnostics;
private PrintWriter errWriter;
@AutoValue
abstract static class SjdDiagnostic {
abstract int pos();
abstract String message();
abstract JavaFileObject source();
static SjdDiagnostic create(int pos, String message, JavaFileObject source) {
return new AutoValue_StrictJavaDepsPlugin_SjdDiagnostic(pos, message, source);
}
}
/**
* On top of javac, we keep Blaze-specific information in the form of two maps. Both map jars
* (exactly as they appear on the classpath) to target names, one is used for direct dependencies,
* the other for the transitive dependencies.
*
* <p>This enables the detection of dependency issues. For instance, when a type com.Foo is
* referenced in the source and it's coming from an indirect dependency, we emit a warning
* flagging that dependency. Also, we can check whether the direct dependencies were actually
* necessary, i.e. if their associated jars were used at all for looking up class definitions.
*/
public StrictJavaDepsPlugin(DependencyModule dependencyModule) {
this.dependencyModule = dependencyModule;
toplevels = new HashSet<>();
trees = new HashSet<>();
missingTargets = new HashSet<>();
diagnostics = new ArrayList<>();
}
@Override
public void init(
Context context,
Log log,
JavaCompiler compiler,
BlazeJavacStatistics.Builder statisticsBuilder) {
super.init(context, log, compiler, statisticsBuilder);
errWriter = log.getWriter(WriterKind.ERROR);
implicitDependencyExtractor =
new ImplicitDependencyExtractor(
dependencyModule.getUsedClasspath(),
dependencyModule.getImplicitDependenciesMap(),
dependencyModule.getPlatformJars());
checkingTreeScanner = context.get(CheckingTreeScanner.class);
if (checkingTreeScanner == null) {
Set<Path> platformJars = dependencyModule.getPlatformJars();
checkingTreeScanner =
new CheckingTreeScanner(dependencyModule, diagnostics, missingTargets, platformJars);
context.put(CheckingTreeScanner.class, checkingTreeScanner);
}
}
/**
* We want to make another pass over the AST and "type-check" the usage of direct/transitive
* dependencies after the type attribution phase.
*/
@Override
public void postAttribute(Env<AttrContext> env) {
JavaFileObject previousSource = checkingTreeScanner.source;
try {
if (isAnnotationProcessorExempt(env.toplevel)) {
return;
}
checkingTreeScanner.source =
env.enclClass.sym.sourcefile != null
? env.enclClass.sym.sourcefile
: env.toplevel.sourcefile;
if (trees.add(env.tree)) {
checkingTreeScanner.scan(env.tree);
}
if (toplevels.add(env.toplevel)) {
checkingTreeScanner.scan(env.toplevel.getImports());
checkingTreeScanner.scan(env.toplevel.getPackage());
dependencyModule.addPackage(env.toplevel.packge);
}
} finally {
checkingTreeScanner.source = previousSource;
}
}
@Override
public void finish() {
implicitDependencyExtractor.accumulate(context, checkingTreeScanner.getSeenClasses());
for (SjdDiagnostic diagnostic : diagnostics) {
JavaFileObject prev = log.useSource(diagnostic.source());
try {
switch (dependencyModule.getStrictJavaDeps()) {
case ERROR:
log.error(diagnostic.pos(), "proc.messager", diagnostic.message());
break;
case WARN:
log.warning(diagnostic.pos(), "proc.messager", diagnostic.message());
break;
case OFF: // continue below
}
} finally {
log.useSource(prev);
}
}
if (!missingTargets.isEmpty()) {
String canonicalizedLabel =
dependencyModule.getTargetLabel() == null
? null
// we don't use the target mapping for the target, just the missing deps
: canonicalizeTarget(dependencyModule.getTargetLabel());
Set<JarOwner> canonicalizedMissing =
missingTargets
.stream()
.filter(owner -> owner.label().isPresent())
.sorted(Comparator.comparing((JarOwner owner) -> owner.label().get()))
// for dependencies that are missing we canonicalize and remap the target so we don't
// suggest private build labels.
.map(owner -> owner.withLabel(owner.label().map(label -> canonicalizeTarget(label))))
.collect(toImmutableSet());
if (dependencyModule.getStrictJavaDeps() != StrictJavaDeps.OFF) {
errWriter.print(
dependencyModule.getFixMessage().get(canonicalizedMissing, canonicalizedLabel));
dependencyModule.setHasMissingTargets();
}
}
}
/**
* An AST visitor that implements our strict_java_deps checks. For now, it only emits warnings for
* types loaded from jar files provided by transitive (indirect) dependencies. Each type is
* considered only once, so at most one warning is generated for it.
*/
private static class CheckingTreeScanner extends TreeScanner {
private final ImmutableSet<Path> directJars;
/** Strict deps diagnostics. */
private final List<SjdDiagnostic> diagnostics;
/** Missing targets */
private final Set<JarOwner> missingTargets;
/** Collect seen direct dependencies and their associated information */
private final Map<Path, Deps.Dependency> directDependenciesMap;
/** We only emit one warning/error per class symbol */
private final Set<ClassSymbol> seenClasses = new HashSet<>();
private final Set<JarOwner> seenTargets = new HashSet<>();
private final Set<Path> seenStrictDepsViolatingJars = new HashSet<>();
/** The set of jars on the compilation bootclasspath. */
private final Set<Path> platformJars;
/** The current source, for diagnostics. */
private JavaFileObject source = null;
public CheckingTreeScanner(
DependencyModule dependencyModule,
List<SjdDiagnostic> diagnostics,
Set<JarOwner> missingTargets,
Set<Path> platformJars) {
this.directJars = dependencyModule.directJars();
this.diagnostics = diagnostics;
this.missingTargets = missingTargets;
this.directDependenciesMap = dependencyModule.getExplicitDependenciesMap();
this.platformJars = platformJars;
}
Set<ClassSymbol> getSeenClasses() {
return seenClasses;
}
/** Checks an AST node denoting a class type against direct/transitive dependencies. */
private void checkTypeLiteral(JCTree node, Symbol sym) {
if (sym == null || sym.kind != Kinds.Kind.TYP) {
return;
}
Path jarPath = getJarPath(sym.enclClass(), platformJars);
// If this type symbol comes from a class file loaded from a jar, check
// whether that jar was a direct dependency and error out otherwise.
if (jarPath != null && seenClasses.add(sym.enclClass())) {
collectExplicitDependency(jarPath, node, sym);
}
}
/**
* Marks the provided dependency as a direct/explicit dependency. Additionally, if
* strict_java_deps is enabled, it emits a [strict] compiler warning/error.
*/
private void collectExplicitDependency(Path jarPath, JCTree node, Symbol sym) {
// Does it make sense to emit a warning/error for this pair of (type, owner)?
// We want to emit only one error/warning per owner.
if (!directJars.contains(jarPath) && seenStrictDepsViolatingJars.add(jarPath)) {
// IO cost here is fine because we only hit this path for an explicit dependency
// _not_ in the direct jars, i.e. an error
JarOwner owner = readJarOwnerFromManifest(jarPath);
if (seenTargets.add(owner)) {
// owner is of the form "//label/of:rule <Aspect name>" where <Aspect name> is
// optional.
Optional<String> canonicalTargetName =
owner.label().map(label -> canonicalizeTarget(label));
missingTargets.add(owner);
String toolInfo =
owner.aspect().isPresent()
? String.format(
"%s wrapped in %s", canonicalTargetName.get(), owner.aspect().get())
: canonicalTargetName.isPresent()
? canonicalTargetName.get()
: owner.jar().toString();
String used =
sym.getSimpleName().contentEquals("package-info")
? "package " + sym.getEnclosingElement()
: "type " + sym;
String message =
String.format(
"[strict] Using %s from an indirect dependency (TOOL_INFO: \"%s\").%s",
used, toolInfo, (owner.label().isPresent() ? " See command below **" : ""));
diagnostics.add(SjdDiagnostic.create(node.pos, message, source));
}
}
if (!directDependenciesMap.containsKey(jarPath)) {
// Also update the dependency proto
Dependency dep =
Dependency.newBuilder()
// Path.toString uses the platform separator (`\` on Windows) which may not
// match the format in params files (which currently always use `/`, see
// bazelbuild/bazel#4108). JavaBuilder should always parse Path strings into
// java.nio.file.Paths before comparing them.
.setPath(jarPath.toString())
.setKind(Dependency.Kind.EXPLICIT)
.build();
directDependenciesMap.put(jarPath, dep);
}
}
private static JarOwner readJarOwnerFromManifest(Path jarPath) {
try (JarFile jarFile = new JarFile(jarPath.toFile())) {
Manifest manifest = jarFile.getManifest();
if (manifest == null) {
return JarOwner.create(jarPath);
}
Attributes attributes = manifest.getMainAttributes();
String label = (String) attributes.get(TARGET_LABEL);
if (label == null) {
return JarOwner.create(jarPath);
}
String injectingRuleKind = (String) attributes.get(INJECTING_RULE_KIND);
return JarOwner.create(jarPath, label, Optional.ofNullable(injectingRuleKind));
} catch (IOException e) {
// This jar file pretty much has to exist, we just used it in the compiler. Throw unchecked.
throw new UncheckedIOException(e);
}
}
@Override
public void visitMethodDef(JCTree.JCMethodDecl method) {
if ((method.mods.flags & Flags.GENERATEDCONSTR) != 0) {
// If this is the constructor for an anonymous inner class, refrain from checking the
// compiler-generated method signature. Don't skip scanning the method body though, there
// might have been an anonymous initializer which still needs to be checked.
scan(method.body);
} else {
super.visitMethodDef(method);
}
}
/** Visits an identifier in the AST. We only care about type symbols. */
@Override
public void visitIdent(JCTree.JCIdent tree) {
checkTypeLiteral(tree, tree.sym);
}
/**
* Visits a field selection in the AST. We care because in some cases types may appear fully
* qualified and only inside a field selection (e.g., "com.foo.Bar.X", we want to catch the
* reference to Bar).
*/
@Override
public void visitSelect(JCTree.JCFieldAccess tree) {
scan(tree.selected);
checkTypeLiteral(tree, tree.sym);
}
@Override
public void visitLambda(JCTree.JCLambda tree) {
if (tree.paramKind != JCTree.JCLambda.ParameterKind.IMPLICIT) {
// don't record type uses for implicitly typed lambda parameters
scan(tree.params);
}
scan(tree.body);
}
@Override
public void visitPackageDef(JCTree.JCPackageDecl tree) {
scan(tree.annotations);
checkTypeLiteral(tree, tree.packge.package_info);
}
}
/**
* Returns true if the compilation unit contains a single top-level class generated by an exempt
* annotation processor (according to its {@link @Generated} annotation).
*
* <p>Annotation processors are expected to never generate more than one top level class, as
* required by the style guide.
*/
public boolean isAnnotationProcessorExempt(JCTree.JCCompilationUnit unit) {
if (unit.getTypeDecls().size() != 1) {
return false;
}
Symbol sym = TreeInfo.symbolFor(getOnlyElement(unit.getTypeDecls()));
if (sym == null) {
return false;
}
for (String value : getGeneratedBy(sym)) {
if (dependencyModule.getExemptGenerators().contains(value)) {
return true;
}
}
return false;
}
private static ImmutableSet<String> getGeneratedBy(Symbol symbol) {
ImmutableSet.Builder<String> suppressions = ImmutableSet.builder();
symbol
.getRawAttributes()
.stream()
.filter(
a -> {
Name name = a.type.tsym.getQualifiedName();
return name.contentEquals("javax.annotation.Generated")
|| name.contentEquals("javax.annotation.processing.Generated");
})
.flatMap(
a ->
a.getElementValues()
.entrySet()
.stream()
.filter(e -> e.getKey().getSimpleName().contentEquals("value"))
.map(e -> e.getValue()))
.forEachOrdered(
a ->
a.accept(
new SimpleAnnotationValueVisitor8<Void, Void>() {
@Override
public Void visitString(String s, Void aVoid) {
suppressions.add(s);
return super.visitString(s, aVoid);
}
@Override
public Void visitArray(List<? extends AnnotationValue> vals, Void aVoid) {
vals.forEach(v -> v.accept(this, null));
return super.visitArray(vals, aVoid);
}
},
null));
return suppressions.build();
}
/** Returns the canonical version of the target name. Package private for testing. */
static String canonicalizeTarget(String target) {
int colonIndex = target.indexOf(':');
if (colonIndex == -1) {
// No ':' in target, nothing to do.
return target;
}
int lastSlash = target.lastIndexOf('/', colonIndex);
if (lastSlash == -1) {
// No '/' or target is actually a filename in label format, return unmodified.
return target;
}
String packageName = target.substring(lastSlash + 1, colonIndex);
String suffix = target.substring(colonIndex + 1);
if (packageName.equals(suffix)) {
// target ends in "/something:something", canonicalize.
return target.substring(0, colonIndex);
}
return target;
}
/**
* Returns the name of the jar file from which the given class symbol was loaded, if available,
* and null otherwise. Implicitly filters out jars from the compilation bootclasspath.
*
* @param platformJars jars on javac's bootclasspath
*/
public static Path getJarPath(ClassSymbol classSymbol, Set<Path> platformJars) {
if (classSymbol == null) {
return null;
}
// Ignore symbols that appear in the sourcepath:
if (haveSourceForSymbol(classSymbol)) {
return null;
}
JavaFileObject classfile = classSymbol.classfile;
Path path = ImplicitDependencyExtractor.getJarPath(classfile);
if (path == null) {
return null;
}
// Filter out classes on bootclasspath
if (platformJars.contains(path)) {
return null;
}
return path;
}
/** Returns true if the given classSymbol corresponds to one of the sources being compiled. */
private static boolean haveSourceForSymbol(ClassSymbol classSymbol) {
if (classSymbol.sourcefile == null) {
return false;
}
try {
// The classreader uses metadata to populate the symbol's sourcefile with a fake file object.
// Call getLastModified() to check if it's a real file:
classSymbol.sourcefile.getLastModified();
} catch (UnsupportedOperationException e) {
return false;
}
return true;
}
@Override
public boolean runOnAttributionErrors() {
return true;
}
}
| src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/plugins/dependency/StrictJavaDepsPlugin.java | // Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.buildjar.javac.plugins.dependency;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Iterables.getOnlyElement;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.buildjar.JarOwner;
import com.google.devtools.build.buildjar.javac.plugins.BlazeJavaCompilerPlugin;
import com.google.devtools.build.buildjar.javac.plugins.dependency.DependencyModule.StrictJavaDeps;
import com.google.devtools.build.buildjar.javac.statistics.BlazeJavacStatistics;
import com.google.devtools.build.lib.view.proto.Deps;
import com.google.devtools.build.lib.view.proto.Deps.Dependency;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Kinds;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeInfo;
import com.sun.tools.javac.tree.TreeScanner;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Log.WriterKind;
import com.sun.tools.javac.util.Name;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.util.SimpleAnnotationValueVisitor8;
import javax.tools.JavaFileObject;
/**
* A plugin for BlazeJavaCompiler that checks for types referenced directly in the source, but
* included through transitive dependencies. To get this information, we hook into the type
* attribution phase of the BlazeJavaCompiler (thus the overhead is another tree scan with the
* classic visitor). The constructor takes a map from jar names to target names, only for the jars
* that come from transitive dependencies (Blaze computes this information).
*/
public final class StrictJavaDepsPlugin extends BlazeJavaCompilerPlugin {
private static final Attributes.Name TARGET_LABEL = new Attributes.Name("Target-Label");
private static final Attributes.Name INJECTING_RULE_KIND =
new Attributes.Name("Injecting-Rule-Kind");
private ImplicitDependencyExtractor implicitDependencyExtractor;
private CheckingTreeScanner checkingTreeScanner;
private final DependencyModule dependencyModule;
/** Marks seen compilation toplevels and their import sections */
private final Set<JCTree.JCCompilationUnit> toplevels;
/** Marks seen ASTs */
private final Set<JCTree> trees;
/** Computed missing dependencies */
private final Set<JarOwner> missingTargets;
/** Strict deps diagnostics. */
private final List<SjdDiagnostic> diagnostics;
private PrintWriter errWriter;
@AutoValue
abstract static class SjdDiagnostic {
abstract int pos();
abstract String message();
abstract JavaFileObject source();
static SjdDiagnostic create(int pos, String message, JavaFileObject source) {
return new AutoValue_StrictJavaDepsPlugin_SjdDiagnostic(pos, message, source);
}
}
/**
* On top of javac, we keep Blaze-specific information in the form of two maps. Both map jars
* (exactly as they appear on the classpath) to target names, one is used for direct dependencies,
* the other for the transitive dependencies.
*
* <p>This enables the detection of dependency issues. For instance, when a type com.Foo is
* referenced in the source and it's coming from an indirect dependency, we emit a warning
* flagging that dependency. Also, we can check whether the direct dependencies were actually
* necessary, i.e. if their associated jars were used at all for looking up class definitions.
*/
public StrictJavaDepsPlugin(DependencyModule dependencyModule) {
this.dependencyModule = dependencyModule;
toplevels = new HashSet<>();
trees = new HashSet<>();
missingTargets = new HashSet<>();
diagnostics = new ArrayList<>();
}
@Override
public void init(
Context context,
Log log,
JavaCompiler compiler,
BlazeJavacStatistics.Builder statisticsBuilder) {
super.init(context, log, compiler, statisticsBuilder);
errWriter = log.getWriter(WriterKind.ERROR);
implicitDependencyExtractor =
new ImplicitDependencyExtractor(
dependencyModule.getUsedClasspath(),
dependencyModule.getImplicitDependenciesMap(),
dependencyModule.getPlatformJars());
checkingTreeScanner = context.get(CheckingTreeScanner.class);
if (checkingTreeScanner == null) {
Set<Path> platformJars = dependencyModule.getPlatformJars();
checkingTreeScanner =
new CheckingTreeScanner(dependencyModule, diagnostics, missingTargets, platformJars);
context.put(CheckingTreeScanner.class, checkingTreeScanner);
}
}
/**
* We want to make another pass over the AST and "type-check" the usage of direct/transitive
* dependencies after the type attribution phase.
*/
@Override
public void postAttribute(Env<AttrContext> env) {
JavaFileObject previousSource = checkingTreeScanner.source;
boolean previousExemption = checkingTreeScanner.isStrictDepsExempt;
try {
ProcessorDependencyMode mode = isAnnotationProcessorExempt(env.toplevel);
if (mode == ProcessorDependencyMode.EXEMPT_NORECORD) {
return;
}
checkingTreeScanner.isStrictDepsExempt |= mode == ProcessorDependencyMode.EXEMPT_RECORD;
checkingTreeScanner.source =
env.enclClass.sym.sourcefile != null
? env.enclClass.sym.sourcefile
: env.toplevel.sourcefile;
if (trees.add(env.tree)) {
checkingTreeScanner.scan(env.tree);
}
if (toplevels.add(env.toplevel)) {
checkingTreeScanner.scan(env.toplevel.getImports());
checkingTreeScanner.scan(env.toplevel.getPackage());
dependencyModule.addPackage(env.toplevel.packge);
}
} finally {
checkingTreeScanner.isStrictDepsExempt = previousExemption;
checkingTreeScanner.source = previousSource;
}
}
@Override
public void finish() {
implicitDependencyExtractor.accumulate(context, checkingTreeScanner.getSeenClasses());
for (SjdDiagnostic diagnostic : diagnostics) {
JavaFileObject prev = log.useSource(diagnostic.source());
try {
switch (dependencyModule.getStrictJavaDeps()) {
case ERROR:
log.error(diagnostic.pos(), "proc.messager", diagnostic.message());
break;
case WARN:
log.warning(diagnostic.pos(), "proc.messager", diagnostic.message());
break;
case OFF: // continue below
}
} finally {
log.useSource(prev);
}
}
if (!missingTargets.isEmpty()) {
String canonicalizedLabel =
dependencyModule.getTargetLabel() == null
? null
// we don't use the target mapping for the target, just the missing deps
: canonicalizeTarget(dependencyModule.getTargetLabel());
Set<JarOwner> canonicalizedMissing =
missingTargets
.stream()
.filter(owner -> owner.label().isPresent())
.sorted(Comparator.comparing((JarOwner owner) -> owner.label().get()))
// for dependencies that are missing we canonicalize and remap the target so we don't
// suggest private build labels.
.map(owner -> owner.withLabel(owner.label().map(label -> canonicalizeTarget(label))))
.collect(toImmutableSet());
if (dependencyModule.getStrictJavaDeps() != StrictJavaDeps.OFF) {
errWriter.print(
dependencyModule.getFixMessage().get(canonicalizedMissing, canonicalizedLabel));
dependencyModule.setHasMissingTargets();
}
}
}
/**
* An AST visitor that implements our strict_java_deps checks. For now, it only emits warnings for
* types loaded from jar files provided by transitive (indirect) dependencies. Each type is
* considered only once, so at most one warning is generated for it.
*/
private static class CheckingTreeScanner extends TreeScanner {
private final ImmutableSet<Path> directJars;
/** Strict deps diagnostics. */
private final List<SjdDiagnostic> diagnostics;
/** Missing targets */
private final Set<JarOwner> missingTargets;
/** Collect seen direct dependencies and their associated information */
private final Map<Path, Deps.Dependency> directDependenciesMap;
/** We only emit one warning/error per class symbol */
private final Set<ClassSymbol> seenClasses = new HashSet<>();
private final Set<JarOwner> seenTargets = new HashSet<>();
private final Set<Path> seenStrictDepsViolatingJars = new HashSet<>();
/** The set of jars on the compilation bootclasspath. */
private final Set<Path> platformJars;
/** Was the node being visited generated by an exempt annotation processor? */
private boolean isStrictDepsExempt = false;
/** The current source, for diagnostics. */
private JavaFileObject source = null;
public CheckingTreeScanner(
DependencyModule dependencyModule,
List<SjdDiagnostic> diagnostics,
Set<JarOwner> missingTargets,
Set<Path> platformJars) {
this.directJars = dependencyModule.directJars();
this.diagnostics = diagnostics;
this.missingTargets = missingTargets;
this.directDependenciesMap = dependencyModule.getExplicitDependenciesMap();
this.platformJars = platformJars;
}
Set<ClassSymbol> getSeenClasses() {
return seenClasses;
}
/** Checks an AST node denoting a class type against direct/transitive dependencies. */
private void checkTypeLiteral(JCTree node, Symbol sym) {
if (sym == null || sym.kind != Kinds.Kind.TYP) {
return;
}
Path jarPath = getJarPath(sym.enclClass(), platformJars);
// If this type symbol comes from a class file loaded from a jar, check
// whether that jar was a direct dependency and error out otherwise.
if (jarPath != null && seenClasses.add(sym.enclClass())) {
collectExplicitDependency(jarPath, node, sym);
}
}
/**
* Marks the provided dependency as a direct/explicit dependency. Additionally, if
* strict_java_deps is enabled, it emits a [strict] compiler warning/error.
*/
private void collectExplicitDependency(Path jarPath, JCTree node, Symbol sym) {
if (!isStrictDepsExempt) {
// Does it make sense to emit a warning/error for this pair of (type, owner)?
// We want to emit only one error/warning per owner.
if (!directJars.contains(jarPath) && seenStrictDepsViolatingJars.add(jarPath)) {
// IO cost here is fine because we only hit this path for an explicit dependency
// _not_ in the direct jars, i.e. an error
JarOwner owner = readJarOwnerFromManifest(jarPath);
if (seenTargets.add(owner)) {
// owner is of the form "//label/of:rule <Aspect name>" where <Aspect name> is
// optional.
Optional<String> canonicalTargetName =
owner.label().map(label -> canonicalizeTarget(label));
missingTargets.add(owner);
String toolInfo =
owner.aspect().isPresent()
? String.format(
"%s wrapped in %s", canonicalTargetName.get(), owner.aspect().get())
: canonicalTargetName.isPresent()
? canonicalTargetName.get()
: owner.jar().toString();
String used =
sym.getSimpleName().contentEquals("package-info")
? "package " + sym.getEnclosingElement()
: "type " + sym;
String message =
String.format(
"[strict] Using %s from an indirect dependency (TOOL_INFO: \"%s\").%s",
used, toolInfo, (owner.label().isPresent() ? " See command below **" : ""));
diagnostics.add(SjdDiagnostic.create(node.pos, message, source));
}
}
}
if (!directDependenciesMap.containsKey(jarPath)) {
// Also update the dependency proto
Dependency dep =
Dependency.newBuilder()
// Path.toString uses the platform separator (`\` on Windows) which may not
// match the format in params files (which currently always use `/`, see
// bazelbuild/bazel#4108). JavaBuilder should always parse Path strings into
// java.nio.file.Paths before comparing them.
.setPath(jarPath.toString())
.setKind(Dependency.Kind.EXPLICIT)
.build();
directDependenciesMap.put(jarPath, dep);
}
}
private static JarOwner readJarOwnerFromManifest(Path jarPath) {
try (JarFile jarFile = new JarFile(jarPath.toFile())) {
Manifest manifest = jarFile.getManifest();
if (manifest == null) {
return JarOwner.create(jarPath);
}
Attributes attributes = manifest.getMainAttributes();
String label = (String) attributes.get(TARGET_LABEL);
if (label == null) {
return JarOwner.create(jarPath);
}
String injectingRuleKind = (String) attributes.get(INJECTING_RULE_KIND);
return JarOwner.create(jarPath, label, Optional.ofNullable(injectingRuleKind));
} catch (IOException e) {
// This jar file pretty much has to exist, we just used it in the compiler. Throw unchecked.
throw new UncheckedIOException(e);
}
}
@Override
public void visitMethodDef(JCTree.JCMethodDecl method) {
if ((method.mods.flags & Flags.GENERATEDCONSTR) != 0) {
// If this is the constructor for an anonymous inner class, refrain from checking the
// compiler-generated method signature. Don't skip scanning the method body though, there
// might have been an anonymous initializer which still needs to be checked.
scan(method.body);
} else {
super.visitMethodDef(method);
}
}
/** Visits an identifier in the AST. We only care about type symbols. */
@Override
public void visitIdent(JCTree.JCIdent tree) {
checkTypeLiteral(tree, tree.sym);
}
/**
* Visits a field selection in the AST. We care because in some cases types may appear fully
* qualified and only inside a field selection (e.g., "com.foo.Bar.X", we want to catch the
* reference to Bar).
*/
@Override
public void visitSelect(JCTree.JCFieldAccess tree) {
scan(tree.selected);
checkTypeLiteral(tree, tree.sym);
}
@Override
public void visitLambda(JCTree.JCLambda tree) {
if (tree.paramKind != JCTree.JCLambda.ParameterKind.IMPLICIT) {
// don't record type uses for implicitly typed lambda parameters
scan(tree.params);
}
scan(tree.body);
}
@Override
public void visitPackageDef(JCTree.JCPackageDecl tree) {
scan(tree.annotations);
checkTypeLiteral(tree, tree.packge.package_info);
}
}
private static final String DAGGER_PROCESSOR_PREFIX = "dagger.";
enum ProcessorDependencyMode {
DEFAULT,
EXEMPT_RECORD,
EXEMPT_NORECORD;
}
/**
* Returns true if the compilation unit contains a single top-level class generated by an exempt
* annotation processor (according to its {@link @Generated} annotation).
*
* <p>Annotation processors are expected to never generate more than one top level class, as
* required by the style guide.
*/
public ProcessorDependencyMode isAnnotationProcessorExempt(JCTree.JCCompilationUnit unit) {
if (unit.getTypeDecls().size() != 1) {
return ProcessorDependencyMode.DEFAULT;
}
Symbol sym = TreeInfo.symbolFor(getOnlyElement(unit.getTypeDecls()));
if (sym == null) {
return ProcessorDependencyMode.DEFAULT;
}
for (String value : getGeneratedBy(sym)) {
// Relax strict deps for dagger-generated code (b/17979436).
if (value.startsWith(DAGGER_PROCESSOR_PREFIX)) {
return ProcessorDependencyMode.EXEMPT_NORECORD;
}
if (dependencyModule.getExemptGenerators().contains(value)) {
return ProcessorDependencyMode.EXEMPT_RECORD;
}
}
return ProcessorDependencyMode.DEFAULT;
}
private static ImmutableSet<String> getGeneratedBy(Symbol symbol) {
ImmutableSet.Builder<String> suppressions = ImmutableSet.builder();
symbol
.getRawAttributes()
.stream()
.filter(
a -> {
Name name = a.type.tsym.getQualifiedName();
return name.contentEquals("javax.annotation.Generated")
|| name.contentEquals("javax.annotation.processing.Generated");
})
.flatMap(
a ->
a.getElementValues()
.entrySet()
.stream()
.filter(e -> e.getKey().getSimpleName().contentEquals("value"))
.map(e -> e.getValue()))
.forEachOrdered(
a ->
a.accept(
new SimpleAnnotationValueVisitor8<Void, Void>() {
@Override
public Void visitString(String s, Void aVoid) {
suppressions.add(s);
return super.visitString(s, aVoid);
}
@Override
public Void visitArray(List<? extends AnnotationValue> vals, Void aVoid) {
vals.forEach(v -> v.accept(this, null));
return super.visitArray(vals, aVoid);
}
},
null));
return suppressions.build();
}
/** Returns the canonical version of the target name. Package private for testing. */
static String canonicalizeTarget(String target) {
int colonIndex = target.indexOf(':');
if (colonIndex == -1) {
// No ':' in target, nothing to do.
return target;
}
int lastSlash = target.lastIndexOf('/', colonIndex);
if (lastSlash == -1) {
// No '/' or target is actually a filename in label format, return unmodified.
return target;
}
String packageName = target.substring(lastSlash + 1, colonIndex);
String suffix = target.substring(colonIndex + 1);
if (packageName.equals(suffix)) {
// target ends in "/something:something", canonicalize.
return target.substring(0, colonIndex);
}
return target;
}
/**
* Returns the name of the jar file from which the given class symbol was loaded, if available,
* and null otherwise. Implicitly filters out jars from the compilation bootclasspath.
*
* @param platformJars jars on javac's bootclasspath
*/
public static Path getJarPath(ClassSymbol classSymbol, Set<Path> platformJars) {
if (classSymbol == null) {
return null;
}
// Ignore symbols that appear in the sourcepath:
if (haveSourceForSymbol(classSymbol)) {
return null;
}
JavaFileObject classfile = classSymbol.classfile;
Path path = ImplicitDependencyExtractor.getJarPath(classfile);
if (path == null) {
return null;
}
// Filter out classes on bootclasspath
if (platformJars.contains(path)) {
return null;
}
return path;
}
/** Returns true if the given classSymbol corresponds to one of the sources being compiled. */
private static boolean haveSourceForSymbol(ClassSymbol classSymbol) {
if (classSymbol.sourcefile == null) {
return false;
}
try {
// The classreader uses metadata to populate the symbol's sourcefile with a fake file object.
// Call getLastModified() to check if it's a real file:
classSymbol.sourcefile.getLastModified();
} catch (UnsupportedOperationException e) {
return false;
}
return true;
}
@Override
public boolean runOnAttributionErrors() {
return true;
}
}
| Consolidate SJD exemptions
PiperOrigin-RevId: 217736958
| src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/plugins/dependency/StrictJavaDepsPlugin.java | Consolidate SJD exemptions | <ide><path>rc/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/plugins/dependency/StrictJavaDepsPlugin.java
<ide> @Override
<ide> public void postAttribute(Env<AttrContext> env) {
<ide> JavaFileObject previousSource = checkingTreeScanner.source;
<del> boolean previousExemption = checkingTreeScanner.isStrictDepsExempt;
<ide> try {
<del> ProcessorDependencyMode mode = isAnnotationProcessorExempt(env.toplevel);
<del> if (mode == ProcessorDependencyMode.EXEMPT_NORECORD) {
<add> if (isAnnotationProcessorExempt(env.toplevel)) {
<ide> return;
<ide> }
<del> checkingTreeScanner.isStrictDepsExempt |= mode == ProcessorDependencyMode.EXEMPT_RECORD;
<ide> checkingTreeScanner.source =
<ide> env.enclClass.sym.sourcefile != null
<ide> ? env.enclClass.sym.sourcefile
<ide> dependencyModule.addPackage(env.toplevel.packge);
<ide> }
<ide> } finally {
<del> checkingTreeScanner.isStrictDepsExempt = previousExemption;
<ide> checkingTreeScanner.source = previousSource;
<ide> }
<ide> }
<ide> /** The set of jars on the compilation bootclasspath. */
<ide> private final Set<Path> platformJars;
<ide>
<del> /** Was the node being visited generated by an exempt annotation processor? */
<del> private boolean isStrictDepsExempt = false;
<del>
<ide> /** The current source, for diagnostics. */
<ide> private JavaFileObject source = null;
<ide>
<ide> * strict_java_deps is enabled, it emits a [strict] compiler warning/error.
<ide> */
<ide> private void collectExplicitDependency(Path jarPath, JCTree node, Symbol sym) {
<del> if (!isStrictDepsExempt) {
<del> // Does it make sense to emit a warning/error for this pair of (type, owner)?
<del> // We want to emit only one error/warning per owner.
<del> if (!directJars.contains(jarPath) && seenStrictDepsViolatingJars.add(jarPath)) {
<del> // IO cost here is fine because we only hit this path for an explicit dependency
<del> // _not_ in the direct jars, i.e. an error
<del> JarOwner owner = readJarOwnerFromManifest(jarPath);
<del> if (seenTargets.add(owner)) {
<del> // owner is of the form "//label/of:rule <Aspect name>" where <Aspect name> is
<del> // optional.
<del> Optional<String> canonicalTargetName =
<del> owner.label().map(label -> canonicalizeTarget(label));
<del> missingTargets.add(owner);
<del> String toolInfo =
<del> owner.aspect().isPresent()
<del> ? String.format(
<del> "%s wrapped in %s", canonicalTargetName.get(), owner.aspect().get())
<del> : canonicalTargetName.isPresent()
<del> ? canonicalTargetName.get()
<del> : owner.jar().toString();
<del> String used =
<del> sym.getSimpleName().contentEquals("package-info")
<del> ? "package " + sym.getEnclosingElement()
<del> : "type " + sym;
<del> String message =
<del> String.format(
<del> "[strict] Using %s from an indirect dependency (TOOL_INFO: \"%s\").%s",
<del> used, toolInfo, (owner.label().isPresent() ? " See command below **" : ""));
<del> diagnostics.add(SjdDiagnostic.create(node.pos, message, source));
<del> }
<add> // Does it make sense to emit a warning/error for this pair of (type, owner)?
<add> // We want to emit only one error/warning per owner.
<add> if (!directJars.contains(jarPath) && seenStrictDepsViolatingJars.add(jarPath)) {
<add> // IO cost here is fine because we only hit this path for an explicit dependency
<add> // _not_ in the direct jars, i.e. an error
<add> JarOwner owner = readJarOwnerFromManifest(jarPath);
<add> if (seenTargets.add(owner)) {
<add> // owner is of the form "//label/of:rule <Aspect name>" where <Aspect name> is
<add> // optional.
<add> Optional<String> canonicalTargetName =
<add> owner.label().map(label -> canonicalizeTarget(label));
<add> missingTargets.add(owner);
<add> String toolInfo =
<add> owner.aspect().isPresent()
<add> ? String.format(
<add> "%s wrapped in %s", canonicalTargetName.get(), owner.aspect().get())
<add> : canonicalTargetName.isPresent()
<add> ? canonicalTargetName.get()
<add> : owner.jar().toString();
<add> String used =
<add> sym.getSimpleName().contentEquals("package-info")
<add> ? "package " + sym.getEnclosingElement()
<add> : "type " + sym;
<add> String message =
<add> String.format(
<add> "[strict] Using %s from an indirect dependency (TOOL_INFO: \"%s\").%s",
<add> used, toolInfo, (owner.label().isPresent() ? " See command below **" : ""));
<add> diagnostics.add(SjdDiagnostic.create(node.pos, message, source));
<ide> }
<ide> }
<ide>
<ide> }
<ide> }
<ide>
<del> private static final String DAGGER_PROCESSOR_PREFIX = "dagger.";
<del>
<del> enum ProcessorDependencyMode {
<del> DEFAULT,
<del> EXEMPT_RECORD,
<del> EXEMPT_NORECORD;
<del> }
<del>
<ide> /**
<ide> * Returns true if the compilation unit contains a single top-level class generated by an exempt
<ide> * annotation processor (according to its {@link @Generated} annotation).
<ide> * <p>Annotation processors are expected to never generate more than one top level class, as
<ide> * required by the style guide.
<ide> */
<del> public ProcessorDependencyMode isAnnotationProcessorExempt(JCTree.JCCompilationUnit unit) {
<add> public boolean isAnnotationProcessorExempt(JCTree.JCCompilationUnit unit) {
<ide> if (unit.getTypeDecls().size() != 1) {
<del> return ProcessorDependencyMode.DEFAULT;
<add> return false;
<ide> }
<ide> Symbol sym = TreeInfo.symbolFor(getOnlyElement(unit.getTypeDecls()));
<ide> if (sym == null) {
<del> return ProcessorDependencyMode.DEFAULT;
<add> return false;
<ide> }
<ide> for (String value : getGeneratedBy(sym)) {
<del> // Relax strict deps for dagger-generated code (b/17979436).
<del> if (value.startsWith(DAGGER_PROCESSOR_PREFIX)) {
<del> return ProcessorDependencyMode.EXEMPT_NORECORD;
<del> }
<ide> if (dependencyModule.getExemptGenerators().contains(value)) {
<del> return ProcessorDependencyMode.EXEMPT_RECORD;
<del> }
<del> }
<del> return ProcessorDependencyMode.DEFAULT;
<add> return true;
<add> }
<add> }
<add> return false;
<ide> }
<ide>
<ide> private static ImmutableSet<String> getGeneratedBy(Symbol symbol) { |
|
Java | apache-2.0 | b21fb36ada2ab27501c0245acf4443295360733a | 0 | lolay/citygrid-java-old | package com.lolay.citygrid;
import java.io.Serializable;
import java.net.URI;
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
@XmlRootElement(name="editorial")
@XmlAccessorType(value=XmlAccessType.FIELD)
public class Editorial implements Serializable {
private static final long serialVersionUID = 1L;
@XmlAttribute(name="attribution_text",required=true)
private String attributionText = null;
@XmlAttribute(name="attribution_logo",required=true)
private URI attributionLogo = null;
@XmlAttribute(name="attribution_source",required=true)
private Integer attributionSource = null;
@XmlElement(name="editorial_id",required=true)
private Integer editorialId = null;
@XmlElement(name="editorial_url",required=true)
private URI editorialUrl = null;
@XmlElement(name="editorial_title",required=true)
private String editorialTitle = null;
@XmlElement(name="editorial_author",required=true)
private String editorialAuthor = null;
@XmlElement(name="editorial_review",required=true)
private String editorialReview = null;
@XmlElement(name="pros")
private String pros = null;
@XmlElement(name="cons")
private String cons = null;
@XmlElement(name="editorial_date",required=true)
private Date editorialDate = null;
@XmlElement(name="review_rating",required=true)
@XmlJavaTypeAdapter(value=ReviewRatingAdapter.class)
private Integer reviewRating = null;
@XmlElement(name="helpfulness_total_count",required=true)
private Integer helpfulnessTotalCount = null;
@XmlElement(name="helpful_count",required=true)
private Integer helpfulCount = null;
@XmlElement(name="unhelpful_count",required=true)
private Integer unhelpfulCount = null;
public String getAttributionText() {
return attributionText;
}
public void setAttributionText(String attributionText) {
this.attributionText = attributionText;
}
public URI getAttributionLogo() {
return attributionLogo;
}
public void setAttributionLogo(URI attributionLogo) {
this.attributionLogo = attributionLogo;
}
public Integer getAttributionSource() {
return attributionSource;
}
public void setAttributionSource(Integer attributionSource) {
this.attributionSource = attributionSource;
}
public Integer getEditorialId() {
return editorialId;
}
public void setEditorialId(Integer editorialId) {
this.editorialId = editorialId;
}
public URI getEditorialUrl() {
return editorialUrl;
}
public void setEditorialUrl(URI editorialUrl) {
this.editorialUrl = editorialUrl;
}
public String getEditorialTitle() {
return editorialTitle;
}
public void setEditorialTitle(String editorialTitle) {
this.editorialTitle = editorialTitle;
}
public String getEditorialAuthor() {
return editorialAuthor;
}
public void setEditorialAuthor(String editorialAuthor) {
this.editorialAuthor = editorialAuthor;
}
public String getEditorialReview() {
return editorialReview;
}
public void setEditorialReview(String editorialReview) {
this.editorialReview = editorialReview;
}
public String getPros() {
return pros;
}
public void setPros(String pros) {
this.pros = pros;
}
public String getCons() {
return cons;
}
public void setCons(String cons) {
this.cons = cons;
}
public Date getEditorialDate() {
return editorialDate;
}
public void setEditorialDate(Date editorialDate) {
this.editorialDate = editorialDate;
}
public Integer getReviewRating() {
return reviewRating;
}
public void setReviewRating(Integer reviewRating) {
this.reviewRating = reviewRating;
}
public Integer getHelpfulnessTotalCount() {
return helpfulnessTotalCount;
}
public void setHelpfulnessTotalCount(Integer helpfulnessTotalCount) {
this.helpfulnessTotalCount = helpfulnessTotalCount;
}
public Integer getHelpfulCount() {
return helpfulCount;
}
public void setHelpfulCount(Integer helpfulCount) {
this.helpfulCount = helpfulCount;
}
public Integer getUnhelpfulCount() {
return unhelpfulCount;
}
public void setUnhelpfulCount(Integer unhelpfulCount) {
this.unhelpfulCount = unhelpfulCount;
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
} | src/main/java/com/lolay/citygrid/Editorial.java | package com.lolay.citygrid;
import java.io.Serializable;
import java.net.URI;
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
@XmlRootElement(name="editorial")
@XmlAccessorType(value=XmlAccessType.FIELD)
public class Editorial implements Serializable {
private static final long serialVersionUID = 1L;
@XmlAttribute(name="attribution_text",required=true)
private String attributionText = null;
@XmlAttribute(name="attribution_logo",required=true)
private URI attributionLogo = null;
@XmlAttribute(name="attribution_source",required=true)
private Integer attributionSource = null;
@XmlElement(name="editorial_id",required=true)
private Integer editorialId = null;
@XmlElement(name="editorial_url",required=true)
private URI editorialUrl = null;
@XmlElement(name="editorial_title",required=true)
private String editorialTitle = null;
@XmlElement(name="editorial_author",required=true)
private String editorialAuthor = null;
@XmlElement(name="pros")
private String pros = null;
@XmlElement(name="cons")
private String cons = null;
@XmlElement(name="editorial_date",required=true)
private Date editorialDate = null;
@XmlElement(name="review_rating",required=true)
@XmlJavaTypeAdapter(value=ReviewRatingAdapter.class)
private Integer review_rating = null;
@XmlElement(name="helpfulness_total_count",required=true)
private Integer helpfulnessTotalCount = null;
@XmlElement(name="helpful_count",required=true)
private Integer helpfulCount = null;
@XmlElement(name="unhelpful_count",required=true)
private Integer unhelpfulCount = null;
public String getAttributionText() {
return attributionText;
}
public void setAttributionText(String attributionText) {
this.attributionText = attributionText;
}
public URI getAttributionLogo() {
return attributionLogo;
}
public void setAttributionLogo(URI attributionLogo) {
this.attributionLogo = attributionLogo;
}
public Integer getAttributionSource() {
return attributionSource;
}
public void setAttributionSource(Integer attributionSource) {
this.attributionSource = attributionSource;
}
public Integer getEditorialId() {
return editorialId;
}
public void setEditorialId(Integer editorialId) {
this.editorialId = editorialId;
}
public URI getEditorialUrl() {
return editorialUrl;
}
public void setEditorialUrl(URI editorialUrl) {
this.editorialUrl = editorialUrl;
}
public String getEditorialTitle() {
return editorialTitle;
}
public void setEditorialTitle(String editorialTitle) {
this.editorialTitle = editorialTitle;
}
public String getEditorialAuthor() {
return editorialAuthor;
}
public void setEditorialAuthor(String editorialAuthor) {
this.editorialAuthor = editorialAuthor;
}
public String getPros() {
return pros;
}
public void setPros(String pros) {
this.pros = pros;
}
public String getCons() {
return cons;
}
public void setCons(String cons) {
this.cons = cons;
}
public Date getEditorialDate() {
return editorialDate;
}
public void setEditorialDate(Date editorialDate) {
this.editorialDate = editorialDate;
}
public Integer getReview_rating() {
return review_rating;
}
public void setReview_rating(Integer review_rating) {
this.review_rating = review_rating;
}
public Integer getHelpfulnessTotalCount() {
return helpfulnessTotalCount;
}
public void setHelpfulnessTotalCount(Integer helpfulnessTotalCount) {
this.helpfulnessTotalCount = helpfulnessTotalCount;
}
public Integer getHelpfulCount() {
return helpfulCount;
}
public void setHelpfulCount(Integer helpfulCount) {
this.helpfulCount = helpfulCount;
}
public Integer getUnhelpfulCount() {
return unhelpfulCount;
}
public void setUnhelpfulCount(Integer unhelpfulCount) {
this.unhelpfulCount = unhelpfulCount;
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
} | Fixed typo and added editorialReview
| src/main/java/com/lolay/citygrid/Editorial.java | Fixed typo and added editorialReview | <ide><path>rc/main/java/com/lolay/citygrid/Editorial.java
<ide> private String editorialTitle = null;
<ide> @XmlElement(name="editorial_author",required=true)
<ide> private String editorialAuthor = null;
<add> @XmlElement(name="editorial_review",required=true)
<add> private String editorialReview = null;
<ide> @XmlElement(name="pros")
<ide> private String pros = null;
<ide> @XmlElement(name="cons")
<ide> private Date editorialDate = null;
<ide> @XmlElement(name="review_rating",required=true)
<ide> @XmlJavaTypeAdapter(value=ReviewRatingAdapter.class)
<del> private Integer review_rating = null;
<add> private Integer reviewRating = null;
<ide> @XmlElement(name="helpfulness_total_count",required=true)
<ide> private Integer helpfulnessTotalCount = null;
<ide> @XmlElement(name="helpful_count",required=true)
<ide> public void setEditorialAuthor(String editorialAuthor) {
<ide> this.editorialAuthor = editorialAuthor;
<ide> }
<add> public String getEditorialReview() {
<add> return editorialReview;
<add> }
<add> public void setEditorialReview(String editorialReview) {
<add> this.editorialReview = editorialReview;
<add> }
<ide> public String getPros() {
<ide> return pros;
<ide> }
<ide> public void setEditorialDate(Date editorialDate) {
<ide> this.editorialDate = editorialDate;
<ide> }
<del> public Integer getReview_rating() {
<del> return review_rating;
<add> public Integer getReviewRating() {
<add> return reviewRating;
<ide> }
<del> public void setReview_rating(Integer review_rating) {
<del> this.review_rating = review_rating;
<add> public void setReviewRating(Integer reviewRating) {
<add> this.reviewRating = reviewRating;
<ide> }
<ide> public Integer getHelpfulnessTotalCount() {
<ide> return helpfulnessTotalCount; |
|
Java | agpl-3.0 | d07c04b1e381f6e778371095c042fc3ed485ae5a | 0 | Spirals-Team/librepair,Spirals-Team/librepair,Spirals-Team/librepair,Spirals-Team/librepair,Spirals-Team/librepair | package com.github.tdurieux.repair.maven.plugin;
import exceptionparser.StackTrace;
import exceptionparser.StackTraceElement;
import exceptionparser.StackTraceParser;
import fr.inria.spirals.npefix.config.Config;
import fr.inria.spirals.npefix.main.DecisionServer;
import fr.inria.spirals.npefix.main.all.DefaultRepairStrategy;
import fr.inria.spirals.npefix.main.all.Launcher;
import fr.inria.spirals.npefix.main.all.TryCatchRepairStrategy;
import fr.inria.spirals.npefix.resi.CallChecker;
import fr.inria.spirals.npefix.resi.context.Decision;
import fr.inria.spirals.npefix.resi.context.Lapse;
import fr.inria.spirals.npefix.resi.context.NPEOutput;
import fr.inria.spirals.npefix.resi.exception.NoMoreDecision;
import fr.inria.spirals.npefix.resi.selector.ExplorerSelector;
import fr.inria.spirals.npefix.resi.selector.GreedySelector;
import fr.inria.spirals.npefix.resi.selector.MonoExplorerSelector;
import fr.inria.spirals.npefix.resi.selector.RandomSelector;
import fr.inria.spirals.npefix.resi.selector.Selector;
import fr.inria.spirals.npefix.resi.strategies.NoStrat;
import fr.inria.spirals.npefix.resi.strategies.ReturnType;
import fr.inria.spirals.npefix.resi.strategies.Strat1A;
import fr.inria.spirals.npefix.resi.strategies.Strat1B;
import fr.inria.spirals.npefix.resi.strategies.Strat2A;
import fr.inria.spirals.npefix.resi.strategies.Strat2B;
import fr.inria.spirals.npefix.resi.strategies.Strat3;
import fr.inria.spirals.npefix.resi.strategies.Strat4;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.surefire.log.api.NullConsoleLogger;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.plugins.surefire.report.ReportTestCase;
import org.apache.maven.plugins.surefire.report.ReportTestSuite;
import org.apache.maven.plugins.surefire.report.SurefireReportParser;
import org.apache.maven.project.MavenProject;
import org.apache.maven.reporting.MavenReportException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
@Mojo( name = "npefix", aggregator = true,
defaultPhase = LifecyclePhase.TEST,
requiresDependencyResolution = ResolutionScope.TEST)
public class NPEFixMojo extends AbstractRepairMojo {
/**
* Location of the file.
*/
@Parameter( defaultValue = "${project.build.directory}/npefix", property = "outputDir", required = true )
private File outputDirectory;
@Parameter( defaultValue = "${project.build.directory}/npefix", property = "resultDir", required = true )
private File resultDirectory;
@Parameter( defaultValue = "exploration", property = "selector", required = true )
private String selector;
@Parameter( defaultValue = "100", property = "laps", required = true )
private int nbIteration;
@Parameter( defaultValue = "class", property = "scope", required = true )
private String scope;
@Parameter( defaultValue = "default", property = "strategy", required = true )
private String repairStrategy;
private NPEOutput result;
public void execute() throws MojoExecutionException {
// get the failing NPE tests
List<Pair<String, Set<File>>> npeTests = getNPETest();
try {
File currentDir = new File(".").getCanonicalFile();
Config.CONFIG.setRootProject(currentDir.toPath().toAbsolutePath());
} catch (IOException e) {
getLog().error("Error while setting the root project path, the created patches might have absolute paths.");
}
final List<URL> dependencies = getClasspath();
Set<File> sourceFolders = new HashSet<>();
if ("project".equals(scope)) {
sourceFolders = new HashSet<>(getSourceFolders());
} else {
for (Pair<String, Set<File>> test : npeTests) {
sourceFolders.addAll(test.getValue());
}
}
List<File> testFolders = getTestFolders();
classpath(dependencies);
// stop if we don't have at least one NPE
if (npeTests.isEmpty()) {
throw new RuntimeException("No failing test with NullPointerException or the NPE occurred outside the source.");
}
final String[] sources = new String[sourceFolders.size() /* + testFolders.size()*/];
int indexSource = 0;
/*for (int i = 0; i < testFolders.size(); i++, indexSource++) {
String s = testFolders.get(i);
sources[indexSource] = s;
System.out.println("Test: " + s);
}*/
// collecting the source and bin folders
for (File sourceFolder : sourceFolders) {
sources[indexSource] = sourceFolder.getAbsolutePath();
System.out.println("Source: " + sourceFolder);
indexSource++;
}
File binFolder = new File(outputDirectory.getAbsolutePath() + "/npefix-bin");
// setting up dependencies
try {
dependencies.add(binFolder.toURI().toURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (!binFolder.exists()) {
binFolder.mkdirs();
}
int complianceLevel = getComplianceLevel();
complianceLevel = Math.max(complianceLevel, 5);
System.out.println("ComplianceLevel: " + complianceLevel);
Date initDate = new Date();
// configuring NPEFix
DefaultRepairStrategy strategy = new DefaultRepairStrategy(sources);
if (repairStrategy.toLowerCase().equals("TryCatch".toLowerCase())) {
strategy = new TryCatchRepairStrategy(sources);
}
Launcher npefix = new Launcher(sources, outputDirectory.getAbsolutePath() + "/npefix-output", binFolder.getAbsolutePath(), classpath(dependencies), complianceLevel, strategy);
//npefix.getSpoon().getEnvironment().setAutoImports(false);
// NPEfix is based on metaprogramming, this is where it happens
npefix.instrument();
List<String> tests = new ArrayList<>();
for (Pair<String, Set<File>> npeTest : npeTests) {
if (!tests.contains(npeTest.getKey())) {
tests.add(npeTest.getKey());
}
}
// getting the patch if any (an object of type NPEOutput), see method run below
this.result = run(npefix, tests);
spoon.Launcher spoon = new spoon.Launcher();
for (File s : sourceFolders) {
spoon.addInputResource(s.getAbsolutePath());
}
spoon.getModelBuilder().setSourceClasspath(classpath(dependencies).split(File.pathSeparatorChar + ""));
spoon.buildModel();
// write a JSON file with the result and the patch
JSONObject jsonObject = result.toJSON(spoon);
jsonObject.put("endInit", initDate.getTime());
System.out.println(resultDirectory.getAbsolutePath());
System.out.println(jsonObject.getJSONArray("executions"));
for(Object ob : jsonObject.getJSONArray("executions"))
{
// the patch in the json file
System.out.println(((JSONObject)ob).getString("diff"));
}
try {
for (Decision decision : CallChecker.strategySelector.getSearchSpace()) {
jsonObject.append("searchSpace", decision.toJSON());
}
FileWriter writer = new FileWriter(resultDirectory.getAbsolutePath() + "/patches_" + new Date().getTime() + ".json");
jsonObject.write(writer);
writer.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private NPEOutput run(Launcher npefix, List<String> npeTests) {
switch (selector.toLowerCase()) {
case "dom":
return npefix.runStrategy(npeTests,
new NoStrat(),
new Strat1A(),
new Strat1B(),
new Strat2A(),
new Strat2B(),
new Strat3(),
new Strat4(ReturnType.NULL),
new Strat4(ReturnType.VAR),
new Strat4(ReturnType.NEW),
new Strat4(ReturnType.VOID));
case "exploration":
ExplorerSelector selector = new ExplorerSelector();
if (repairStrategy.toLowerCase().equals("TryCatch".toLowerCase())) {
selector = new ExplorerSelector(new Strat4(ReturnType.NULL), new Strat4(ReturnType.VAR), new Strat4(ReturnType.NEW), new Strat4(ReturnType.VOID));
}
return multipleRuns(npefix, npeTests, selector);
case "mono":
Config.CONFIG.setMultiPoints(false);
return multipleRuns(npefix, npeTests, new MonoExplorerSelector());
case "greedy":
return multipleRuns(npefix, npeTests, new GreedySelector());
case "random":
return multipleRuns(npefix, npeTests, new RandomSelector());
}
return null;
}
private NPEOutput multipleRuns(Launcher npefix, List<String> npeTests, Selector selector) {
DecisionServer decisionServer = new DecisionServer(selector);
decisionServer.startServer();
NPEOutput output = new NPEOutput();
int countError = 0;
while (output.size() < nbIteration) {
if(countError > 5) {
break;
}
try {
List<Lapse> result = npefix.run(selector, npeTests);
if(result.isEmpty()) {
countError++;
continue;
}
boolean isEnd = true;
for (int i = 0; i < result.size() && isEnd; i++) {
Lapse lapse = result.get(i);
if (lapse.getOracle().getError() != null) {
isEnd = isEnd && lapse.getOracle().getError().contains(NoMoreDecision.class.getSimpleName()) || lapse.getDecisions().isEmpty();
} else {
isEnd = false;
}
}
if (isEnd) {
// no more decision
countError++;
continue;
}
countError = 0;
if(output.size() + result.size() > nbIteration) {
output.addAll(result.subList(0, (nbIteration - output.size())));
} else {
output.addAll(result);
}
} catch (OutOfMemoryError e) {
e.printStackTrace();
countError++;
continue;
} catch (Exception e) {
if(e.getCause() instanceof OutOfMemoryError) {
countError++;
continue;
}
e.printStackTrace();
countError++;
continue;
}
System.out.println("Multirun " + output.size() + "/" + nbIteration + " " + ((int)(output.size()/(double)nbIteration * 100)) + "%");
}
output.setEnd(new Date());
return output;
}
public static String getNpeFixVersion() {
try {
final java.util.Properties properties = new java.util.Properties();
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("versions.properties"));
return (properties.getProperty("npefix.version"));
} catch (Exception e) { throw new RuntimeException(e); }
}
private String classpath(List<URL> dependencies) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dependencies.size(); i++) {
URL s = dependencies.get(i);
sb.append(s.getPath()).append(File.pathSeparatorChar);
}
final Artifact artifact =artifactFactory.createArtifact("fr.inria.gforge.spirals","npefix", getNpeFixVersion(), null, "jar");
File file = new File(localRepository.getBasedir() + "/" + localRepository.pathOf(artifact));
sb.append(file.getAbsoluteFile());
System.out.println(sb);
return sb.toString();
}
private File getSurefireReportsDirectory( MavenProject subProject ) {
String buildDir = subProject.getBuild().getDirectory();
return new File( buildDir + "/surefire-reports" );
}
/** gets the failing tests due to a NullPointerException by parsing the Surefire XML files */
private List<Pair<String, Set<File>>> getNPETest() {
List<Pair<String, Set<File>>> output = new ArrayList<>();
for (MavenProject mavenProject : reactorProjects) {
File surefireReportsDirectory = getSurefireReportsDirectory(mavenProject);
SurefireReportParser parser = new SurefireReportParser(Collections.singletonList(surefireReportsDirectory), Locale.ENGLISH, new NullConsoleLogger());
try {
List<ReportTestSuite> testSuites = parser.parseXMLReportFiles();
for (int i = 0; i < testSuites.size(); i++) {
ReportTestSuite reportTestSuite = testSuites.get(i);
List<ReportTestCase> testCases = reportTestSuite.getTestCases();
for (int j = 0; j < testCases.size(); j++) {
ReportTestCase reportTestCase = testCases.get(j);
if (reportTestCase.hasFailure() && reportTestCase.getFailureDetail() != null) {
try {
StackTrace stackTrace = StackTraceParser.parse(reportTestCase.getFailureDetail());
StackTrace causedBy = stackTrace.getCausedBy();
while (causedBy != null) {
stackTrace = causedBy;
causedBy = stackTrace.getCausedBy();
}
if (stackTrace.getExceptionType().contains("NullPointerException") || repairStrategy.toLowerCase().equals("TryCatch".toLowerCase())) {
Set<File> files = new HashSet<>();
for (StackTraceElement stackTraceElement : stackTrace.getElements()) {
String path = stackTraceElement.getMethod().substring(0, stackTraceElement.getMethod().lastIndexOf(".")).replace(".", "/") + ".java";
if (path.contains("$")) {
path = path.substring(0, path.indexOf("$")) + ".java";
}
if ("package".equals(scope)) {
path = path.substring(0, path.lastIndexOf("/"));
}
for (MavenProject project : reactorProjects) {
File file = new File(project.getBuild().getSourceDirectory() + "/" + path);
if (file.exists()) {
files.add(file);
break;
}
}
if (!"stack".equals(scope)) {
break;
}
}
output.add(new Pair<>(reportTestCase.getFullClassName() + "#" + reportTestCase.getName(), files));
}
} catch (StackTraceParser.ParseException e) {
e.printStackTrace();
}
}
}
}
} catch (MavenReportException e) {
e.printStackTrace();
}
}
return output;
}
public NPEOutput getResult() {
return result;
}
}
| src/maven-repair/src/main/java/com/github/tdurieux/repair/maven/plugin/NPEFixMojo.java | package com.github.tdurieux.repair.maven.plugin;
import exceptionparser.StackTrace;
import exceptionparser.StackTraceElement;
import exceptionparser.StackTraceParser;
import fr.inria.spirals.npefix.config.Config;
import fr.inria.spirals.npefix.main.DecisionServer;
import fr.inria.spirals.npefix.main.all.DefaultRepairStrategy;
import fr.inria.spirals.npefix.main.all.Launcher;
import fr.inria.spirals.npefix.main.all.TryCatchRepairStrategy;
import fr.inria.spirals.npefix.resi.CallChecker;
import fr.inria.spirals.npefix.resi.context.Decision;
import fr.inria.spirals.npefix.resi.context.Lapse;
import fr.inria.spirals.npefix.resi.context.NPEOutput;
import fr.inria.spirals.npefix.resi.exception.NoMoreDecision;
import fr.inria.spirals.npefix.resi.selector.ExplorerSelector;
import fr.inria.spirals.npefix.resi.selector.GreedySelector;
import fr.inria.spirals.npefix.resi.selector.MonoExplorerSelector;
import fr.inria.spirals.npefix.resi.selector.RandomSelector;
import fr.inria.spirals.npefix.resi.selector.Selector;
import fr.inria.spirals.npefix.resi.strategies.NoStrat;
import fr.inria.spirals.npefix.resi.strategies.ReturnType;
import fr.inria.spirals.npefix.resi.strategies.Strat1A;
import fr.inria.spirals.npefix.resi.strategies.Strat1B;
import fr.inria.spirals.npefix.resi.strategies.Strat2A;
import fr.inria.spirals.npefix.resi.strategies.Strat2B;
import fr.inria.spirals.npefix.resi.strategies.Strat3;
import fr.inria.spirals.npefix.resi.strategies.Strat4;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.surefire.log.api.NullConsoleLogger;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.plugins.surefire.report.ReportTestCase;
import org.apache.maven.plugins.surefire.report.ReportTestSuite;
import org.apache.maven.plugins.surefire.report.SurefireReportParser;
import org.apache.maven.project.MavenProject;
import org.apache.maven.reporting.MavenReportException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
@Mojo( name = "npefix", aggregator = true,
defaultPhase = LifecyclePhase.TEST,
requiresDependencyResolution = ResolutionScope.TEST)
public class NPEFixMojo extends AbstractRepairMojo {
/**
* Location of the file.
*/
@Parameter( defaultValue = "${project.build.directory}/npefix", property = "outputDir", required = true )
private File outputDirectory;
@Parameter( defaultValue = "${project.build.directory}/npefix", property = "resultDir", required = true )
private File resultDirectory;
@Parameter( defaultValue = "exploration", property = "selector", required = true )
private String selector;
@Parameter( defaultValue = "100", property = "laps", required = true )
private int nbIteration;
@Parameter( defaultValue = "class", property = "scope", required = true )
private String scope;
@Parameter( defaultValue = "default", property = "strategy", required = true )
private String repairStrategy;
private NPEOutput result;
public void execute() throws MojoExecutionException {
List<Pair<String, Set<File>>> npeTests = getNPETest();
try {
File currentDir = new File(".").getCanonicalFile();
Config.CONFIG.setRootProject(currentDir.toPath().toAbsolutePath());
} catch (IOException e) {
getLog().error("Error while setting the root project path, the created patches might have absolute paths.");
}
final List<URL> dependencies = getClasspath();
Set<File> sourceFolders = new HashSet<>();
if ("project".equals(scope)) {
sourceFolders = new HashSet<>(getSourceFolders());
} else {
for (Pair<String, Set<File>> test : npeTests) {
sourceFolders.addAll(test.getValue());
}
}
List<File> testFolders = getTestFolders();
classpath(dependencies);
if (npeTests.isEmpty()) {
throw new RuntimeException("No failing test with NullPointerException or the NPE occurred outside the source.");
}
final String[] sources = new String[sourceFolders.size() /* + testFolders.size()*/];
int indexSource = 0;
/*for (int i = 0; i < testFolders.size(); i++, indexSource++) {
String s = testFolders.get(i);
sources[indexSource] = s;
System.out.println("Test: " + s);
}*/
for (File sourceFolder : sourceFolders) {
sources[indexSource] = sourceFolder.getAbsolutePath();
System.out.println("Source: " + sourceFolder);
indexSource++;
}
File binFolder = new File(outputDirectory.getAbsolutePath() + "/npefix-bin");
try {
dependencies.add(binFolder.toURI().toURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (!binFolder.exists()) {
binFolder.mkdirs();
}
int complianceLevel = getComplianceLevel();
complianceLevel = Math.max(complianceLevel, 5);
System.out.println("ComplianceLevel: " + complianceLevel);
Date initDate = new Date();
DefaultRepairStrategy strategy = new DefaultRepairStrategy(sources);
if (repairStrategy.toLowerCase().equals("TryCatch".toLowerCase())) {
strategy = new TryCatchRepairStrategy(sources);
}
Launcher npefix = new Launcher(sources, outputDirectory.getAbsolutePath() + "/npefix-output", binFolder.getAbsolutePath(), classpath(dependencies), complianceLevel, strategy);
//npefix.getSpoon().getEnvironment().setAutoImports(false);
npefix.instrument();
List<String> tests = new ArrayList<>();
for (Pair<String, Set<File>> npeTest : npeTests) {
if (!tests.contains(npeTest.getKey())) {
tests.add(npeTest.getKey());
}
}
this.result = run(npefix, tests);
spoon.Launcher spoon = new spoon.Launcher();
for (File s : sourceFolders) {
spoon.addInputResource(s.getAbsolutePath());
}
spoon.getModelBuilder().setSourceClasspath(classpath(dependencies).split(File.pathSeparatorChar + ""));
spoon.buildModel();
JSONObject jsonObject = result.toJSON(spoon);
jsonObject.put("endInit", initDate.getTime());
System.out.println(resultDirectory.getAbsolutePath());
System.out.println(jsonObject.getJSONArray("executions"));
for(Object ob : jsonObject.getJSONArray("executions"))
{
// the patch in the json file
System.out.println(((JSONObject)ob).getString("diff"));
}
try {
for (Decision decision : CallChecker.strategySelector.getSearchSpace()) {
jsonObject.append("searchSpace", decision.toJSON());
}
FileWriter writer = new FileWriter(resultDirectory.getAbsolutePath() + "/patches_" + new Date().getTime() + ".json");
jsonObject.write(writer);
writer.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private NPEOutput run(Launcher npefix, List<String> npeTests) {
switch (selector.toLowerCase()) {
case "dom":
return npefix.runStrategy(npeTests,
new NoStrat(),
new Strat1A(),
new Strat1B(),
new Strat2A(),
new Strat2B(),
new Strat3(),
new Strat4(ReturnType.NULL),
new Strat4(ReturnType.VAR),
new Strat4(ReturnType.NEW),
new Strat4(ReturnType.VOID));
case "exploration":
ExplorerSelector selector = new ExplorerSelector();
if (repairStrategy.toLowerCase().equals("TryCatch".toLowerCase())) {
selector = new ExplorerSelector(new Strat4(ReturnType.NULL), new Strat4(ReturnType.VAR), new Strat4(ReturnType.NEW), new Strat4(ReturnType.VOID));
}
return multipleRuns(npefix, npeTests, selector);
case "mono":
Config.CONFIG.setMultiPoints(false);
return multipleRuns(npefix, npeTests, new MonoExplorerSelector());
case "greedy":
return multipleRuns(npefix, npeTests, new GreedySelector());
case "random":
return multipleRuns(npefix, npeTests, new RandomSelector());
}
return null;
}
private NPEOutput multipleRuns(Launcher npefix, List<String> npeTests, Selector selector) {
DecisionServer decisionServer = new DecisionServer(selector);
decisionServer.startServer();
NPEOutput output = new NPEOutput();
int countError = 0;
while (output.size() < nbIteration) {
if(countError > 5) {
break;
}
try {
List<Lapse> result = npefix.run(selector, npeTests);
if(result.isEmpty()) {
countError++;
continue;
}
boolean isEnd = true;
for (int i = 0; i < result.size() && isEnd; i++) {
Lapse lapse = result.get(i);
if (lapse.getOracle().getError() != null) {
isEnd = isEnd && lapse.getOracle().getError().contains(NoMoreDecision.class.getSimpleName()) || lapse.getDecisions().isEmpty();
} else {
isEnd = false;
}
}
if (isEnd) {
// no more decision
countError++;
continue;
}
countError = 0;
if(output.size() + result.size() > nbIteration) {
output.addAll(result.subList(0, (nbIteration - output.size())));
} else {
output.addAll(result);
}
} catch (OutOfMemoryError e) {
e.printStackTrace();
countError++;
continue;
} catch (Exception e) {
if(e.getCause() instanceof OutOfMemoryError) {
countError++;
continue;
}
e.printStackTrace();
countError++;
continue;
}
System.out.println("Multirun " + output.size() + "/" + nbIteration + " " + ((int)(output.size()/(double)nbIteration * 100)) + "%");
}
output.setEnd(new Date());
return output;
}
public static String getNpeFixVersion() {
try {
final java.util.Properties properties = new java.util.Properties();
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("versions.properties"));
return (properties.getProperty("npefix.version"));
} catch (Exception e) { throw new RuntimeException(e); }
}
private String classpath(List<URL> dependencies) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dependencies.size(); i++) {
URL s = dependencies.get(i);
sb.append(s.getPath()).append(File.pathSeparatorChar);
}
final Artifact artifact =artifactFactory.createArtifact("fr.inria.gforge.spirals","npefix", getNpeFixVersion(), null, "jar");
File file = new File(localRepository.getBasedir() + "/" + localRepository.pathOf(artifact));
sb.append(file.getAbsoluteFile());
System.out.println(sb);
return sb.toString();
}
private File getSurefireReportsDirectory( MavenProject subProject ) {
String buildDir = subProject.getBuild().getDirectory();
return new File( buildDir + "/surefire-reports" );
}
private List<Pair<String, Set<File>>> getNPETest() {
List<Pair<String, Set<File>>> output = new ArrayList<>();
for (MavenProject mavenProject : reactorProjects) {
File surefireReportsDirectory = getSurefireReportsDirectory(mavenProject);
SurefireReportParser parser = new SurefireReportParser(Collections.singletonList(surefireReportsDirectory), Locale.ENGLISH, new NullConsoleLogger());
try {
List<ReportTestSuite> testSuites = parser.parseXMLReportFiles();
for (int i = 0; i < testSuites.size(); i++) {
ReportTestSuite reportTestSuite = testSuites.get(i);
List<ReportTestCase> testCases = reportTestSuite.getTestCases();
for (int j = 0; j < testCases.size(); j++) {
ReportTestCase reportTestCase = testCases.get(j);
if (reportTestCase.hasFailure() && reportTestCase.getFailureDetail() != null) {
try {
StackTrace stackTrace = StackTraceParser.parse(reportTestCase.getFailureDetail());
StackTrace causedBy = stackTrace.getCausedBy();
while (causedBy != null) {
stackTrace = causedBy;
causedBy = stackTrace.getCausedBy();
}
if (stackTrace.getExceptionType().contains("NullPointerException") || repairStrategy.toLowerCase().equals("TryCatch".toLowerCase())) {
Set<File> files = new HashSet<>();
for (StackTraceElement stackTraceElement : stackTrace.getElements()) {
String path = stackTraceElement.getMethod().substring(0, stackTraceElement.getMethod().lastIndexOf(".")).replace(".", "/") + ".java";
if (path.contains("$")) {
path = path.substring(0, path.indexOf("$")) + ".java";
}
if ("package".equals(scope)) {
path = path.substring(0, path.lastIndexOf("/"));
}
for (MavenProject project : reactorProjects) {
File file = new File(project.getBuild().getSourceDirectory() + "/" + path);
if (file.exists()) {
files.add(file);
break;
}
}
if (!"stack".equals(scope)) {
break;
}
}
output.add(new Pair<>(reportTestCase.getFullClassName() + "#" + reportTestCase.getName(), files));
}
} catch (StackTraceParser.ParseException e) {
e.printStackTrace();
}
}
}
}
} catch (MavenReportException e) {
e.printStackTrace();
}
}
return output;
}
public NPEOutput getResult() {
return result;
}
}
| doc: improve documentation of NPEFixMojo (#1097)
| src/maven-repair/src/main/java/com/github/tdurieux/repair/maven/plugin/NPEFixMojo.java | doc: improve documentation of NPEFixMojo (#1097) | <ide><path>rc/maven-repair/src/main/java/com/github/tdurieux/repair/maven/plugin/NPEFixMojo.java
<ide> private NPEOutput result;
<ide>
<ide> public void execute() throws MojoExecutionException {
<add>
<add> // get the failing NPE tests
<ide> List<Pair<String, Set<File>>> npeTests = getNPETest();
<ide>
<ide> try {
<ide>
<ide> classpath(dependencies);
<ide>
<add> // stop if we don't have at least one NPE
<ide> if (npeTests.isEmpty()) {
<ide> throw new RuntimeException("No failing test with NullPointerException or the NPE occurred outside the source.");
<ide> }
<ide> sources[indexSource] = s;
<ide> System.out.println("Test: " + s);
<ide> }*/
<add>
<add> // collecting the source and bin folders
<ide> for (File sourceFolder : sourceFolders) {
<ide> sources[indexSource] = sourceFolder.getAbsolutePath();
<ide> System.out.println("Source: " + sourceFolder);
<ide> }
<ide> File binFolder = new File(outputDirectory.getAbsolutePath() + "/npefix-bin");
<ide>
<add> // setting up dependencies
<ide> try {
<ide> dependencies.add(binFolder.toURI().toURL());
<ide> } catch (MalformedURLException e) {
<ide>
<ide> Date initDate = new Date();
<ide>
<add> // configuring NPEFix
<ide> DefaultRepairStrategy strategy = new DefaultRepairStrategy(sources);
<ide> if (repairStrategy.toLowerCase().equals("TryCatch".toLowerCase())) {
<ide> strategy = new TryCatchRepairStrategy(sources);
<ide>
<ide> //npefix.getSpoon().getEnvironment().setAutoImports(false);
<ide>
<add> // NPEfix is based on metaprogramming, this is where it happens
<ide> npefix.instrument();
<ide>
<ide>
<ide> tests.add(npeTest.getKey());
<ide> }
<ide> }
<add>
<add> // getting the patch if any (an object of type NPEOutput), see method run below
<ide> this.result = run(npefix, tests);
<ide>
<ide>
<ide> spoon.getModelBuilder().setSourceClasspath(classpath(dependencies).split(File.pathSeparatorChar + ""));
<ide> spoon.buildModel();
<ide>
<add> // write a JSON file with the result and the patch
<ide> JSONObject jsonObject = result.toJSON(spoon);
<ide> jsonObject.put("endInit", initDate.getTime());
<ide> System.out.println(resultDirectory.getAbsolutePath());
<ide> String buildDir = subProject.getBuild().getDirectory();
<ide> return new File( buildDir + "/surefire-reports" );
<ide> }
<del>
<add>
<add> /** gets the failing tests due to a NullPointerException by parsing the Surefire XML files */
<ide> private List<Pair<String, Set<File>>> getNPETest() {
<ide> List<Pair<String, Set<File>>> output = new ArrayList<>();
<ide> |
|
Java | apache-2.0 | error: pathspec 'src/main/java/com/google/sps/data/Image.java' did not match any file(s) known to git
| b7e513575bd03182df8943e0e68986f730447cde | 1 | googleinterns/step256-2020,googleinterns/step256-2020,googleinterns/step256-2020 | package com.google.sps.data;
import com.google.auto.value.AutoValue;
@AutoValue public abstract class Image{
public static Image create(long id, String blobKey, long timestamp)
{
return new AutoValue_Image(id, blobKey, timestamp);
}
public abstract long getId();
public abstract String blobKey();
public abstract long timestamp();
}
| src/main/java/com/google/sps/data/Image.java | Use AtuoValue for Image object class.
| src/main/java/com/google/sps/data/Image.java | Use AtuoValue for Image object class. | <ide><path>rc/main/java/com/google/sps/data/Image.java
<add>package com.google.sps.data;
<add>
<add>import com.google.auto.value.AutoValue;
<add>
<add>@AutoValue public abstract class Image{
<add>
<add> public static Image create(long id, String blobKey, long timestamp)
<add>{
<add> return new AutoValue_Image(id, blobKey, timestamp);
<add>}
<add>
<add> public abstract long getId();
<add> public abstract String blobKey();
<add> public abstract long timestamp();
<add>} |
|
Java | bsd-3-clause | ba8a02f749c95d0d1083ed1053c32be2b2adc8bb | 0 | inepex/ineform,inepex/ineform | package com.inepex.ineom.shared.assistedobject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.inepex.ineom.shared.IFConsts;
import com.inepex.ineom.shared.IneList;
import com.inepex.ineom.shared.Relation;
public class AssistedObjectUtil {
public static List<Long> getObjectIds(Collection<AssistedObject> objList){
List<Long> idList = new ArrayList<Long>();
for(AssistedObject obj : objList){
idList.add(obj.getId());
}
return idList;
}
public static String getObjectIdsAsString(Collection<AssistedObject> objList){
StringBuffer sb = new StringBuffer();
int i = 0;
for(AssistedObject obj : objList) {
sb.append(obj.getId());
if(i < objList.size() - 1)
sb.append(";");
i++;
}
return sb.toString();
}
public static String getObjectIdsAsStringWithCustomDelimeter(Collection<AssistedObject> objList, String delimeter){
StringBuffer sb = new StringBuffer();
int i = 0;
for(AssistedObject obj : objList) {
sb.append(obj.getId());
if(i < objList.size() - 1)
sb.append(delimeter);
i++;
}
return sb.toString();
}
public static String getIdFieldAsString(Collection<AssistedObject> objList, String idDescName){
StringBuffer sb = new StringBuffer();
int i = 0;
for(AssistedObject obj : objList) {
sb.append(obj.getLongUnchecked(idDescName));
if(i < objList.size() - 1)
sb.append(";");
i++;
}
return sb.toString();
}
public static String getRelationIdFieldAsString(Collection<AssistedObject> objList, String keyOfRelation){
StringBuffer sb = new StringBuffer();
int i = 0;
for(AssistedObject obj : objList) {
sb.append(obj.getRelationUnchecked(keyOfRelation).getId());
if(i < objList.size() - 1)
sb.append(";");
i++;
}
return sb.toString();
}
public static String createIdListString(Collection<Long> ids) {
StringBuffer sb = new StringBuffer();
int i = 0;
for(Long l : ids) {
sb.append(l);
if(i < ids.size() - 1)
sb.append(";");
i++;
}
return sb.toString();
}
public static List<Relation> mapObjectsToRelation(Collection<AssistedObject> objList){
return mapObjectsToRelation(objList, IFConsts.KEY_ID);
}
public static List<Relation> mapObjectsToRelation(Collection<AssistedObject> objList, String displayNameKey){
List<Relation> relations = new ArrayList<>();
for(AssistedObject obj : objList){
relations.add(new Relation(obj.getStringUnchecked(displayNameKey), obj));
}
return relations;
}
public static List<Long> getObjectIds(IneList ineList) {
List<Long> idList = new ArrayList<Long>();
for(Relation rel : ineList.getRelationList()) {
idList.add(rel.getId());
}
return idList;
}
}
| ineom/src/main/java/com/inepex/ineom/shared/assistedobject/AssistedObjectUtil.java | package com.inepex.ineom.shared.assistedobject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.inepex.ineom.shared.IFConsts;
import com.inepex.ineom.shared.IneList;
import com.inepex.ineom.shared.Relation;
public class AssistedObjectUtil {
public static List<Long> getObjectIds(Collection<AssistedObject> objList){
List<Long> idList = new ArrayList<Long>();
for(AssistedObject obj : objList){
idList.add(obj.getId());
}
return idList;
}
public static String getObjectIdsAsString(Collection<AssistedObject> objList){
StringBuffer sb = new StringBuffer();
int i = 0;
for(AssistedObject obj : objList) {
sb.append(obj.getId());
if(i < objList.size() - 1)
sb.append(";");
i++;
}
return sb.toString();
}
public static String getObjectIdsAsStringWithCustomDelimeter(Collection<AssistedObject> objList, String delimeter){
StringBuffer sb = new StringBuffer();
int i = 0;
for(AssistedObject obj : objList) {
sb.append(obj.getId());
if(i < objList.size() - 1)
sb.append(delimeter);
i++;
}
return sb.toString();
}
public static String getIdFieldAsString(Collection<AssistedObject> objList, String idDescName){
StringBuffer sb = new StringBuffer();
int i = 0;
for(AssistedObject obj : objList) {
sb.append(obj.getLongUnchecked(idDescName));
if(i < objList.size() - 1)
sb.append(";");
i++;
}
return sb.toString();
}
public static String getRelationIdFieldAsString(Collection<AssistedObject> objList, String keyOfRelation){
StringBuffer sb = new StringBuffer();
int i = 0;
for(AssistedObject obj : objList) {
sb.append(obj.getRelationUnchecked(keyOfRelation).getId());
if(i < objList.size() - 1)
sb.append(";");
i++;
}
return sb.toString();
}
public static String createIdListString(Collection<Long> ids) {
StringBuffer sb = new StringBuffer();
int i = 0;
for(Long l : ids) {
sb.append(l);
if(i < ids.size() - 1)
sb.append(";");
i++;
}
return sb.toString();
}
public static List<Relation> mapObjectsToRelation(Collection<AssistedObject> objList){
return mapObjectsToRelation(objList, IFConsts.KEY_ID);
}
public static List<Relation> mapObjectsToRelation(Collection<AssistedObject> objList, String displayNameKey){
List<Relation> relations = new ArrayList<>();
for(AssistedObject obj : objList){
relations.add(new Relation(obj.getStringUnchecked(displayNameKey), obj));
}
return relations;
}
public static List<Long> getObjectIds(IneList ineList) {
List<Long> idList = new ArrayList<Long>();
for(Relation rel : ineList.getRelationList()) {
idList.add(rel.getId());
}
return idList;
}
}
| remove whitespace | ineom/src/main/java/com/inepex/ineom/shared/assistedobject/AssistedObjectUtil.java | remove whitespace | <ide><path>neom/src/main/java/com/inepex/ineom/shared/assistedobject/AssistedObjectUtil.java
<ide> }
<ide> return idList;
<ide> }
<del>
<ide> } |
|
Java | apache-2.0 | cbbd798fb5230ffd0e213d5fd4898605c2e41dc5 | 0 | CMPUT301F16T10/Drivr | /*
* Copyright 2016 CMPUT301F16T10
*
* 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 ca.ualberta.cs.drivr;
/**
* A data class for storing user information.
*/
//TODO: I've just put everything in here to keep things simple, but we could just put the new things related to Drivers in the Driver class.
public class User {
private String name;
private String username;
private String phoneNumber;
private String email;
private String vehicleDescription;
private double rating;
private int totalRatings;
/**
* Instantiate a new User.
*/
public User() {
name = "";
username = "";
phoneNumber = "";
email = "";
vehicleDescription = "";
rating = 0;
totalRatings = 0;
}
/**
* Instantiate a new User.
* @param name The name of the user.
* @param username The username of the user.
*/
public User(String name, String username) {
this();
this.name = name;
this.username = username;
}
/**
* Get the name.
* @return The name.
*/
public String getName() {
return name;
}
/**
* Set the name.
* @param name The name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Get the username.
* @return The username.
*/
public String getUsername() {
return username;
}
/**
* Set the username.
* @param username The username.
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Get the phone number.
* @return The phone number.
*/
public String getPhoneNumber() {
return phoneNumber;
}
/**
* Set the phone number.
* @param phoneNumber The phone number.
*/
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
/**
* Get the email address.
* @return The email address.
*/
public String getEmail() {
return email;
}
/**
* Set the email address.
* @param email The email address.
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Get the driver's vehicle description.
* @return The vehicle description.
*/
public String getVehicleDescription() {
return vehicleDescription;
}
/**
* Set the driver's vehicle description.
* @param vehicleDescription The vehicle description.
*/
public void setVehicleDescription(String vehicleDescription) {
this.vehicleDescription = vehicleDescription;
}
/**
* Get the driver's rating.
* @return The rating.
*/
public double getRating() {
return rating;
}
/**
* Get the driver's rating.
* @param rating The rating.
*/
public void getRating(double rating) {
this.rating = rating;
}
/**
* Get the driver's total ratings.
* @return The total ratings.
*/
public int getTotalRatings() {
return totalRatings;
}
/**
* Set the driver's total ratings.
* @param totalRatings The total ratings.
*/
public void setTotalRatings(int totalRatings) {
this.totalRatings = totalRatings;
}
/**
* Changes the driver's rating by multiplying it by totalRatings to get his overall sum of
* ratings, then increases totalRatings by 1, adds the new rating to this rating then
* divides it by the new totalRatings.
*
* @param rating The rating given to the driver.
*/
public void changeRating(double rating) {
this.rating *= totalRatings;
totalRatings++;
this.rating += rating;
this.rating /= totalRatings;
}
}
| app/src/main/java/ca/ualberta/cs/drivr/User.java | /*
* Copyright 2016 CMPUT301F16T10
*
* 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 ca.ualberta.cs.drivr;
/**
* A data class for storing user information.
*/
public class User {
private String name;
private String username;
private String phoneNumber;
private String email;
private String vehicleDescription;
private double rating;
private int totalRatings;
/**
* Instantiate a new User.
*/
public User() {
name = "";
username = "";
phoneNumber = "";
email = "";
vehicleDescription = "";
rating = 0;
totalRatings = 0;
}
/**
* Instantiate a new User.
* @param name The name of the user.
* @param username The username of the user.
*/
public User(String name, String username) {
this();
this.name = name;
this.username = username;
}
/**
* Get the name.
* @return The name.
*/
public String getName() {
return name;
}
/**
* Set the name.
* @param name The name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Get the username.
* @return The username.
*/
public String getUsername() {
return username;
}
/**
* Set the username.
* @param username The username.
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Get the phone number.
* @return The phone number.
*/
public String getPhoneNumber() {
return phoneNumber;
}
/**
* Set the phone number.
* @param phoneNumber The phone number.
*/
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
/**
* Get the email address.
* @return The email address.
*/
public String getEmail() {
return email;
}
/**
* Set the email address.
* @param email The email address.
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Get the driver's vehicle description.
* @return The vehicle description.
*/
public String getVehicleDescription() {
return vehicleDescription;
}
/**
* Set the driver's vehicle description.
* @param vehicleDescription The vehicle description.
*/
public void setVehicleDescription(String vehicleDescription) {
this.vehicleDescription = vehicleDescription;
}
/**
* Get the driver's rating.
* @return The rating.
*/
public double getRating() {
return rating;
}
/**
* Get the driver's total ratings.
* @return The total ratings.
*/
public int getTotalRatings() {
return totalRatings;
}
/**
* Sets the driver's rating by multiplying it by totalRatings to get his overall sum of
* ratings, then increases totalRatings by 1, adds the new rating to this rating then
* divides it by the new totalRatings.
*
* @param rating The rating given to the driver.
*/
public void setRating(double rating) {
this.rating *= totalRatings;
totalRatings++;
this.rating += rating;
this.rating /= totalRatings;
}
}
| Quick change, added setters + TODO comment | app/src/main/java/ca/ualberta/cs/drivr/User.java | Quick change, added setters + TODO comment | <ide><path>pp/src/main/java/ca/ualberta/cs/drivr/User.java
<ide> /**
<ide> * A data class for storing user information.
<ide> */
<add>
<add>//TODO: I've just put everything in here to keep things simple, but we could just put the new things related to Drivers in the Driver class.
<ide> public class User {
<ide>
<ide> private String name;
<ide> public double getRating() {
<ide> return rating;
<ide> }
<add>
<add> /**
<add> * Get the driver's rating.
<add> * @param rating The rating.
<add> */
<add> public void getRating(double rating) {
<add> this.rating = rating;
<add> }
<ide>
<ide> /**
<ide> * Get the driver's total ratings.
<ide> public int getTotalRatings() {
<ide> return totalRatings;
<ide> }
<add>
<add> /**
<add> * Set the driver's total ratings.
<add> * @param totalRatings The total ratings.
<add> */
<add> public void setTotalRatings(int totalRatings) {
<add> this.totalRatings = totalRatings;
<add> }
<ide>
<ide> /**
<del> * Sets the driver's rating by multiplying it by totalRatings to get his overall sum of
<add> * Changes the driver's rating by multiplying it by totalRatings to get his overall sum of
<ide> * ratings, then increases totalRatings by 1, adds the new rating to this rating then
<ide> * divides it by the new totalRatings.
<ide> *
<ide> * @param rating The rating given to the driver.
<ide> */
<del> public void setRating(double rating) {
<add> public void changeRating(double rating) {
<ide> this.rating *= totalRatings;
<ide> totalRatings++;
<ide> this.rating += rating; |
|
Java | mit | 660a97d0bcd5baa8626937a856e1890f8b6ba74f | 0 | andreasb242/settlers-remake,JKatzwinkel/settlers-remake,jsettlers/settlers-remake,andreasb242/settlers-remake,andreasb242/settlers-remake,andreas-eberle/settlers-remake,phirschbeck/settlers-remake,Peter-Maximilian/settlers-remake,andreas-eberle/settlers-remake,phirschbeck/settlers-remake,jsettlers/settlers-remake,andreas-eberle/settlers-remake,phirschbeck/settlers-remake,jsettlers/settlers-remake | package jsettlers.common;
public final class Color {
public static final Color BLACK = new Color(0, 0, 0, 1);
public static final Color WHITE = new Color(1, 1, 1, 1);
public static final Color TRANSPARENT = new Color(0, 0, 0, 0);
public static final Color RED = new Color(1, 0, 0, 1);
public static final Color BLUE = new Color(0, 0, 1, 1);
public static final Color GREEN = new Color(0, 1, 0, 1);
public static final Color LIGHT_GREEN = new Color(0, 0.7f, 0, 1);
public static final Color ORANGE = new Color(1, 0.6f, 0, 1);
public static final Color CYAN = new Color(0, 1, 1, 1);
private final float blue;
private final float red;
private final float green;
private final float alpha;
private final int argb;
private final short shortColor;
public Color(int argb) {
this(argb, ((argb >> 16) & 0xff) / 255f, ((argb >> 8) & 0xff) / 255f,
((argb >> 0) & 0xff) / 255f, ((argb >> 24) & 0xff) / 255f);
}
private Color(float red, float green, float blue, float alpha) {
this(Color.getARGB(red, green, blue, alpha), red, green, blue, alpha);
}
private Color(int argb, float red, float green, float blue, float alpha) {
this.argb = argb;
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = alpha;
this.shortColor = toShortColorForced(1);
}
public final float getAlpha() {
return alpha;
}
public final float getBlue() {
return blue;
}
public final float getGreen() {
return green;
}
public final float getRed() {
return red;
}
public final int getARGB() {
return argb;
}
public final int getABGR() {
return (argb & 0xff00ff00) | ((argb & 0xff) << 16) | ((argb >> 16) & 0xff);
}
public static final int getARGB(float red, float green, float blue,
float alpha) {
return ((int) (alpha * 255) & 0xff) << 24
| ((int) (red * 255) & 0xff) << 16
| ((int) (green * 255) & 0xff) << 8
| ((int) (blue * 255) & 0xff);
}
public static final int getABGR(float red, float green, float blue, float alpha) {
return ((int) (alpha * 255) & 0xff) << 24 | ((int) (red * 255) & 0xff)
| ((int) (green * 255) & 0xff) << 8
| ((int) (blue * 255) & 0xff) << 16;
}
public short toShortColor(float multiply) {
if (multiply == 1) {
return shortColor;
} else if (multiply < 0) {
return BLACK.toShortColor(1);
} else {
return toShortColorForced(multiply);
}
}
private short toShortColorForced(float multiply) {
if (alpha < .1f) {
return 0;
} else {
return (short) ((int) (Math.min(1, red * multiply) * 0x1f) << 11
| (int) (Math.min(1, green * multiply) * 0x1f) << 6
| (int) (Math.min(1, blue * multiply) * 0x1f) << 1 | 1);
}
}
public static Color fromShort(short s) {
return new Color((float) (s >> 11 & 0x1f) / 0x1f,
(float) (s >> 6 & 0x1f) / 0x1f, (float) (s >> 1 & 0x1f) / 0x1f,
s & 1);
}
}
| src/jsettlers/common/Color.java | package jsettlers.common;
public final class Color {
public static final Color BLACK = new Color(0, 0, 0, 1);
public static final Color WHITE = new Color(1, 1, 1, 1);
public static final Color TRANSPARENT = new Color(0, 0, 0, 0);
public static final Color RED = new Color(1, 0, 0, 1);
public static final Color BLUE = new Color(0, 0, 1, 1);
public static final Color GREEN = new Color(0, 1, 0, 1);
public static final Color LIGHT_GREEN = new Color(0, 0.7f, 0, 1);
public static final Color ORANGE = new Color(1, 0.6f, 0, 1);
public static final Color CYAN = new Color(0, 1, 1, 1);
private final float blue;
private final float red;
private final float green;
private final float alpha;
private final int argb;
private final short shortColor;
public Color(int argb) {
this(argb, ((argb >> 16) & 0xff) / 255f,
((argb >> 8) & 0xff) / 255f, ((argb >> 0) & 0xff) / 255f, ((argb >> 24) & 0xff) / 255f);
}
private Color(float red, float green, float blue, float alpha) {
this(Color.getARGB(red, green, blue, alpha), red, green, blue, alpha);
}
private Color(int argb, float red, float green, float blue, float alpha) {
this.argb = argb;
this.red = red;
this.green = green;
this.blue = blue;
this.alpha = alpha;
this.shortColor = toShortColorForced(1);
}
public final float getAlpha() {
return alpha;
}
public final float getBlue() {
return blue;
}
public final float getGreen() {
return green;
}
public final float getRed() {
return red;
}
public final int getARGB() {
return argb;
}
public static final int getARGB(float red, float green, float blue,
float alpha) {
return ((int) (alpha * 255) & 0xff) << 24
| ((int) (red * 255) & 0xff) << 16
| ((int) (green * 255) & 0xff) << 8
| ((int) (blue * 255) & 0xff);
}
public short toShortColor(float multiply) {
if (multiply == 1) {
return shortColor;
} else if (multiply < 0) {
return BLACK.toShortColor(1);
} else {
return toShortColorForced(multiply);
}
}
private short toShortColorForced(float multiply) {
if (alpha < .1f) {
return 0;
} else {
return (short) ((int) (Math.min(1, red * multiply) * 0x1f) << 11
| (int) (Math.min(1, green * multiply) * 0x1f) << 6
| (int) (Math.min(1, blue * multiply) * 0x1f) << 1 | 1);
}
}
public static Color fromShort(short s) {
return new Color((float) (s >> 11 & 0x1f) / 0x1f,
(float) (s >> 6 & 0x1f) / 0x1f, (float) (s >> 1 & 0x1f) / 0x1f,
s & 1);
}
}
| Fixed movable/mapo object colors (they were RGB, but must be BGR)
| src/jsettlers/common/Color.java | Fixed movable/mapo object colors (they were RGB, but must be BGR) | <ide><path>rc/jsettlers/common/Color.java
<ide> private final short shortColor;
<ide>
<ide> public Color(int argb) {
<del> this(argb, ((argb >> 16) & 0xff) / 255f,
<del> ((argb >> 8) & 0xff) / 255f, ((argb >> 0) & 0xff) / 255f, ((argb >> 24) & 0xff) / 255f);
<add> this(argb, ((argb >> 16) & 0xff) / 255f, ((argb >> 8) & 0xff) / 255f,
<add> ((argb >> 0) & 0xff) / 255f, ((argb >> 24) & 0xff) / 255f);
<ide> }
<ide>
<ide> private Color(float red, float green, float blue, float alpha) {
<ide> public final int getARGB() {
<ide> return argb;
<ide> }
<add>
<add> public final int getABGR() {
<add> return (argb & 0xff00ff00) | ((argb & 0xff) << 16) | ((argb >> 16) & 0xff);
<add> }
<ide>
<ide> public static final int getARGB(float red, float green, float blue,
<ide> float alpha) {
<ide> | ((int) (red * 255) & 0xff) << 16
<ide> | ((int) (green * 255) & 0xff) << 8
<ide> | ((int) (blue * 255) & 0xff);
<add> }
<add>
<add> public static final int getABGR(float red, float green, float blue, float alpha) {
<add> return ((int) (alpha * 255) & 0xff) << 24 | ((int) (red * 255) & 0xff)
<add> | ((int) (green * 255) & 0xff) << 8
<add> | ((int) (blue * 255) & 0xff) << 16;
<ide> }
<ide>
<ide> public short toShortColor(float multiply) {
<ide> (float) (s >> 6 & 0x1f) / 0x1f, (float) (s >> 1 & 0x1f) / 0x1f,
<ide> s & 1);
<ide> }
<add>
<ide> } |
|
Java | apache-2.0 | f9b282e6360ebf8fb73ac555b6f0ace8fc9ad4c7 | 0 | alexjyong/FlowSpaceFirewall,ajragusa/FlowSpaceFirewall,ajragusa/FlowSpaceFirewall,thompsbp/FlowSpaceFirewall,thompsbp/FlowSpaceFirewall,thompsbp/FlowSpaceFirewall,jab1982/FlowSpaceFirewall,GlobalNOC/FlowSpaceFirewall,alexjyong/FlowSpaceFirewall,jab1982/FlowSpaceFirewall,jab1982/FlowSpaceFirewall,GlobalNOC/FlowSpaceFirewall,alexjyong/FlowSpaceFirewall,ajragusa/FlowSpaceFirewall,GlobalNOC/FlowSpaceFirewall | /*
Copyright 2013 Trustees of Indiana 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.iu.grnoc.flowspace_firewall;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.easymock.*;
import static org.junit.Assert.*;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.core.ImmutablePort;
import org.junit.Test;
import org.junit.Before;
import org.openflow.protocol.OFMatch;
import org.openflow.protocol.Wildcards.Flag;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.action.OFActionOutput;
import org.openflow.protocol.action.OFActionVirtualLanIdentifier;
import org.openflow.protocol.statistics.OFFlowStatisticsReply;
import org.openflow.protocol.statistics.OFStatistics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
public class FlowStatSlicerTest {
List <OFStatistics> allowedStats;
List <OFStatistics> noAllowedStats;
List <OFStatistics> mixedStats;
IOFSwitch sw;
VLANSlicer slicer;
PortConfig pConfig;
PortConfig pConfig2;
PortConfig pConfig3;
PortConfig pConfig5;
protected static Logger log = LoggerFactory.getLogger(FlowStatSlicerTest.class);
@Rule
public ExpectedException thrown = ExpectedException.none();
public void buildAllowedStats(){
List<OFAction> actions = new ArrayList<OFAction>();
OFActionOutput output = new OFActionOutput();
output.setPort((short)1);
actions.add(output);
OFMatch match = new OFMatch();
match.setInputPort((short)1);
match.setDataLayerVirtualLan((short)100);
match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
//all allowed stats
allowedStats = new ArrayList<OFStatistics>();
OFFlowStatisticsReply stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123126L);
allowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)2);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)2);
match.setDataLayerVirtualLan((short)102);
match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123125L);
allowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)3);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)3);
match.setDataLayerVirtualLan((short)103);
match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123124L);
allowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)5);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)5);
match.setDataLayerVirtualLan((short)105);
match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123123L);
allowedStats.add(stat);
}
public void buildNoAllowedStats(){
//no allowed stats
noAllowedStats = new ArrayList<OFStatistics>();
List<OFAction> actions = new ArrayList<OFAction>();
OFActionOutput output = new OFActionOutput();
output.setPort((short)1);
actions.add(output);
OFMatch match = new OFMatch();
match.setInputPort((short)1);
match.setDataLayerVirtualLan((short)300);
OFFlowStatisticsReply stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123126L);
noAllowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)2);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)2);
match.setDataLayerVirtualLan((short)202);
match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123125L);
noAllowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)3);
OFActionVirtualLanIdentifier setVid = new OFActionVirtualLanIdentifier();
setVid.setVirtualLanIdentifier((short)300);
actions.add(setVid);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)3);
match.setDataLayerVirtualLan((short)103);
match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123124L);
noAllowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)4);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)5);
match.setDataLayerVirtualLan((short)105);
match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123123L);
noAllowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)4);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)5);
match.setDataLayerVirtualLan((short)105);
match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123123L);
noAllowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)5);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)4);
match.setDataLayerVirtualLan((short)105);
match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123123L);
noAllowedStats.add(stat);
}
public void buildMixedStats(){
//a mixed set of stats some allowed some not allowed
mixedStats = new ArrayList<OFStatistics>();
}
@Before
public void buildStats(){
buildAllowedStats();
buildNoAllowedStats();
buildMixedStats();
}
@Before
public void buildSlicer(){
ArrayList <ImmutablePort> ports = new ArrayList <ImmutablePort>();
ImmutablePort p = createMock(ImmutablePort.class);
expect(p.getName()).andReturn("foo").anyTimes();
expect(p.getPortNumber()).andReturn((short)1).anyTimes();
EasyMock.replay(p);
ports.add(p);
ImmutablePort p2 = createMock(ImmutablePort.class);
expect(p2.getName()).andReturn("foo2").anyTimes();
expect(p2.getPortNumber()).andReturn((short)2).anyTimes();
EasyMock.replay(p2);
ports.add(p2);
ImmutablePort p3 = createMock(ImmutablePort.class);
expect(p3.getName()).andReturn("foo3").anyTimes();
expect(p3.getPortNumber()).andReturn((short)3).anyTimes();
EasyMock.replay(p3);
ports.add(p3);
ImmutablePort p4 = createMock(ImmutablePort.class);
expect(p4.getName()).andReturn("foo4").anyTimes();
expect(p4.getPortNumber()).andReturn((short)4).anyTimes();
EasyMock.replay(p4);
ports.add(p4);
ImmutablePort p5 = createMock(ImmutablePort.class);
expect(p5.getName()).andReturn("foo5").anyTimes();
expect(p5.getPortNumber()).andReturn((short)5).anyTimes();
EasyMock.replay(p5);
ports.add(p5);
sw = createMock(IOFSwitch.class);
expect(sw.getId()).andReturn(0L).anyTimes();
expect(sw.getStringId()).andReturn("0000000").anyTimes();
expect(sw.getPort((short)1)).andReturn(p).anyTimes();
expect(sw.getPort((short)2)).andReturn(p2).anyTimes();
expect(sw.getPort((short)3)).andReturn(p3).anyTimes();
expect(sw.getPort((short)4)).andReturn(p4).anyTimes();
expect(sw.getPort((short)5)).andReturn(p5).anyTimes();
expect(sw.getPort((short)100)).andReturn(null).anyTimes();
expect(sw.getPort((short)-1)).andReturn(null).anyTimes();
expect(sw.getPorts()).andReturn((Collection <ImmutablePort>) ports).anyTimes();
EasyMock.replay(sw);
assertNotNull("switch id is not null", sw.getId());
assertNotNull("switch port is not null", sw.getPort((short)1));
assertEquals("ports == sw.getPorts()", ports, sw.getPorts());
slicer = new VLANSlicer();
pConfig = new PortConfig();
pConfig.setPortName("foo");
VLANRange range = new VLANRange();
range.setVlanAvail((short)100,true);
range.setVlanAvail((short)1000,true);
pConfig.setVLANRange(range);
slicer.setPortConfig("foo", pConfig);
pConfig2 = new PortConfig();
pConfig.setPortName("foo2");
range = new VLANRange();
range.setVlanAvail((short)102,true);
range.setVlanAvail((short)1000,true);
pConfig2.setVLANRange(range);
slicer.setPortConfig("foo2", pConfig2);
pConfig3 = new PortConfig();
pConfig.setPortName("foo3");
range = new VLANRange();
range.setVlanAvail((short)103,true);
range.setVlanAvail((short)1000,true);
pConfig3.setVLANRange(range);
slicer.setPortConfig("foo3", pConfig3);
pConfig5 = new PortConfig();
pConfig.setPortName("foo5");
range = new VLANRange();
range.setVlanAvail((short)105,true);
range.setVlanAvail((short)1000,true);
pConfig5.setVLANRange(range);
slicer.setPortConfig("foo5", pConfig5);
slicer.setSwitch(sw);
}
@Test
public void testSliceStatsAllAllowed() {
List <OFStatistics> slicedStats = FlowStatSlicer.SliceStats(slicer, allowedStats);
assertEquals("Number of sliced stat is same as number of total stats", allowedStats.size(),slicedStats.size());
}
@Test
public void testSliceStatsMixed(){
//List <OFStatistics> slicedStats = FlowStatSlicer.SliceStats(slicer, mixedStats);
}
@Test
public void testSliceStatsNull(){
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("FlowStat slicer got null stats!!");
@SuppressWarnings("unused")
List <OFStatistics> slicedStats = FlowStatSlicer.SliceStats(slicer, null);
}
@Test
public void testSliceStatsNonAllowed(){
List <OFStatistics> slicedStats = FlowStatSlicer.SliceStats(slicer, noAllowedStats);
assertNotNull("Sliced Stats with no allowed stats returned ok",slicedStats);
assertEquals("Sliced stats", slicedStats.size(),0);
}
@Test
public void testSliceStatsNoStats(){
List <OFStatistics> slicedStats = FlowStatSlicer.SliceStats(slicer, new ArrayList<OFStatistics>());
assertNotNull("Sliced Stats with no allowed stats returned ok",slicedStats);
assertEquals("Sliced stats", 0, slicedStats.size());
}
}
| src/test/java/edu/iu/grnoc/flowspace_firewall/FlowStatSlicerTest.java | /*
Copyright 2013 Trustees of Indiana 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.iu.grnoc.flowspace_firewall;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.easymock.*;
import static org.junit.Assert.*;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.core.ImmutablePort;
import org.junit.Test;
import org.junit.Before;
import org.openflow.protocol.OFMatch;
import org.openflow.protocol.Wildcards.Flag;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.action.OFActionOutput;
import org.openflow.protocol.action.OFActionVirtualLanIdentifier;
import org.openflow.protocol.statistics.OFFlowStatisticsReply;
import org.openflow.protocol.statistics.OFStatistics;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
public class FlowStatSlicerTest {
List <OFStatistics> allowedStats;
List <OFStatistics> noAllowedStats;
List <OFStatistics> mixedStats;
IOFSwitch sw;
VLANSlicer slicer;
PortConfig pConfig;
PortConfig pConfig2;
PortConfig pConfig3;
PortConfig pConfig5;
@Rule
public ExpectedException thrown = ExpectedException.none();
public void buildAllowedStats(){
List<OFAction> actions = new ArrayList<OFAction>();
OFActionOutput output = new OFActionOutput();
output.setPort((short)1);
actions.add(output);
OFMatch match = new OFMatch();
match.setInputPort((short)1);
match.setDataLayerVirtualLan((short)100);
//all allowed stats
allowedStats = new ArrayList<OFStatistics>();
OFFlowStatisticsReply stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123126L);
allowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)2);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)2);
match.setDataLayerVirtualLan((short)102);
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123125L);
allowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)3);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)3);
match.setDataLayerVirtualLan((short)103);
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123124L);
allowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)5);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)5);
match.setDataLayerVirtualLan((short)105);
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123123L);
allowedStats.add(stat);
}
public void buildNoAllowedStats(){
//no allowed stats
noAllowedStats = new ArrayList<OFStatistics>();
List<OFAction> actions = new ArrayList<OFAction>();
OFActionOutput output = new OFActionOutput();
output.setPort((short)1);
actions.add(output);
OFMatch match = new OFMatch();
match.setInputPort((short)1);
match.setDataLayerVirtualLan((short)300);
OFFlowStatisticsReply stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123126L);
noAllowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)2);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)2);
match.setDataLayerVirtualLan((short)202);
match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123125L);
noAllowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)3);
OFActionVirtualLanIdentifier setVid = new OFActionVirtualLanIdentifier();
setVid.setVirtualLanIdentifier((short)300);
actions.add(setVid);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)3);
match.setDataLayerVirtualLan((short)103);
match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123124L);
noAllowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)4);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)5);
match.setDataLayerVirtualLan((short)105);
match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123123L);
noAllowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)4);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)5);
match.setDataLayerVirtualLan((short)105);
match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123123L);
noAllowedStats.add(stat);
actions = new ArrayList<OFAction>();
output = new OFActionOutput();
output.setPort((short)5);
actions.add(output);
match = new OFMatch();
match.setInputPort((short)4);
match.setDataLayerVirtualLan((short)105);
match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
stat = new OFFlowStatisticsReply();
stat.setActions(actions);
stat.setMatch(match);
stat.setByteCount(123123L);
noAllowedStats.add(stat);
}
public void buildMixedStats(){
//a mixed set of stats some allowed some not allowed
mixedStats = new ArrayList<OFStatistics>();
}
@Before
public void buildStats(){
buildAllowedStats();
buildNoAllowedStats();
buildMixedStats();
}
@Before
public void buildSlicer(){
ArrayList <ImmutablePort> ports = new ArrayList <ImmutablePort>();
ImmutablePort p = createMock(ImmutablePort.class);
expect(p.getName()).andReturn("foo").anyTimes();
expect(p.getPortNumber()).andReturn((short)1).anyTimes();
EasyMock.replay(p);
ports.add(p);
ImmutablePort p2 = createMock(ImmutablePort.class);
expect(p2.getName()).andReturn("foo2").anyTimes();
expect(p2.getPortNumber()).andReturn((short)2).anyTimes();
EasyMock.replay(p2);
ports.add(p2);
ImmutablePort p3 = createMock(ImmutablePort.class);
expect(p3.getName()).andReturn("foo3").anyTimes();
expect(p3.getPortNumber()).andReturn((short)3).anyTimes();
EasyMock.replay(p3);
ports.add(p3);
ImmutablePort p4 = createMock(ImmutablePort.class);
expect(p4.getName()).andReturn("foo4").anyTimes();
expect(p4.getPortNumber()).andReturn((short)4).anyTimes();
EasyMock.replay(p4);
ports.add(p4);
ImmutablePort p5 = createMock(ImmutablePort.class);
expect(p5.getName()).andReturn("foo5").anyTimes();
expect(p5.getPortNumber()).andReturn((short)5).anyTimes();
EasyMock.replay(p5);
ports.add(p5);
sw = createMock(IOFSwitch.class);
expect(sw.getId()).andReturn(0L).anyTimes();
expect(sw.getStringId()).andReturn("0000000").anyTimes();
expect(sw.getPort((short)1)).andReturn(p).anyTimes();
expect(sw.getPort((short)2)).andReturn(p2).anyTimes();
expect(sw.getPort((short)3)).andReturn(p3).anyTimes();
expect(sw.getPort((short)4)).andReturn(p4).anyTimes();
expect(sw.getPort((short)5)).andReturn(p5).anyTimes();
expect(sw.getPort((short)100)).andReturn(null).anyTimes();
expect(sw.getPort((short)-1)).andReturn(null).anyTimes();
expect(sw.getPorts()).andReturn((Collection <ImmutablePort>) ports).anyTimes();
EasyMock.replay(sw);
assertNotNull("switch id is not null", sw.getId());
assertNotNull("switch port is not null", sw.getPort((short)1));
assertEquals("ports == sw.getPorts()", ports, sw.getPorts());
slicer = new VLANSlicer();
pConfig = new PortConfig();
pConfig.setPortName("foo");
VLANRange range = new VLANRange();
range.setVlanAvail((short)100,true);
range.setVlanAvail((short)1000,true);
pConfig.setVLANRange(range);
slicer.setPortConfig("foo", pConfig);
pConfig2 = new PortConfig();
pConfig.setPortName("foo2");
range = new VLANRange();
range.setVlanAvail((short)102,true);
range.setVlanAvail((short)1000,true);
pConfig2.setVLANRange(range);
slicer.setPortConfig("foo2", pConfig2);
pConfig3 = new PortConfig();
pConfig.setPortName("foo3");
range = new VLANRange();
range.setVlanAvail((short)103,true);
range.setVlanAvail((short)1000,true);
pConfig3.setVLANRange(range);
slicer.setPortConfig("foo3", pConfig3);
pConfig5 = new PortConfig();
pConfig.setPortName("foo5");
range = new VLANRange();
range.setVlanAvail((short)105,true);
range.setVlanAvail((short)1000,true);
pConfig5.setVLANRange(range);
slicer.setPortConfig("foo5", pConfig5);
slicer.setSwitch(sw);
}
@Test
public void testSliceStatsAllAllowed() {
List <OFStatistics> slicedStats = FlowStatSlicer.SliceStats(slicer, allowedStats);
assertEquals("Number of sliced stat is same as number of total stats", allowedStats.size(),slicedStats.size());
}
@Test
public void testSliceStatsMixed(){
//List <OFStatistics> slicedStats = FlowStatSlicer.SliceStats(slicer, mixedStats);
}
@Test
public void testSliceStatsNull(){
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("FlowStat slicer got null stats!!");
@SuppressWarnings("unused")
List <OFStatistics> slicedStats = FlowStatSlicer.SliceStats(slicer, null);
}
@Test
public void testSliceStatsNonAllowed(){
List <OFStatistics> slicedStats = FlowStatSlicer.SliceStats(slicer, noAllowedStats);
assertNotNull("Sliced Stats with no allowed stats returned ok",slicedStats);
assertEquals("Sliced stats", slicedStats.size(),0);
}
@Test
public void testSliceStatsNoStats(){
List <OFStatistics> slicedStats = FlowStatSlicer.SliceStats(slicer, new ArrayList<OFStatistics>());
assertNotNull("Sliced Stats with no allowed stats returned ok",slicedStats);
assertEquals("Sliced stats", 0, slicedStats.size());
}
}
| finished fixing tests
| src/test/java/edu/iu/grnoc/flowspace_firewall/FlowStatSlicerTest.java | finished fixing tests | <ide><path>rc/test/java/edu/iu/grnoc/flowspace_firewall/FlowStatSlicerTest.java
<ide> import org.openflow.protocol.action.OFActionVirtualLanIdentifier;
<ide> import org.openflow.protocol.statistics.OFFlowStatisticsReply;
<ide> import org.openflow.protocol.statistics.OFStatistics;
<add>import org.slf4j.Logger;
<add>import org.slf4j.LoggerFactory;
<ide>
<ide> import org.junit.Rule;
<ide> import org.junit.rules.ExpectedException;
<ide> PortConfig pConfig2;
<ide> PortConfig pConfig3;
<ide> PortConfig pConfig5;
<add> protected static Logger log = LoggerFactory.getLogger(FlowStatSlicerTest.class);
<ide>
<ide> @Rule
<ide> public ExpectedException thrown = ExpectedException.none();
<ide> OFMatch match = new OFMatch();
<ide> match.setInputPort((short)1);
<ide> match.setDataLayerVirtualLan((short)100);
<del>
<add> match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
<add> match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
<ide> //all allowed stats
<ide> allowedStats = new ArrayList<OFStatistics>();
<ide> OFFlowStatisticsReply stat = new OFFlowStatisticsReply();
<ide> match = new OFMatch();
<ide> match.setInputPort((short)2);
<ide> match.setDataLayerVirtualLan((short)102);
<add> match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
<add> match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
<ide> stat = new OFFlowStatisticsReply();
<ide> stat.setActions(actions);
<ide> stat.setMatch(match);
<ide> match = new OFMatch();
<ide> match.setInputPort((short)3);
<ide> match.setDataLayerVirtualLan((short)103);
<add> match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
<add> match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
<ide> stat = new OFFlowStatisticsReply();
<ide> stat.setActions(actions);
<ide> stat.setMatch(match);
<ide> match = new OFMatch();
<ide> match.setInputPort((short)5);
<ide> match.setDataLayerVirtualLan((short)105);
<add> match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
<add> match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
<ide> stat = new OFFlowStatisticsReply();
<ide> stat.setActions(actions);
<ide> stat.setMatch(match);
<ide> match.setDataLayerVirtualLan((short)105);
<ide> match.setWildcards(match.getWildcardObj().matchOn(Flag.DL_VLAN));
<ide> match.setWildcards(match.getWildcardObj().matchOn(Flag.IN_PORT));
<add>
<ide> stat = new OFFlowStatisticsReply();
<ide> stat.setActions(actions);
<ide> stat.setMatch(match); |
|
Java | mit | 73ab503149db3e517f7302be3555da5d7fffa1f3 | 0 | danielgindi/android-helpers | package com.dg.helpers;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Checkable;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
/**
* Created by Daniel Cohen Gindi ([email protected])
*/
public class DismissSoftkeyboardHelper
{
public static void setupUI(final Context context, View view)
{
if (view == null) return;
String viewPackageName = view.getClass().getPackage().getName();
String viewClassName = view.getClass().getSimpleName();
if ((view instanceof EditText) ||
(view instanceof Button) ||
(view instanceof ImageButton) ||
(view instanceof Checkable) ||
(view instanceof DatePicker) ||
(view instanceof AdapterView) ||
(Build.VERSION.SDK_INT >= 11 && view instanceof android.widget.NumberPicker) ||
(view instanceof android.widget.RadioGroup) ||
(view instanceof android.widget.TimePicker) ||
(Build.VERSION.SDK_INT >= 21 && view instanceof android.widget.Toolbar) ||
(viewPackageName.equals("android.widget") && viewClassName.equals("Toolbar")) ||
(viewClassName.equals("TextInputLayout")))
{
return;
}
view.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
hideSoftKeyboard(context);
return false;
}
});
if (view instanceof ViewGroup)
{
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++)
{
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(context, innerView);
}
}
}
public static void hideSoftKeyboard(Context context)
{
try
{
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(), 0);
}
catch (Exception ex)
{
}
}
} | Helpers/src/main/java/com/dg/helpers/DismissSoftkeyboardHelper.java | package com.dg.helpers;
import android.app.Activity;
import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Checkable;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
/**
* Created by Daniel Cohen Gindi ([email protected])
*/
public class DismissSoftkeyboardHelper
{
public static void setupUI(final Context context, View view)
{
if (view == null) return;
if ((view instanceof EditText) ||
(view instanceof Button) ||
(view instanceof ImageButton) ||
(view instanceof Checkable) ||
(view instanceof DatePicker) ||
(view instanceof AdapterView) ||
(view instanceof android.widget.NumberPicker) ||
(view instanceof android.widget.RadioGroup) ||
(view instanceof android.widget.TimePicker) ||
(view instanceof android.widget.Toolbar) ||
(view.getClass().getSimpleName().equals("TextInputLayout")))
{
return;
}
view.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
hideSoftKeyboard(context);
return false;
}
});
if (view instanceof ViewGroup)
{
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++)
{
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(context, innerView);
}
}
}
public static void hideSoftKeyboard(Context context)
{
try
{
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(), 0);
}
catch (Exception ex)
{
}
}
} | Fix class not found on API < 21 when calling setupUI
| Helpers/src/main/java/com/dg/helpers/DismissSoftkeyboardHelper.java | Fix class not found on API < 21 when calling setupUI | <ide><path>elpers/src/main/java/com/dg/helpers/DismissSoftkeyboardHelper.java
<ide>
<ide> import android.app.Activity;
<ide> import android.content.Context;
<add>import android.os.Build;
<ide> import android.view.MotionEvent;
<ide> import android.view.View;
<ide> import android.view.ViewGroup;
<ide> {
<ide> if (view == null) return;
<ide>
<add> String viewPackageName = view.getClass().getPackage().getName();
<add> String viewClassName = view.getClass().getSimpleName();
<add>
<ide> if ((view instanceof EditText) ||
<ide> (view instanceof Button) ||
<ide> (view instanceof ImageButton) ||
<ide> (view instanceof Checkable) ||
<ide> (view instanceof DatePicker) ||
<ide> (view instanceof AdapterView) ||
<del> (view instanceof android.widget.NumberPicker) ||
<add> (Build.VERSION.SDK_INT >= 11 && view instanceof android.widget.NumberPicker) ||
<ide> (view instanceof android.widget.RadioGroup) ||
<ide> (view instanceof android.widget.TimePicker) ||
<del> (view instanceof android.widget.Toolbar) ||
<del> (view.getClass().getSimpleName().equals("TextInputLayout")))
<add> (Build.VERSION.SDK_INT >= 21 && view instanceof android.widget.Toolbar) ||
<add> (viewPackageName.equals("android.widget") && viewClassName.equals("Toolbar")) ||
<add> (viewClassName.equals("TextInputLayout")))
<ide> {
<ide> return;
<ide> } |
|
Java | apache-2.0 | ff56becc88bd26e41b0491d65643aa2e6ed80d32 | 0 | madanadit/alluxio,maboelhassan/alluxio,calvinjia/tachyon,wwjiang007/alluxio,calvinjia/tachyon,maobaolong/alluxio,ChangerYoung/alluxio,jswudi/alluxio,ShailShah/alluxio,Reidddddd/mo-alluxio,calvinjia/tachyon,jsimsa/alluxio,wwjiang007/alluxio,Reidddddd/mo-alluxio,Reidddddd/alluxio,madanadit/alluxio,maboelhassan/alluxio,wwjiang007/alluxio,Reidddddd/alluxio,Reidddddd/mo-alluxio,maobaolong/alluxio,uronce-cc/alluxio,EvilMcJerkface/alluxio,Reidddddd/alluxio,Alluxio/alluxio,madanadit/alluxio,apc999/alluxio,bf8086/alluxio,ShailShah/alluxio,aaudiber/alluxio,riversand963/alluxio,jswudi/alluxio,apc999/alluxio,Alluxio/alluxio,Reidddddd/mo-alluxio,wwjiang007/alluxio,jsimsa/alluxio,aaudiber/alluxio,calvinjia/tachyon,EvilMcJerkface/alluxio,Alluxio/alluxio,Alluxio/alluxio,bf8086/alluxio,apc999/alluxio,Alluxio/alluxio,aaudiber/alluxio,apc999/alluxio,WilliamZapata/alluxio,madanadit/alluxio,apc999/alluxio,riversand963/alluxio,uronce-cc/alluxio,maobaolong/alluxio,EvilMcJerkface/alluxio,WilliamZapata/alluxio,EvilMcJerkface/alluxio,uronce-cc/alluxio,wwjiang007/alluxio,PasaLab/tachyon,maboelhassan/alluxio,calvinjia/tachyon,PasaLab/tachyon,maobaolong/alluxio,apc999/alluxio,PasaLab/tachyon,calvinjia/tachyon,EvilMcJerkface/alluxio,maboelhassan/alluxio,aaudiber/alluxio,uronce-cc/alluxio,jswudi/alluxio,apc999/alluxio,ChangerYoung/alluxio,uronce-cc/alluxio,riversand963/alluxio,ChangerYoung/alluxio,EvilMcJerkface/alluxio,jswudi/alluxio,maobaolong/alluxio,Reidddddd/alluxio,PasaLab/tachyon,ShailShah/alluxio,riversand963/alluxio,calvinjia/tachyon,aaudiber/alluxio,riversand963/alluxio,jsimsa/alluxio,calvinjia/tachyon,maboelhassan/alluxio,WilliamZapata/alluxio,maobaolong/alluxio,bf8086/alluxio,uronce-cc/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio,WilliamZapata/alluxio,WilliamZapata/alluxio,maobaolong/alluxio,Reidddddd/mo-alluxio,Reidddddd/alluxio,madanadit/alluxio,Alluxio/alluxio,maboelhassan/alluxio,ShailShah/alluxio,Alluxio/alluxio,ChangerYoung/alluxio,WilliamZapata/alluxio,maobaolong/alluxio,PasaLab/tachyon,jswudi/alluxio,jswudi/alluxio,madanadit/alluxio,aaudiber/alluxio,ShailShah/alluxio,PasaLab/tachyon,bf8086/alluxio,bf8086/alluxio,aaudiber/alluxio,maboelhassan/alluxio,Reidddddd/alluxio,wwjiang007/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,ShailShah/alluxio,PasaLab/tachyon,wwjiang007/alluxio,jsimsa/alluxio,madanadit/alluxio,bf8086/alluxio,ChangerYoung/alluxio,Alluxio/alluxio,riversand963/alluxio,madanadit/alluxio,wwjiang007/alluxio,maobaolong/alluxio,Reidddddd/alluxio,wwjiang007/alluxio,ChangerYoung/alluxio,bf8086/alluxio,jsimsa/alluxio,bf8086/alluxio,jsimsa/alluxio,Alluxio/alluxio | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.client.lineage;
import alluxio.Configuration;
import alluxio.PropertyKey;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Tests {@link LineageContext}.
*/
public final class LineageContextTest {
/**
* Tests the concurrency of the {@link LineageContext}.
*/
@Test
public void concurrency() throws Exception {
final List<LineageMasterClient> clients = new ArrayList<>();
// acquire all the clients
for (int i = 0; i < Configuration.getInt(PropertyKey.USER_LINEAGE_MASTER_CLIENT_THREADS); i++) {
clients.add(LineageContext.INSTANCE.acquireMasterClient());
}
(new Thread(new AcquireClient())).start();
// wait for thread to run
Thread.sleep(5L);
// release all the clients
for (LineageMasterClient client : clients) {
LineageContext.INSTANCE.releaseMasterClient(client);
}
}
class AcquireClient implements Runnable {
@Override
public void run() {
LineageMasterClient client = null;
try {
client = LineageContext.INSTANCE.acquireMasterClient();
} catch (IOException e) {
Assert.fail("Failed to acquire a lineage master client due to interruption occured.");
} finally {
LineageContext.INSTANCE.releaseMasterClient(client);
}
}
}
}
| core/client/src/test/java/alluxio/client/lineage/LineageContextTest.java | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.client.lineage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import alluxio.Configuration;
import alluxio.PropertyKey;
/**
* Tests {@link LineageContext}.
*/
public final class LineageContextTest {
/**
* Tests the concurrency of the {@link LineageContext}.
*/
@Test
public void concurrency() throws Exception {
final List<LineageMasterClient> clients = new ArrayList<>();
// acquire all the clients
for (int i = 0; i < Configuration.getInt(PropertyKey.USER_LINEAGE_MASTER_CLIENT_THREADS); i++) {
clients.add(LineageContext.INSTANCE.acquireMasterClient());
}
(new Thread(new AcquireClient())).start();
// wait for thread to run
Thread.sleep(5L);
// release all the clients
for (LineageMasterClient client : clients) {
LineageContext.INSTANCE.releaseMasterClient(client);
}
}
class AcquireClient implements Runnable {
@Override
public void run() {
LineageMasterClient client = null;
try {
client = LineageContext.INSTANCE.acquireMasterClient();
} catch (IOException e) {
Assert.fail("Failed to acquire a lineage master client due to interruption occured.");
} finally {
LineageContext.INSTANCE.releaseMasterClient(client);
}
}
}
}
| Adjust packages order to pass the checkstyle.
| core/client/src/test/java/alluxio/client/lineage/LineageContextTest.java | Adjust packages order to pass the checkstyle. | <ide><path>ore/client/src/test/java/alluxio/client/lineage/LineageContextTest.java
<ide>
<ide> package alluxio.client.lineage;
<ide>
<del>import java.io.IOException;
<del>import java.util.ArrayList;
<del>import java.util.List;
<add>import alluxio.Configuration;
<add>import alluxio.PropertyKey;
<ide>
<ide> import org.junit.Assert;
<ide> import org.junit.Test;
<ide>
<del>import alluxio.Configuration;
<del>import alluxio.PropertyKey;
<add>import java.io.IOException;
<add>import java.util.ArrayList;
<add>import java.util.List;
<ide>
<ide> /**
<ide> * Tests {@link LineageContext}. |
|
Java | mit | 67812e1c154a7bc6bb87aa1709616d0b6adb5763 | 0 | gman-x/jdungeonquest | package jdungeonquest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jdungeonquest.effects.Effect;
import jdungeonquest.effects.GiveGold;
import org.yaml.snakeyaml.Yaml;
public class CardHolder {
public Deck dragonDeck = new Deck();
public Deck doorDeck = new Deck();
public Deck corpseDeck = new Deck();
public Deck cryptDeck = new Deck();
public Deck trapDeck = new Deck();
public Deck searchDeck = new Deck();
public Deck roomDeck = new Deck();
public Deck treasureDeck = new Deck();
public Deck monsterDeck = new Deck();
Map<Integer, Card> cardsMap = new HashMap<Integer, Card>();
public CardHolder(){
initializeCards();
}
private void initializeCards(){
Yaml yaml = new Yaml();
List<Card> allCards;
allCards = (ArrayList<Card>) yaml.load(CardHolder.class.getResourceAsStream("/Cards.yaml"));
int currentCard = 0;
for(Card card: allCards){
cardsMap.put(currentCard, card);
currentCard++;
switch(card.getDeckType()){
case Dragon:
dragonDeck.putCard(card);
break;
case Door:
doorDeck.putCard(card);
break;
case Corpse:
corpseDeck.putCard(card);
break;
case Crypt:
cryptDeck.putCard(card);
break;
case Trap:
trapDeck.putCard(card);
break;
case Search:
searchDeck.putCard(card);
break;
case Room:
roomDeck.putCard(card);
break;
case Treasure:
treasureDeck.putCard(card);
break;
case Monster:
monsterDeck.putCard(card);
break;
default: break;
}
}
dragonDeck.shuffle();
doorDeck.shuffle();
corpseDeck.shuffle();
cryptDeck.shuffle();
trapDeck.shuffle();
searchDeck.shuffle();
roomDeck.shuffle();
treasureDeck.shuffle();
monsterDeck.shuffle();
}
}
| src/main/java/jdungeonquest/CardHolder.java | package jdungeonquest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jdungeonquest.effects.Effect;
import jdungeonquest.effects.GiveGold;
import org.yaml.snakeyaml.Yaml;
public class CardHolder {
public Deck dragonDeck = new Deck();
public Deck doorDeck = new Deck();
public Deck corpseDeck = new Deck();
public Deck cryptDeck = new Deck();
public Deck trapDeck = new Deck();
public Deck searchDeck = new Deck();
public Deck roomDeck = new Deck();
public Deck treasureDeck = new Deck();
public Deck monsterDeck = new Deck();
Map<Integer, Card> cardsMap = new HashMap<Integer, Card>();
public CardHolder(){
initializeCards();
}
private void initializeCards(){
Yaml yaml = new Yaml();
List<Card> allCards;
allCards = (ArrayList<Card>) yaml.load(CardHolder.class.getResourceAsStream("/Cards.yaml"));
int currentCard = 0;
for(Card card: allCards){
cardsMap.put(currentCard, card);
currentCard++;
switch(card.getDeckType()){
case Dragon:
dragonDeck.putCard(card);
break;
case Door:
doorDeck.putCard(card);
break;
case Corpse:
corpseDeck.putCard(card);
break;
case Crypt:
cryptDeck.putCard(card);
break;
case Trap:
trapDeck.putCard(card);
break;
case Search:
searchDeck.putCard(card);
break;
case Room:
roomDeck.putCard(card);
break;
case Treasure:
treasureDeck.putCard(card);
break;
case Monster:
monsterDeck.putCard(card);
break;
default: break;
}
}
}
}
| Card decks are now shuffled on initialization
| src/main/java/jdungeonquest/CardHolder.java | Card decks are now shuffled on initialization | <ide><path>rc/main/java/jdungeonquest/CardHolder.java
<ide> default: break;
<ide> }
<ide> }
<add> dragonDeck.shuffle();
<add> doorDeck.shuffle();
<add> corpseDeck.shuffle();
<add> cryptDeck.shuffle();
<add> trapDeck.shuffle();
<add> searchDeck.shuffle();
<add> roomDeck.shuffle();
<add> treasureDeck.shuffle();
<add> monsterDeck.shuffle();
<ide> }
<ide> } |
|
Java | mit | 61ecba37e43a9f8bdfecc81918ebcde7fbd7ede4 | 0 | bitDecayGames/GlobalGameJam2017 | package com.bitdecay.game.system;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;
import com.bitdecay.game.component.PositionComponent;
import com.bitdecay.game.component.RemoveNowComponent;
import com.bitdecay.game.component.SonarPingComponent;
import com.bitdecay.game.gameobject.MyGameObject;
import com.bitdecay.game.room.AbstractRoom;
import com.bitdecay.game.system.abstracted.AbstractDrawableSystem;
/**
* Created by Monday on 1/21/2017.
*/
public class SonarPingSystem extends AbstractDrawableSystem {
public float propagationSpeed = 6f;
public float maxSonarRange = 4000f;
public SonarPingSystem(AbstractRoom room) {
super(room);
}
@Override
protected boolean validateGob(MyGameObject gob) {
return gob.hasComponents(PositionComponent.class, SonarPingComponent.class);
}
@Override
public void preDraw(SpriteBatch spriteBatch, OrthographicCamera camera) {
DrawSystem.pingShader.begin();
gobs.forEach(gob -> {
gob.forEachComponentDo(SonarPingComponent.class, ping -> {
ping.radius += propagationSpeed;
if (ping.radius <= maxSonarRange){
DrawSystem.pingShader.setUniformf("f_sweepRadius", ping.radius);
} else {
gob.addComponent(new RemoveNowComponent(gob));
DrawSystem.pingShader.setUniformf("f_sweepRadius", 0);
}
});
gob.forEachComponentDo(PositionComponent.class, pos -> {
Vector3 projected = camera.project(new Vector3(pos.x, pos.y, 0));
DrawSystem.pingShader.setUniformf("v_center",projected.x, projected.y);
});
});
DrawSystem.pingShader.end();
}
@Override
public void draw(SpriteBatch spriteBatch, OrthographicCamera camera) {
// no op
}
}
| src/main/java/com/bitdecay/game/system/SonarPingSystem.java | package com.bitdecay.game.system;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;
import com.bitdecay.game.component.PositionComponent;
import com.bitdecay.game.component.RemoveNowComponent;
import com.bitdecay.game.component.SonarPingComponent;
import com.bitdecay.game.gameobject.MyGameObject;
import com.bitdecay.game.room.AbstractRoom;
import com.bitdecay.game.system.abstracted.AbstractDrawableSystem;
/**
* Created by Monday on 1/21/2017.
*/
public class SonarPingSystem extends AbstractDrawableSystem {
public float propagationSpeed = 6f;
public float maxSonarRange = 2000f;
public SonarPingSystem(AbstractRoom room) {
super(room);
}
@Override
protected boolean validateGob(MyGameObject gob) {
return gob.hasComponents(PositionComponent.class, SonarPingComponent.class);
}
@Override
public void preDraw(SpriteBatch spriteBatch, OrthographicCamera camera) {
DrawSystem.pingShader.begin();
gobs.forEach(gob -> {
gob.forEachComponentDo(SonarPingComponent.class, ping -> {
ping.radius += propagationSpeed;
if (ping.radius > maxSonarRange){
gob.addComponent(new RemoveNowComponent(gob));
}
DrawSystem.pingShader.setUniformf("f_sweepRadius", ping.radius);
});
gob.forEachComponentDo(PositionComponent.class, pos -> {
Vector3 projected = camera.project(new Vector3(pos.x, pos.y, 0));
DrawSystem.pingShader.setUniformf("v_center",projected.x, projected.y);
});
});
DrawSystem.pingShader.end();
}
@Override
public void draw(SpriteBatch spriteBatch, OrthographicCamera camera) {
// no op
}
}
| fix sonar
| src/main/java/com/bitdecay/game/system/SonarPingSystem.java | fix sonar | <ide><path>rc/main/java/com/bitdecay/game/system/SonarPingSystem.java
<ide> */
<ide> public class SonarPingSystem extends AbstractDrawableSystem {
<ide> public float propagationSpeed = 6f;
<del> public float maxSonarRange = 2000f;
<add> public float maxSonarRange = 4000f;
<ide>
<ide> public SonarPingSystem(AbstractRoom room) {
<ide> super(room);
<ide> gobs.forEach(gob -> {
<ide> gob.forEachComponentDo(SonarPingComponent.class, ping -> {
<ide> ping.radius += propagationSpeed;
<del> if (ping.radius > maxSonarRange){
<add> if (ping.radius <= maxSonarRange){
<add> DrawSystem.pingShader.setUniformf("f_sweepRadius", ping.radius);
<add> } else {
<ide> gob.addComponent(new RemoveNowComponent(gob));
<add> DrawSystem.pingShader.setUniformf("f_sweepRadius", 0);
<ide> }
<del> DrawSystem.pingShader.setUniformf("f_sweepRadius", ping.radius);
<ide> });
<ide>
<ide> gob.forEachComponentDo(PositionComponent.class, pos -> { |
|
Java | apache-2.0 | 1bc30d9de2074549e590a956b31007e72dd12b18 | 0 | YMartsynkevych/camel,veithen/camel,punkhorn/camel-upstream,yury-vashchyla/camel,christophd/camel,adessaigne/camel,bfitzpat/camel,oscerd/camel,josefkarasek/camel,noelo/camel,driseley/camel,manuelh9r/camel,atoulme/camel,yury-vashchyla/camel,YMartsynkevych/camel,alvinkwekel/camel,davidwilliams1978/camel,punkhorn/camel-upstream,apache/camel,partis/camel,sabre1041/camel,jarst/camel,snurmine/camel,ge0ffrey/camel,bdecoste/camel,w4tson/camel,sverkera/camel,yuruki/camel,grange74/camel,RohanHart/camel,CandleCandle/camel,arnaud-deprez/camel,haku/camel,aaronwalker/camel,jameszkw/camel,tkopczynski/camel,allancth/camel,rmarting/camel,Thopap/camel,mgyongyosi/camel,skinzer/camel,duro1/camel,engagepoint/camel,stravag/camel,stravag/camel,RohanHart/camel,dsimansk/camel,DariusX/camel,pax95/camel,NetNow/camel,bfitzpat/camel,onders86/camel,gnodet/camel,jkorab/camel,royopa/camel,gilfernandes/camel,partis/camel,sabre1041/camel,edigrid/camel,NetNow/camel,drsquidop/camel,nboukhed/camel,NickCis/camel,trohovsky/camel,isururanawaka/camel,NetNow/camel,oscerd/camel,tlehoux/camel,mike-kukla/camel,josefkarasek/camel,pkletsko/camel,ssharma/camel,bfitzpat/camel,ramonmaruko/camel,maschmid/camel,ekprayas/camel,scranton/camel,igarashitm/camel,mgyongyosi/camel,nicolaferraro/camel,bdecoste/camel,NetNow/camel,bhaveshdt/camel,lburgazzoli/camel,tdiesler/camel,scranton/camel,snadakuduru/camel,JYBESSON/camel,iweiss/camel,NickCis/camel,erwelch/camel,askannon/camel,davidkarlsen/camel,mnki/camel,yuruki/camel,trohovsky/camel,gautric/camel,brreitme/camel,satishgummadelli/camel,lburgazzoli/camel,chirino/camel,anoordover/camel,joakibj/camel,haku/camel,snurmine/camel,igarashitm/camel,aaronwalker/camel,manuelh9r/camel,jonmcewen/camel,salikjan/camel,mnki/camel,oalles/camel,edigrid/camel,chanakaudaya/camel,stalet/camel,grange74/camel,apache/camel,anton-k11/camel,dmvolod/camel,coderczp/camel,JYBESSON/camel,jlpedrosa/camel,nikhilvibhav/camel,pax95/camel,pplatek/camel,borcsokj/camel,davidkarlsen/camel,Fabryprog/camel,oalles/camel,FingolfinTEK/camel,alvinkwekel/camel,JYBESSON/camel,sverkera/camel,jollygeorge/camel,sverkera/camel,dmvolod/camel,pmoerenhout/camel,MohammedHammam/camel,isururanawaka/camel,acartapanis/camel,YoshikiHigo/camel,dpocock/camel,rmarting/camel,punkhorn/camel-upstream,woj-i/camel,ge0ffrey/camel,MrCoder/camel,brreitme/camel,JYBESSON/camel,acartapanis/camel,adessaigne/camel,prashant2402/camel,manuelh9r/camel,YoshikiHigo/camel,chirino/camel,igarashitm/camel,erwelch/camel,woj-i/camel,jarst/camel,lasombra/camel,dkhanolkar/camel,w4tson/camel,askannon/camel,jkorab/camel,pplatek/camel,duro1/camel,gilfernandes/camel,ullgren/camel,arnaud-deprez/camel,mgyongyosi/camel,skinzer/camel,erwelch/camel,jamesnetherton/camel,onders86/camel,isavin/camel,borcsokj/camel,woj-i/camel,jpav/camel,akhettar/camel,christophd/camel,koscejev/camel,jameszkw/camel,nikvaessen/camel,MohammedHammam/camel,iweiss/camel,sirlatrom/camel,oscerd/camel,dsimansk/camel,grgrzybek/camel,FingolfinTEK/camel,johnpoth/camel,woj-i/camel,mgyongyosi/camel,haku/camel,oalles/camel,isururanawaka/camel,yogamaha/camel,gnodet/camel,tadayosi/camel,ramonmaruko/camel,sverkera/camel,gyc567/camel,yuruki/camel,chirino/camel,objectiser/camel,tarilabs/camel,cunningt/camel,askannon/camel,rmarting/camel,grange74/camel,snadakuduru/camel,partis/camel,nikhilvibhav/camel,Fabryprog/camel,FingolfinTEK/camel,tarilabs/camel,tdiesler/camel,askannon/camel,isavin/camel,qst-jdc-labs/camel,edigrid/camel,tdiesler/camel,isavin/camel,w4tson/camel,tlehoux/camel,YMartsynkevych/camel,ekprayas/camel,erwelch/camel,royopa/camel,zregvart/camel,jpav/camel,dmvolod/camel,jkorab/camel,christophd/camel,jonmcewen/camel,chanakaudaya/camel,sirlatrom/camel,gautric/camel,NickCis/camel,dpocock/camel,CodeSmell/camel,JYBESSON/camel,haku/camel,josefkarasek/camel,mzapletal/camel,sebi-hgdata/camel,cunningt/camel,snadakuduru/camel,anton-k11/camel,mohanaraosv/camel,pkletsko/camel,bgaudaen/camel,oalles/camel,ekprayas/camel,lburgazzoli/apache-camel,prashant2402/camel,mohanaraosv/camel,gyc567/camel,borcsokj/camel,joakibj/camel,jarst/camel,mzapletal/camel,pkletsko/camel,mgyongyosi/camel,josefkarasek/camel,bdecoste/camel,edigrid/camel,tadayosi/camel,pplatek/camel,scranton/camel,grgrzybek/camel,partis/camel,bgaudaen/camel,duro1/camel,neoramon/camel,grange74/camel,partis/camel,adessaigne/camel,allancth/camel,mcollovati/camel,ssharma/camel,isururanawaka/camel,FingolfinTEK/camel,coderczp/camel,tarilabs/camel,gilfernandes/camel,sebi-hgdata/camel,cunningt/camel,tdiesler/camel,logzio/camel,davidwilliams1978/camel,CodeSmell/camel,satishgummadelli/camel,coderczp/camel,rparree/camel,YoshikiHigo/camel,christophd/camel,jamesnetherton/camel,dpocock/camel,jameszkw/camel,josefkarasek/camel,CodeSmell/camel,pplatek/camel,ssharma/camel,nboukhed/camel,stalet/camel,logzio/camel,isavin/camel,rparree/camel,yogamaha/camel,royopa/camel,bgaudaen/camel,tkopczynski/camel,anton-k11/camel,jmandawg/camel,dvankleef/camel,grange74/camel,noelo/camel,logzio/camel,tkopczynski/camel,davidwilliams1978/camel,anoordover/camel,jarst/camel,gnodet/camel,lowwool/camel,jollygeorge/camel,snurmine/camel,sabre1041/camel,objectiser/camel,stravag/camel,ramonmaruko/camel,neoramon/camel,stravag/camel,borcsokj/camel,isururanawaka/camel,veithen/camel,JYBESSON/camel,bhaveshdt/camel,eformat/camel,jkorab/camel,ssharma/camel,hqstevenson/camel,YMartsynkevych/camel,NickCis/camel,lburgazzoli/apache-camel,grgrzybek/camel,mohanaraosv/camel,lburgazzoli/apache-camel,kevinearls/camel,maschmid/camel,nikvaessen/camel,ekprayas/camel,atoulme/camel,maschmid/camel,kevinearls/camel,rmarting/camel,stalet/camel,bfitzpat/camel,davidkarlsen/camel,skinzer/camel,pkletsko/camel,YMartsynkevych/camel,gautric/camel,Thopap/camel,chirino/camel,CandleCandle/camel,bdecoste/camel,hqstevenson/camel,YoshikiHigo/camel,isururanawaka/camel,pplatek/camel,arnaud-deprez/camel,drsquidop/camel,logzio/camel,jpav/camel,eformat/camel,trohovsky/camel,tlehoux/camel,skinzer/camel,jamesnetherton/camel,koscejev/camel,pax95/camel,atoulme/camel,johnpoth/camel,jmandawg/camel,DariusX/camel,pplatek/camel,grgrzybek/camel,iweiss/camel,johnpoth/camel,yogamaha/camel,veithen/camel,prashant2402/camel,mnki/camel,rparree/camel,sirlatrom/camel,logzio/camel,neoramon/camel,johnpoth/camel,anton-k11/camel,punkhorn/camel-upstream,jonmcewen/camel,RohanHart/camel,yogamaha/camel,MrCoder/camel,scranton/camel,brreitme/camel,ge0ffrey/camel,gautric/camel,stravag/camel,nikvaessen/camel,askannon/camel,nboukhed/camel,oalles/camel,sabre1041/camel,cunningt/camel,jmandawg/camel,haku/camel,mnki/camel,MohammedHammam/camel,joakibj/camel,yogamaha/camel,mcollovati/camel,ekprayas/camel,allancth/camel,w4tson/camel,sirlatrom/camel,yuruki/camel,anoordover/camel,eformat/camel,tlehoux/camel,pax95/camel,snadakuduru/camel,neoramon/camel,curso007/camel,MrCoder/camel,nicolaferraro/camel,sverkera/camel,anoordover/camel,dvankleef/camel,bhaveshdt/camel,oscerd/camel,lasombra/camel,sverkera/camel,pmoerenhout/camel,royopa/camel,nicolaferraro/camel,DariusX/camel,MohammedHammam/camel,joakibj/camel,onders86/camel,pmoerenhout/camel,dmvolod/camel,eformat/camel,Thopap/camel,iweiss/camel,ge0ffrey/camel,sebi-hgdata/camel,ssharma/camel,snadakuduru/camel,mike-kukla/camel,chanakaudaya/camel,bdecoste/camel,mike-kukla/camel,tkopczynski/camel,acartapanis/camel,jonmcewen/camel,brreitme/camel,dkhanolkar/camel,MohammedHammam/camel,manuelh9r/camel,tadayosi/camel,zregvart/camel,mzapletal/camel,koscejev/camel,Thopap/camel,lowwool/camel,CandleCandle/camel,CandleCandle/camel,chirino/camel,prashant2402/camel,atoulme/camel,qst-jdc-labs/camel,yuruki/camel,apache/camel,jlpedrosa/camel,anoordover/camel,kevinearls/camel,jmandawg/camel,jamesnetherton/camel,dkhanolkar/camel,bfitzpat/camel,lburgazzoli/apache-camel,NetNow/camel,rparree/camel,hqstevenson/camel,iweiss/camel,mohanaraosv/camel,FingolfinTEK/camel,sirlatrom/camel,tarilabs/camel,veithen/camel,allancth/camel,igarashitm/camel,qst-jdc-labs/camel,rparree/camel,veithen/camel,atoulme/camel,igarashitm/camel,allancth/camel,trohovsky/camel,hqstevenson/camel,gyc567/camel,nikhilvibhav/camel,drsquidop/camel,josefkarasek/camel,jkorab/camel,curso007/camel,snadakuduru/camel,mike-kukla/camel,christophd/camel,chanakaudaya/camel,mzapletal/camel,mcollovati/camel,yogamaha/camel,tlehoux/camel,drsquidop/camel,duro1/camel,zregvart/camel,satishgummadelli/camel,tlehoux/camel,dvankleef/camel,dvankleef/camel,RohanHart/camel,dkhanolkar/camel,rparree/camel,pax95/camel,driseley/camel,jmandawg/camel,allancth/camel,grgrzybek/camel,lasombra/camel,edigrid/camel,MrCoder/camel,tarilabs/camel,CandleCandle/camel,lburgazzoli/apache-camel,haku/camel,woj-i/camel,davidwilliams1978/camel,ullgren/camel,gyc567/camel,bhaveshdt/camel,igarashitm/camel,jlpedrosa/camel,duro1/camel,oalles/camel,apache/camel,onders86/camel,jpav/camel,nikvaessen/camel,satishgummadelli/camel,lburgazzoli/apache-camel,DariusX/camel,coderczp/camel,skinzer/camel,koscejev/camel,snurmine/camel,dpocock/camel,sebi-hgdata/camel,yury-vashchyla/camel,akhettar/camel,rmarting/camel,sabre1041/camel,yury-vashchyla/camel,driseley/camel,coderczp/camel,jollygeorge/camel,engagepoint/camel,sebi-hgdata/camel,salikjan/camel,manuelh9r/camel,dvankleef/camel,dsimansk/camel,jameszkw/camel,nicolaferraro/camel,cunningt/camel,dsimansk/camel,jmandawg/camel,kevinearls/camel,dmvolod/camel,jlpedrosa/camel,MohammedHammam/camel,ekprayas/camel,aaronwalker/camel,akhettar/camel,gilfernandes/camel,lowwool/camel,maschmid/camel,acartapanis/camel,pplatek/camel,atoulme/camel,prashant2402/camel,Fabryprog/camel,arnaud-deprez/camel,satishgummadelli/camel,mnki/camel,yury-vashchyla/camel,Fabryprog/camel,lburgazzoli/camel,ssharma/camel,mike-kukla/camel,hqstevenson/camel,noelo/camel,erwelch/camel,mike-kukla/camel,noelo/camel,arnaud-deprez/camel,eformat/camel,johnpoth/camel,objectiser/camel,alvinkwekel/camel,dsimansk/camel,nikhilvibhav/camel,pmoerenhout/camel,eformat/camel,logzio/camel,yuruki/camel,dpocock/camel,nikvaessen/camel,adessaigne/camel,trohovsky/camel,scranton/camel,lburgazzoli/camel,ramonmaruko/camel,duro1/camel,adessaigne/camel,CodeSmell/camel,bfitzpat/camel,driseley/camel,rmarting/camel,ullgren/camel,snurmine/camel,ramonmaruko/camel,davidkarlsen/camel,maschmid/camel,drsquidop/camel,isavin/camel,lasombra/camel,mgyongyosi/camel,YoshikiHigo/camel,jonmcewen/camel,MrCoder/camel,neoramon/camel,curso007/camel,grange74/camel,YMartsynkevych/camel,nboukhed/camel,MrCoder/camel,pkletsko/camel,drsquidop/camel,sebi-hgdata/camel,jarst/camel,chanakaudaya/camel,akhettar/camel,nboukhed/camel,lburgazzoli/camel,borcsokj/camel,davidwilliams1978/camel,qst-jdc-labs/camel,kevinearls/camel,jkorab/camel,mzapletal/camel,tkopczynski/camel,bgaudaen/camel,anoordover/camel,ge0ffrey/camel,johnpoth/camel,grgrzybek/camel,iweiss/camel,hqstevenson/camel,anton-k11/camel,pmoerenhout/camel,gnodet/camel,tadayosi/camel,pax95/camel,gyc567/camel,stalet/camel,cunningt/camel,jpav/camel,Thopap/camel,jpav/camel,prashant2402/camel,stalet/camel,bdecoste/camel,joakibj/camel,bgaudaen/camel,gautric/camel,Thopap/camel,adessaigne/camel,NickCis/camel,jollygeorge/camel,woj-i/camel,chirino/camel,partis/camel,FingolfinTEK/camel,pmoerenhout/camel,RohanHart/camel,dkhanolkar/camel,lasombra/camel,lowwool/camel,mnki/camel,ge0ffrey/camel,erwelch/camel,edigrid/camel,noelo/camel,chanakaudaya/camel,royopa/camel,gyc567/camel,NickCis/camel,jameszkw/camel,brreitme/camel,jonmcewen/camel,w4tson/camel,mcollovati/camel,objectiser/camel,dmvolod/camel,bgaudaen/camel,oscerd/camel,anton-k11/camel,tdiesler/camel,bhaveshdt/camel,onders86/camel,manuelh9r/camel,gautric/camel,royopa/camel,mohanaraosv/camel,lowwool/camel,stravag/camel,jlpedrosa/camel,curso007/camel,driseley/camel,mohanaraosv/camel,borcsokj/camel,snurmine/camel,nikvaessen/camel,joakibj/camel,onders86/camel,isavin/camel,yury-vashchyla/camel,jarst/camel,curso007/camel,tkopczynski/camel,jollygeorge/camel,tadayosi/camel,davidwilliams1978/camel,brreitme/camel,scranton/camel,coderczp/camel,gilfernandes/camel,bhaveshdt/camel,CandleCandle/camel,maschmid/camel,mzapletal/camel,trohovsky/camel,jollygeorge/camel,engagepoint/camel,kevinearls/camel,alvinkwekel/camel,sirlatrom/camel,dkhanolkar/camel,jamesnetherton/camel,jlpedrosa/camel,christophd/camel,aaronwalker/camel,w4tson/camel,RohanHart/camel,sabre1041/camel,qst-jdc-labs/camel,qst-jdc-labs/camel,lasombra/camel,lowwool/camel,aaronwalker/camel,arnaud-deprez/camel,lburgazzoli/camel,YoshikiHigo/camel,aaronwalker/camel,curso007/camel,veithen/camel,koscejev/camel,skinzer/camel,akhettar/camel,oscerd/camel,stalet/camel,apache/camel,akhettar/camel,ramonmaruko/camel,tdiesler/camel,NetNow/camel,gilfernandes/camel,jamesnetherton/camel,acartapanis/camel,neoramon/camel,dpocock/camel,zregvart/camel,koscejev/camel,ullgren/camel,askannon/camel,dsimansk/camel,dvankleef/camel,engagepoint/camel,driseley/camel,tadayosi/camel,pkletsko/camel,apache/camel,tarilabs/camel,acartapanis/camel,jameszkw/camel,noelo/camel,satishgummadelli/camel,gnodet/camel,logzio/camel,engagepoint/camel,nboukhed/camel | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.test.junit4;
import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import org.apache.camel.CamelContext;
import org.apache.camel.Channel;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.InvalidPayloadException;
import org.apache.camel.Message;
import org.apache.camel.Predicate;
import org.apache.camel.Processor;
import org.apache.camel.Route;
import org.apache.camel.builder.Builder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.builder.ValueBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.DefaultExchange;
import org.apache.camel.processor.DelegateProcessor;
import org.apache.camel.util.ExchangeHelper;
import org.apache.camel.util.PredicateAssertHelper;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A bunch of useful testing methods
*
* @version
*/
public abstract class TestSupport extends Assert {
protected static final String LS = System.getProperty("line.separator");
private static final Logger LOG = LoggerFactory.getLogger(TestSupport.class);
protected transient Logger log = LoggerFactory.getLogger(getClass());
// CHECKSTYLE:OFF
@Rule
public TestName testName = new TestName();
// CHECKSTYLE:ON
// Builder methods for expressions used when testing
// -------------------------------------------------------------------------
/**
* Returns a value builder for the given header
*/
public static ValueBuilder header(String name) {
return Builder.header(name);
}
/**
* Returns a value builder for the given property
*/
public static ValueBuilder property(String name) {
return Builder.property(name);
}
/**
* Returns a predicate and value builder for the inbound body on an exchange
*/
public static ValueBuilder body() {
return Builder.body();
}
/**
* Returns a predicate and value builder for the inbound message body as a
* specific type
*/
public static <T> ValueBuilder bodyAs(Class<T> type) {
return Builder.bodyAs(type);
}
/**
* Returns a predicate and value builder for the outbound body on an
* exchange
*/
public static ValueBuilder outBody() {
return Builder.outBody();
}
/**
* Returns a predicate and value builder for the outbound message body as a
* specific type
*/
public static <T> ValueBuilder outBodyAs(Class<T> type) {
return Builder.outBodyAs(type);
}
/**
* Returns a predicate and value builder for the fault body on an
* exchange
*/
public static ValueBuilder faultBody() {
return Builder.faultBody();
}
/**
* Returns a predicate and value builder for the fault message body as a
* specific type
*/
public static <T> ValueBuilder faultBodyAs(Class<T> type) {
return Builder.faultBodyAs(type);
}
/**
* Returns a value builder for the given system property
*/
public static ValueBuilder systemProperty(String name) {
return Builder.systemProperty(name);
}
/**
* Returns a value builder for the given system property
*/
public static ValueBuilder systemProperty(String name, String defaultValue) {
return Builder.systemProperty(name, defaultValue);
}
// Assertions
// -----------------------------------------------------------------------
public static <T> T assertIsInstanceOf(Class<T> expectedType, Object value) {
assertNotNull("Expected an instance of type: " + expectedType.getName() + " but was null", value);
assertTrue("object should be a " + expectedType.getName() + " but was: " + value + " with type: "
+ value.getClass().getName(), expectedType.isInstance(value));
return expectedType.cast(value);
}
public static void assertEndpointUri(Endpoint endpoint, String uri) {
assertNotNull("Endpoint is null when expecting endpoint for: " + uri, endpoint);
assertEquals("Endoint uri for: " + endpoint, uri, endpoint.getEndpointUri());
}
/**
* Asserts the In message on the exchange contains the expected value
*/
public static Object assertInMessageHeader(Exchange exchange, String name, Object expected) {
return assertMessageHeader(exchange.getIn(), name, expected);
}
/**
* Asserts the Out message on the exchange contains the expected value
*/
public static Object assertOutMessageHeader(Exchange exchange, String name, Object expected) {
return assertMessageHeader(exchange.getOut(), name, expected);
}
/**
* Asserts that the given exchange has an OUT message of the given body value
*
* @param exchange the exchange which should have an OUT message
* @param expected the expected value of the OUT message
* @throws InvalidPayloadException is thrown if the payload is not the expected class type
*/
public static void assertInMessageBodyEquals(Exchange exchange, Object expected) throws InvalidPayloadException {
assertNotNull("Should have a response exchange!", exchange);
Object actual;
if (expected == null) {
actual = ExchangeHelper.getMandatoryInBody(exchange);
assertEquals("in body of: " + exchange, expected, actual);
} else {
actual = ExchangeHelper.getMandatoryInBody(exchange, expected.getClass());
}
assertEquals("in body of: " + exchange, expected, actual);
LOG.debug("Received response: " + exchange + " with in: " + exchange.getIn());
}
/**
* Asserts that the given exchange has an OUT message of the given body value
*
* @param exchange the exchange which should have an OUT message
* @param expected the expected value of the OUT message
* @throws InvalidPayloadException is thrown if the payload is not the expected class type
*/
public static void assertOutMessageBodyEquals(Exchange exchange, Object expected) throws InvalidPayloadException {
assertNotNull("Should have a response exchange!", exchange);
Object actual;
if (expected == null) {
actual = ExchangeHelper.getMandatoryOutBody(exchange);
assertEquals("output body of: " + exchange, expected, actual);
} else {
actual = ExchangeHelper.getMandatoryOutBody(exchange, expected.getClass());
}
assertEquals("output body of: " + exchange, expected, actual);
LOG.debug("Received response: " + exchange + " with out: " + exchange.getOut());
}
public static Object assertMessageHeader(Message message, String name, Object expected) {
Object value = message.getHeader(name);
assertEquals("Header: " + name + " on Message: " + message, expected, value);
return value;
}
/**
* Asserts that the given expression when evaluated returns the given answer
*/
public static Object assertExpression(Expression expression, Exchange exchange, Object expected) {
Object value;
if (expected != null) {
value = expression.evaluate(exchange, expected.getClass());
} else {
value = expression.evaluate(exchange, Object.class);
}
LOG.debug("Evaluated expression: " + expression + " on exchange: " + exchange + " result: " + value);
assertEquals("Expression: " + expression + " on Exchange: " + exchange, expected, value);
return value;
}
/**
* Asserts that the predicate returns the expected value on the exchange
*/
public static void assertPredicateMatches(Predicate predicate, Exchange exchange) {
assertPredicate(predicate, exchange, true);
}
/**
* Asserts that the predicate returns the expected value on the exchange
*/
public static void assertPredicateDoesNotMatch(Predicate predicate, Exchange exchange) {
try {
PredicateAssertHelper.assertMatches(predicate, "Predicate should match: ", exchange);
} catch (AssertionError e) {
LOG.debug("Caught expected assertion error: " + e);
}
assertPredicate(predicate, exchange, false);
}
/**
* Asserts that the predicate returns the expected value on the exchange
*/
public static boolean assertPredicate(final Predicate predicate, Exchange exchange, boolean expected) {
if (expected) {
PredicateAssertHelper.assertMatches(predicate, "Predicate failed: ", exchange);
}
boolean value = predicate.matches(exchange);
LOG.debug("Evaluated predicate: " + predicate + " on exchange: " + exchange + " result: " + value);
assertEquals("Predicate: " + predicate + " on Exchange: " + exchange, expected, value);
return value;
}
/**
* Resolves an endpoint and asserts that it is found
*/
public static Endpoint resolveMandatoryEndpoint(CamelContext context, String uri) {
Endpoint endpoint = context.getEndpoint(uri);
assertNotNull("No endpoint found for URI: " + uri, endpoint);
return endpoint;
}
/**
* Resolves an endpoint and asserts that it is found
*/
public static <T extends Endpoint> T resolveMandatoryEndpoint(CamelContext context, String uri,
Class<T> endpointType) {
T endpoint = context.getEndpoint(uri, endpointType);
assertNotNull("No endpoint found for URI: " + uri, endpoint);
return endpoint;
}
/**
* Creates an exchange with the given body
*/
protected Exchange createExchangeWithBody(CamelContext camelContext, Object body) {
Exchange exchange = new DefaultExchange(camelContext);
Message message = exchange.getIn();
message.setHeader("testClass", getClass().getName());
message.setBody(body);
return exchange;
}
public static <T> T assertOneElement(List<T> list) {
assertEquals("Size of list should be 1: " + list, 1, list.size());
return list.get(0);
}
/**
* Asserts that a list is of the given size
*/
public static <T> List<T> assertListSize(List<T> list, int size) {
return assertListSize("List", list, size);
}
/**
* Asserts that a list is of the given size
*/
public static <T> List<T> assertListSize(String message, List<T> list, int size) {
assertEquals(message + " should be of size: "
+ size + " but is: " + list, size, list.size());
return list;
}
/**
* Asserts that a list is of the given size
*/
public static <T> Collection<T> assertCollectionSize(Collection<T> list, int size) {
return assertCollectionSize("List", list, size);
}
/**
* Asserts that a list is of the given size
*/
public static <T> Collection<T> assertCollectionSize(String message, Collection<T> list, int size) {
assertEquals(message + " should be of size: "
+ size + " but is: " + list, size, list.size());
return list;
}
/**
* A helper method to create a list of Route objects for a given route builder
*/
public static List<Route> getRouteList(RouteBuilder builder) throws Exception {
CamelContext context = new DefaultCamelContext();
context.addRoutes(builder);
context.start();
List<Route> answer = context.getRoutes();
context.stop();
return answer;
}
/**
* Asserts that the text contains the given string
*
* @param text the text to compare
* @param containedText the text which must be contained inside the other text parameter
*/
public static void assertStringContains(String text, String containedText) {
assertNotNull("Text should not be null!", text);
assertTrue("Text: " + text + " does not contain: " + containedText, text.contains(containedText));
}
/**
* If a processor is wrapped with a bunch of DelegateProcessor or DelegateAsyncProcessor objects
* this call will drill through them and return the wrapped Processor.
*/
public static Processor unwrap(Processor processor) {
while (true) {
if (processor instanceof DelegateProcessor) {
processor = ((DelegateProcessor)processor).getProcessor();
} else {
return processor;
}
}
}
/**
* If a processor is wrapped with a bunch of DelegateProcessor or DelegateAsyncProcessor objects
* this call will drill through them and return the Channel.
* <p/>
* Returns null if no channel is found.
*/
public static Channel unwrapChannel(Processor processor) {
while (true) {
if (processor instanceof Channel) {
return (Channel) processor;
} else if (processor instanceof DelegateProcessor) {
processor = ((DelegateProcessor)processor).getProcessor();
} else {
return null;
}
}
}
/**
* Recursively delete a directory, useful to zapping test data
*
* @param file the directory to be deleted
*/
public static void deleteDirectory(String file) {
deleteDirectory(new File(file));
}
/**
* Recursively delete a directory, useful to zapping test data
*
* @param file the directory to be deleted
*/
public static void deleteDirectory(File file) {
int tries = 0;
int maxTries = 5;
boolean exists = true;
while (exists && (tries < maxTries)) {
recursivelyDeleteDirectory(file);
tries++;
exists = file.exists();
if (exists) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
}
}
if (exists) {
throw new RuntimeException("Deletion of file " + file + " failed");
}
}
private static void recursivelyDeleteDirectory(File file) {
if (!file.exists()) {
return;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
recursivelyDeleteDirectory(files[i]);
}
}
boolean success = file.delete();
if (!success) {
LOG.warn("Deletion of file: " + file.getAbsolutePath() + " failed");
}
}
/**
* create the directory
*
* @param file the directory to be created
*/
public static void createDirectory(String file) {
File dir = new File(file);
dir.mkdirs();
}
/**
* To be used for folder/directory comparison that works across different platforms such
* as Window, Mac and Linux.
*/
public static void assertDirectoryEquals(String expected, String actual) {
assertDirectoryEquals(null, expected, actual);
}
/**
* To be used for folder/directory comparison that works across different platforms such
* as Window, Mac and Linux.
*/
public static void assertDirectoryEquals(String message, String expected, String actual) {
// must use single / as path separators
String expectedPath = expected.replace('\\', '/');
String actualPath = actual.replace('\\', '/');
if (message != null) {
assertEquals(message, expectedPath, actualPath);
} else {
assertEquals(expectedPath, actualPath);
}
}
/**
* To be used to check is a file is found in the file system
*/
public static void assertFileExists(String filename) {
File file = new File(filename).getAbsoluteFile();
assertTrue("File " + filename + " should exist", file.exists());
}
/**
* Is this OS the given platform.
* <p/>
* Uses <tt>os.name</tt> from the system properties to determine the OS.
*
* @param platform such as Windows
* @return <tt>true</tt> if its that platform.
*/
public static boolean isPlatform(String platform) {
String osName = System.getProperty("os.name").toLowerCase(Locale.US);
return osName.indexOf(platform.toLowerCase(Locale.US)) > -1;
}
/**
* Is this Java by the given vendor.
* <p/>
* Uses <tt>java.vendor</tt> from the system properties to determine the vendor.
*
* @param vendor such as IBM
* @return <tt>true</tt> if its that vendor.
*/
public static boolean isJavaVendor(String vendor) {
String javaVendor = System.getProperty("java.vendor").toLowerCase(Locale.US);
return javaVendor.indexOf(vendor.toLowerCase(Locale.US)) > -1;
}
/**
* Is this Java 1.5
*
* @return <tt>true</tt> if its Java 1.5, <tt>false</tt> if its not (for example Java 1.6 or better)
* @deprecated will be removed in the near future as Camel now requires JDK1.6+
*/
@Deprecated
public static boolean isJava15() {
String javaVersion = System.getProperty("java.version").toLowerCase(Locale.US);
return javaVersion.startsWith("1.5");
}
/**
* Gets the current test method name
*
* @return the method name
*/
public String getTestMethodName() {
return testName.getMethodName();
}
}
| components/camel-test/src/main/java/org/apache/camel/test/junit4/TestSupport.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.camel.test.junit4;
import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import org.apache.camel.CamelContext;
import org.apache.camel.Channel;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.InvalidPayloadException;
import org.apache.camel.Message;
import org.apache.camel.Predicate;
import org.apache.camel.Processor;
import org.apache.camel.Route;
import org.apache.camel.builder.Builder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.builder.ValueBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.DefaultExchange;
import org.apache.camel.processor.DelegateProcessor;
import org.apache.camel.util.ExchangeHelper;
import org.apache.camel.util.PredicateAssertHelper;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A bunch of useful testing methods
*
* @version
*/
public abstract class TestSupport extends Assert {
protected static final String LS = System.getProperty("line.separator");
private static final Logger LOG = LoggerFactory.getLogger(TestSupport.class);
protected transient Logger log = LoggerFactory.getLogger(getClass());
// CHECKSTYLE:OFF
@Rule
public TestName testName = new TestName();
// CHECKSTYLE:ON
// Builder methods for expressions used when testing
// -------------------------------------------------------------------------
/**
* Returns a value builder for the given header
*/
public static ValueBuilder header(String name) {
return Builder.header(name);
}
/**
* Returns a value builder for the given property
*/
public static ValueBuilder property(String name) {
return Builder.property(name);
}
/**
* Returns a predicate and value builder for the inbound body on an exchange
*/
public static ValueBuilder body() {
return Builder.body();
}
/**
* Returns a predicate and value builder for the inbound message body as a
* specific type
*/
public static <T> ValueBuilder bodyAs(Class<T> type) {
return Builder.bodyAs(type);
}
/**
* Returns a predicate and value builder for the outbound body on an
* exchange
*/
public static ValueBuilder outBody() {
return Builder.outBody();
}
/**
* Returns a predicate and value builder for the outbound message body as a
* specific type
*/
public static <T> ValueBuilder outBodyAs(Class<T> type) {
return Builder.outBodyAs(type);
}
/**
* Returns a predicate and value builder for the fault body on an
* exchange
*/
public static ValueBuilder faultBody() {
return Builder.faultBody();
}
/**
* Returns a predicate and value builder for the fault message body as a
* specific type
*/
public static <T> ValueBuilder faultBodyAs(Class<T> type) {
return Builder.faultBodyAs(type);
}
/**
* Returns a value builder for the given system property
*/
public static ValueBuilder systemProperty(String name) {
return Builder.systemProperty(name);
}
/**
* Returns a value builder for the given system property
*/
public static ValueBuilder systemProperty(String name, String defaultValue) {
return Builder.systemProperty(name, defaultValue);
}
// Assertions
// -----------------------------------------------------------------------
public static <T> T assertIsInstanceOf(Class<T> expectedType, Object value) {
assertNotNull("Expected an instance of type: " + expectedType.getName() + " but was null", value);
assertTrue("object should be a " + expectedType.getName() + " but was: " + value + " with type: "
+ value.getClass().getName(), expectedType.isInstance(value));
return expectedType.cast(value);
}
public static void assertEndpointUri(Endpoint endpoint, String uri) {
assertNotNull("Endpoint is null when expecting endpoint for: " + uri, endpoint);
assertEquals("Endoint uri for: " + endpoint, uri, endpoint.getEndpointUri());
}
/**
* Asserts the In message on the exchange contains the expected value
*/
public static Object assertInMessageHeader(Exchange exchange, String name, Object expected) {
return assertMessageHeader(exchange.getIn(), name, expected);
}
/**
* Asserts the Out message on the exchange contains the expected value
*/
public static Object assertOutMessageHeader(Exchange exchange, String name, Object expected) {
return assertMessageHeader(exchange.getOut(), name, expected);
}
/**
* Asserts that the given exchange has an OUT message of the given body value
*
* @param exchange the exchange which should have an OUT message
* @param expected the expected value of the OUT message
* @throws InvalidPayloadException is thrown if the payload is not the expected class type
*/
public static void assertInMessageBodyEquals(Exchange exchange, Object expected) throws InvalidPayloadException {
assertNotNull("Should have a response exchange!", exchange);
Object actual;
if (expected == null) {
actual = ExchangeHelper.getMandatoryInBody(exchange);
assertEquals("in body of: " + exchange, expected, actual);
} else {
actual = ExchangeHelper.getMandatoryInBody(exchange, expected.getClass());
}
assertEquals("in body of: " + exchange, expected, actual);
LOG.debug("Received response: " + exchange + " with in: " + exchange.getIn());
}
/**
* Asserts that the given exchange has an OUT message of the given body value
*
* @param exchange the exchange which should have an OUT message
* @param expected the expected value of the OUT message
* @throws InvalidPayloadException is thrown if the payload is not the expected class type
*/
public static void assertOutMessageBodyEquals(Exchange exchange, Object expected) throws InvalidPayloadException {
assertNotNull("Should have a response exchange!", exchange);
Object actual;
if (expected == null) {
actual = ExchangeHelper.getMandatoryOutBody(exchange);
assertEquals("output body of: " + exchange, expected, actual);
} else {
actual = ExchangeHelper.getMandatoryOutBody(exchange, expected.getClass());
}
assertEquals("output body of: " + exchange, expected, actual);
LOG.debug("Received response: " + exchange + " with out: " + exchange.getOut());
}
public static Object assertMessageHeader(Message message, String name, Object expected) {
Object value = message.getHeader(name);
assertEquals("Header: " + name + " on Message: " + message, expected, value);
return value;
}
/**
* Asserts that the given expression when evaluated returns the given answer
*/
public static Object assertExpression(Expression expression, Exchange exchange, Object expected) {
Object value;
if (expected != null) {
value = expression.evaluate(exchange, expected.getClass());
} else {
value = expression.evaluate(exchange, Object.class);
}
LOG.debug("Evaluated expression: " + expression + " on exchange: " + exchange + " result: " + value);
assertEquals("Expression: " + expression + " on Exchange: " + exchange, expected, value);
return value;
}
/**
* Asserts that the predicate returns the expected value on the exchange
*/
public static void assertPredicateMatches(Predicate predicate, Exchange exchange) {
assertPredicate(predicate, exchange, true);
}
/**
* Asserts that the predicate returns the expected value on the exchange
*/
public static void assertPredicateDoesNotMatch(Predicate predicate, Exchange exchange) {
try {
PredicateAssertHelper.assertMatches(predicate, "Predicate should match: ", exchange);
} catch (AssertionError e) {
LOG.debug("Caught expected assertion error: " + e);
}
assertPredicate(predicate, exchange, false);
}
/**
* Asserts that the predicate returns the expected value on the exchange
*/
public static boolean assertPredicate(final Predicate predicate, Exchange exchange, boolean expected) {
if (expected) {
PredicateAssertHelper.assertMatches(predicate, "Predicate failed: ", exchange);
}
boolean value = predicate.matches(exchange);
LOG.debug("Evaluated predicate: " + predicate + " on exchange: " + exchange + " result: " + value);
assertEquals("Predicate: " + predicate + " on Exchange: " + exchange, expected, value);
return value;
}
/**
* Resolves an endpoint and asserts that it is found
*/
public static Endpoint resolveMandatoryEndpoint(CamelContext context, String uri) {
Endpoint endpoint = context.getEndpoint(uri);
assertNotNull("No endpoint found for URI: " + uri, endpoint);
return endpoint;
}
/**
* Resolves an endpoint and asserts that it is found
*/
public static <T extends Endpoint> T resolveMandatoryEndpoint(CamelContext context, String uri,
Class<T> endpointType) {
T endpoint = context.getEndpoint(uri, endpointType);
assertNotNull("No endpoint found for URI: " + uri, endpoint);
return endpoint;
}
/**
* Creates an exchange with the given body
*/
protected Exchange createExchangeWithBody(CamelContext camelContext, Object body) {
Exchange exchange = new DefaultExchange(camelContext);
Message message = exchange.getIn();
message.setHeader("testClass", getClass().getName());
message.setBody(body);
return exchange;
}
public static <T> T assertOneElement(List<T> list) {
assertEquals("Size of list should be 1: " + list, 1, list.size());
return list.get(0);
}
/**
* Asserts that a list is of the given size
*/
public static <T> List<T> assertListSize(List<T> list, int size) {
return assertListSize("List", list, size);
}
/**
* Asserts that a list is of the given size
*/
public static <T> List<T> assertListSize(String message, List<T> list, int size) {
assertEquals(message + " should be of size: "
+ size + " but is: " + list, size, list.size());
return list;
}
/**
* Asserts that a list is of the given size
*/
public static <T> Collection<T> assertCollectionSize(Collection<T> list, int size) {
return assertCollectionSize("List", list, size);
}
/**
* Asserts that a list is of the given size
*/
public static <T> Collection<T> assertCollectionSize(String message, Collection<T> list, int size) {
assertEquals(message + " should be of size: "
+ size + " but is: " + list, size, list.size());
return list;
}
/**
* A helper method to create a list of Route objects for a given route builder
*/
public static List<Route> getRouteList(RouteBuilder builder) throws Exception {
CamelContext context = new DefaultCamelContext();
context.addRoutes(builder);
context.start();
List<Route> answer = context.getRoutes();
context.stop();
return answer;
}
/**
* Asserts that the text contains the given string
*
* @param text the text to compare
* @param containedText the text which must be contained inside the other text parameter
*/
public static void assertStringContains(String text, String containedText) {
assertNotNull("Text should not be null!", text);
assertTrue("Text: " + text + " does not contain: " + containedText, text.contains(containedText));
}
/**
* If a processor is wrapped with a bunch of DelegateProcessor or DelegateAsyncProcessor objects
* this call will drill through them and return the wrapped Processor.
*/
public static Processor unwrap(Processor processor) {
while (true) {
if (processor instanceof DelegateProcessor) {
processor = ((DelegateProcessor)processor).getProcessor();
} else {
return processor;
}
}
}
/**
* If a processor is wrapped with a bunch of DelegateProcessor or DelegateAsyncProcessor objects
* this call will drill through them and return the Channel.
* <p/>
* Returns null if no channel is found.
*/
public static Channel unwrapChannel(Processor processor) {
while (true) {
if (processor instanceof Channel) {
return (Channel) processor;
} else if (processor instanceof DelegateProcessor) {
processor = ((DelegateProcessor)processor).getProcessor();
} else {
return null;
}
}
}
/**
* Recursively delete a directory, useful to zapping test data
*
* @param file the directory to be deleted
*/
public static void deleteDirectory(String file) {
deleteDirectory(new File(file));
}
/**
* Recursively delete a directory, useful to zapping test data
*
* @param file the directory to be deleted
*/
public static void deleteDirectory(File file) {
int tries = 0;
int maxTries = 5;
boolean exists = true;
while (exists && (tries < maxTries)) {
recursivelyDeleteDirectory(file);
tries ++;
exists = file.exists();
if (exists) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
}
}
if (exists) {
throw new RuntimeException("Deletion of file " + file + " failed");
}
}
private static void recursivelyDeleteDirectory(File file) {
if (!file.exists()) {
return;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
recursivelyDeleteDirectory(files[i]);
}
}
boolean success = file.delete();
if (!success) {
LOG.warn("Deletion of file: " + file.getAbsolutePath() + " failed");
}
}
/**
* create the directory
*
* @param file the directory to be created
*/
public static void createDirectory(String file) {
File dir = new File(file);
dir.mkdirs();
}
/**
* To be used for folder/directory comparison that works across different platforms such
* as Window, Mac and Linux.
*/
public static void assertDirectoryEquals(String expected, String actual) {
assertDirectoryEquals(null, expected, actual);
}
/**
* To be used for folder/directory comparison that works across different platforms such
* as Window, Mac and Linux.
*/
public static void assertDirectoryEquals(String message, String expected, String actual) {
// must use single / as path separators
String expectedPath = expected.replace('\\', '/');
String actualPath = actual.replace('\\', '/');
if (message != null) {
assertEquals(message, expectedPath, actualPath);
} else {
assertEquals(expectedPath, actualPath);
}
}
/**
* To be used to check is a file is found in the file system
*/
public static void assertFileExists(String filename) {
File file = new File(filename).getAbsoluteFile();
assertTrue("File " + filename + " should exist", file.exists());
}
/**
* Is this OS the given platform.
* <p/>
* Uses <tt>os.name</tt> from the system properties to determine the OS.
*
* @param platform such as Windows
* @return <tt>true</tt> if its that platform.
*/
public static boolean isPlatform(String platform) {
String osName = System.getProperty("os.name").toLowerCase(Locale.US);
return osName.indexOf(platform.toLowerCase(Locale.US)) > -1;
}
/**
* Is this Java by the given vendor.
* <p/>
* Uses <tt>java.vendor</tt> from the system properties to determine the vendor.
*
* @param vendor such as IBM
* @return <tt>true</tt> if its that vendor.
*/
public static boolean isJavaVendor(String vendor) {
String javaVendor = System.getProperty("java.vendor").toLowerCase(Locale.US);
return javaVendor.indexOf(vendor.toLowerCase(Locale.US)) > -1;
}
/**
* Is this Java 1.5
*
* @return <tt>true</tt> if its Java 1.5, <tt>false</tt> if its not (for example Java 1.6 or better)
* @deprecated will be removed in the near future as Camel now requires JDK1.6+
*/
@Deprecated
public static boolean isJava15() {
String javaVersion = System.getProperty("java.version").toLowerCase(Locale.US);
return javaVersion.startsWith("1.5");
}
/**
* Gets the current test method name
*
* @return the method name
*/
public String getTestMethodName() {
return testName.getMethodName();
}
}
| Checkstyle fix
git-svn-id: 11f3c9e1d08a13a4be44fe98a6d63a9c00f6ab23@1169738 13f79535-47bb-0310-9956-ffa450edef68
| components/camel-test/src/main/java/org/apache/camel/test/junit4/TestSupport.java | Checkstyle fix | <ide><path>omponents/camel-test/src/main/java/org/apache/camel/test/junit4/TestSupport.java
<ide> boolean exists = true;
<ide> while (exists && (tries < maxTries)) {
<ide> recursivelyDeleteDirectory(file);
<del> tries ++;
<add> tries++;
<ide> exists = file.exists();
<ide> if (exists) {
<ide> try { |
|
Java | mit | 975fa475eb03096c84ce4181c69819f6620cb0e4 | 0 | PatricioAlejandro/IngSw-II | //1
//2
//3
//4
//5 | pruebaSW.java | //1
//2
//3
//4 | anadir linea 5
| pruebaSW.java | anadir linea 5 | <ide><path>ruebaSW.java
<ide> //2
<ide> //3
<ide> //4
<add>//5 |
|
JavaScript | mit | 9b37be91c9f37740def5d130f355c5b016bcb85a | 0 | mshmsh5000/dosomething-1,chloealee/dosomething,mshmsh5000/dosomething-1,angaither/dosomething,sbsmith86/dosomething,DoSomething/dosomething,angaither/dosomething,chloealee/dosomething,DoSomething/phoenix,DoSomething/dosomething,chloealee/dosomething,deadlybutter/phoenix,deadlybutter/phoenix,DoSomething/phoenix,DoSomething/phoenix,jonuy/dosomething,deadlybutter/phoenix,angaither/dosomething,sergii-tkachenko/phoenix,DoSomething/phoenix,sbsmith86/dosomething,DoSomething/dosomething,DoSomething/dosomething,sbsmith86/dosomething,sergii-tkachenko/phoenix,deadlybutter/phoenix,DoSomething/dosomething,jonuy/dosomething,jonuy/dosomething,deadlybutter/phoenix,mshmsh5000/dosomething,jonuy/dosomething,sergii-tkachenko/phoenix,angaither/dosomething,chloealee/dosomething,sergii-tkachenko/phoenix,jonuy/dosomething,mshmsh5000/dosomething,mshmsh5000/dosomething-1,sbsmith86/dosomething,sergii-tkachenko/phoenix,sbsmith86/dosomething,chloealee/dosomething,mshmsh5000/dosomething,mshmsh5000/dosomething-1,sbsmith86/dosomething,jonuy/dosomething,chloealee/dosomething,mshmsh5000/dosomething,DoSomething/phoenix,angaither/dosomething,DoSomething/dosomething,angaither/dosomething,mshmsh5000/dosomething-1 | define(function(require) {
"use strict";
var $ = require("jquery");
var _ = require("lodash");
var Campaign = require("finder/Campaign");
var noResultsTplSrc = require("text!finder/templates/no-results.tpl.html");
/**
* ResultsView manages search results from Finder
* @type {Object}
*/
var ResultsView = {
// The container element where the results go
$container: null,
// The gallery located in the container
$gallery: $("<ul class='gallery -mosaic'></ul>"),
// The div that is shown if no filters are selected
$blankSlateDiv: null,
// How many slots are currently used. Full-height = 2, half-height = 1
slots: 0,
// How many slots are we allowing
maxSlots: 8,
// For tracking what page we're on
start: 0,
/**
* Construct the cloneables and set the parent div where the results go
* @param {jQuery} $container The container element where the results will live
* @param {jQuery} $blankSlateDiv The div containing initial pre-filtered state
* @param {function} paginateAction Function to query next page of results.
*/
init: function ($container, $blankSlateDiv, paginateAction, clearFormAction) {
ResultsView.$container = $container;
ResultsView.$container.hide();
ResultsView.$paginationLink = $("<div class='pagination-link'><a href='#' class='secondary js-finder-show-more'>Show More</a></div>");
$("body").on("click", ".js-finder-show-more", function(event) {
event.preventDefault();
paginateAction(ResultsView.start);
});
ResultsView.$blankSlateDiv = $blankSlateDiv;
ResultsView.$container.on("click", "#reset-filters", function(event) {
event.preventDefault();
ResultsView.showBlankSlate();
// TODO: Maybe allow for FormView.clear() to be called from ResultsView so
// it doesn't have to be passed in as an argument to the init().
clearFormAction();
});
},
/**
* Shows the blank slate div (initial state).
*/
showBlankSlate: function() {
ResultsView.$container.hide();
ResultsView.$blankSlateDiv.show();
},
/**
* Shows the empty slate div (no results state).
*/
showEmptyState: function() {
var message = _.template(noResultsTplSrc);
ResultsView.$container.append(message);
},
/**
* Replace current results with new data
* @param {Object} data The raw data from the query
*/
parseResults: function (data) {
// Remove the old results
ResultsView.clear();
if (data.retrieved > 0) {
// Results view cleared, and since we have results add the gallery into the container.
ResultsView.$container.append(ResultsView.$gallery);
// Loopy loop! (Like me after drinking coffeeeee)
for (var i in data.result.response.docs) {
ResultsView.add(new Campaign(data.result.response.docs[i]));
}
// There are more results than we've shown so far, add "Show More" button
ResultsView.showPaginationLink(data.result.response.numFound > ResultsView.start);
} else {
ResultsView.showEmptyState();
}
// Hey! We're done loading! I guess we can let the users know we're done.
ResultsView.loading(false);
},
/**
* Show or hide pagination link.
* @param {boolean} showLink Should link be shown?
*/
showPaginationLink: function(showLink) {
ResultsView.$paginationLink.remove();
if(showLink) {
ResultsView.$container.append(ResultsView.$paginationLink);
ResultsView.$paginationLink.show();
}
},
/**
* Append to current results with new data.
* @param {Object} data The raw data from the query
*/
appendResults: function (data) {
// Add those results to the page!
for (var i in data.result.response.docs) {
ResultsView.add(new Campaign(data.result.response.docs[i]));
}
// There are more results than we've shown so far, add "Show More" button
ResultsView.showPaginationLink(data.result.response.numFound > ResultsView.start);
// Hey! We're done loading! I guess we can let the users know we're done.
ResultsView.loading(false);
},
/**
* Toggle the loading indicator for the results div
* @param {boolean} setTo Should I stay or should I go? If I go there will be trouble...or clicking.
*/
loading: function (setTo) {
// Allow the function to be called without a parameter, since X.loading() would seem
// to be a logical call.
if (setTo === undefined) {
setTo = true;
}
// If we're loading, add a class to the results div. Otherwise, remove it.
ResultsView.$container.append("<div class='spinner'></div>");
ResultsView.$container.toggleClass("loading", setTo);
},
/**
* Have we run the init method?
*/
checkInit: function () {
if (ResultsView.$container === null) {
// Nope. I'm gonna vomit...
throw "Error: ResultsView is not initialized.";
}
// Yup.
},
/**
* Remove the current results and reboot this object.
*/
clear: function () {
ResultsView.checkInit();
ResultsView.$container.empty();
ResultsView.$gallery.empty();
ResultsView.$container.show();
ResultsView.$blankSlateDiv.hide();
ResultsView.slots = 0;
ResultsView.start = 0;
},
/**
* Add a campaign to the results
* @param {Campaign} campaign The campaign to add
*/
add: function (campaign) {
// Make sure we've initialized ourself
ResultsView.checkInit();
// If we're full, screw it.
// if (ResultsView.slots === ResultsView.maxSlots) {
// return;
// }
// Render campaign object and append to the gallery
ResultsView.$gallery.append(campaign.render());
ResultsView.slots++;
// Track where we are for paging
ResultsView.start++;
// Lazy-load in images
ResultsView.$container.find("img").unveil(200, function() {
$(this).load(function() {
this.style.opacity = 1;
});
});
}
};
return ResultsView;
});
| lib/themes/dosomething/paraneue_dosomething/js/finder/ResultsView.js | define(function(require) {
"use strict";
var $ = require("jquery");
var _ = require("lodash");
var Campaign = require("finder/Campaign");
var noResultsTplSrc = require("text!finder/templates/no-results.tpl.html");
/**
* ResultsView manages search results from Finder
* @type {Object}
*/
var ResultsView = {
// The container element where the results go
$container: null,
// The gallery located in the container
$gallery: $("<ul class='gallery -mosaic'></ul>"),
// The div that is shown if no filters are selected
$blankSlateDiv: null,
// How many slots are currently used. Full-height = 2, half-height = 1
slots: 0,
// How many slots are we allowing
maxSlots: 8,
// For tracking what page we're on
start: 0,
/**
* Construct the cloneables and set the parent div where the results go
* @param {jQuery} $container The container element where the results will live
* @param {jQuery} $blankSlateDiv The div containing initial pre-filtered state
* @param {function} paginateAction Function to query next page of results.
*/
init: function ($container, $blankSlateDiv, paginateAction, clearFormAction) {
ResultsView.$container = $container;
ResultsView.$container.hide();
ResultsView.$paginationLink = $("<div class='pagination-link'><a href='#' class='secondary js-finder-show-more'>Show More</a></div>");
$("body").on("click", ".js-finder-show-more", function(event) {
event.preventDefault();
paginateAction(ResultsView.start);
});
ResultsView.$blankSlateDiv = $blankSlateDiv;
ResultsView.$container.on("click", "#reset-filters", function(event) {
event.preventDefault();
ResultsView.showBlankSlate();
// TODO: Maybe allow for FormView.clear() to be called from ResultsView so
// it doesn't have to be passed in as an argument to the init().
clearFormAction();
});
},
/**
* Shows the blank slate div (initial state).
*/
showBlankSlate: function() {
ResultsView.$container.hide();
ResultsView.$blankSlateDiv.show();
},
/**
* Shows the empty slate div (no results state).
*/
showEmptyState: function() {
var message = _.template(noResultsTplSrc);
ResultsView.$container.append(message);
},
/**
* Replace current results with new data
* @param {Object} data The raw data from the query
*/
parseResults: function (data) {
console.log(data);
// Remove the old results
ResultsView.clear();
if (data.retrieved > 0) {
// Results view cleared, and since we have results add the gallery into the container.
ResultsView.$container.append(ResultsView.$gallery);
// Loopy loop! (Like me after drinking coffeeeee)
for (var i in data.result.response.docs) {
ResultsView.add(new Campaign(data.result.response.docs[i]));
}
// There are more results than we've shown so far, add "Show More" button
ResultsView.showPaginationLink(data.result.response.numFound > ResultsView.start);
} else {
ResultsView.showEmptyState();
}
// Hey! We're done loading! I guess we can let the users know we're done.
ResultsView.loading(false);
},
/**
* Show or hide pagination link.
* @param {boolean} showLink Should link be shown?
*/
showPaginationLink: function(showLink) {
ResultsView.$paginationLink.remove();
if(showLink) {
ResultsView.$container.append(ResultsView.$paginationLink);
ResultsView.$paginationLink.show();
}
},
/**
* Append to current results with new data.
* @param {Object} data The raw data from the query
*/
appendResults: function (data) {
// Add those results to the page!
for (var i in data.result.response.docs) {
ResultsView.add(new Campaign(data.result.response.docs[i]));
}
// There are more results than we've shown so far, add "Show More" button
ResultsView.showPaginationLink(data.result.response.numFound > ResultsView.start);
// Hey! We're done loading! I guess we can let the users know we're done.
ResultsView.loading(false);
},
/**
* Toggle the loading indicator for the results div
* @param {boolean} setTo Should I stay or should I go? If I go there will be trouble...or clicking.
*/
loading: function (setTo) {
// Allow the function to be called without a parameter, since X.loading() would seem
// to be a logical call.
if (setTo === undefined) {
setTo = true;
}
// If we're loading, add a class to the results div. Otherwise, remove it.
ResultsView.$container.append("<div class='spinner'></div>");
ResultsView.$container.toggleClass("loading", setTo);
},
/**
* Have we run the init method?
*/
checkInit: function () {
if (ResultsView.$container === null) {
// Nope. I'm gonna vomit...
throw "Error: ResultsView is not initialized.";
}
// Yup.
},
/**
* Remove the current results and reboot this object.
*/
clear: function () {
ResultsView.checkInit();
ResultsView.$container.empty();
ResultsView.$gallery.empty();
ResultsView.$container.show();
ResultsView.$blankSlateDiv.hide();
ResultsView.slots = 0;
ResultsView.start = 0;
},
/**
* Add a campaign to the results
* @param {Campaign} campaign The campaign to add
*/
add: function (campaign) {
// Make sure we've initialized ourself
ResultsView.checkInit();
// If we're full, screw it.
// if (ResultsView.slots === ResultsView.maxSlots) {
// return;
// }
// Render campaign object and append to the gallery
ResultsView.$gallery.append(campaign.render());
ResultsView.slots++;
// Track where we are for paging
ResultsView.start++;
// Lazy-load in images
ResultsView.$container.find("img").unveil(200, function() {
$(this).load(function() {
this.style.opacity = 1;
});
});
}
};
return ResultsView;
});
| Removing debug info.
| lib/themes/dosomething/paraneue_dosomething/js/finder/ResultsView.js | Removing debug info. | <ide><path>ib/themes/dosomething/paraneue_dosomething/js/finder/ResultsView.js
<ide> * @param {Object} data The raw data from the query
<ide> */
<ide> parseResults: function (data) {
<del> console.log(data);
<ide> // Remove the old results
<ide> ResultsView.clear();
<ide> |
|
Java | apache-2.0 | 0d5834ddd7cdd62f2442134a2a11d93c4ca06dde | 0 | holon-platform/holon-jaxrs | /*
* Copyright 2000-2017 Holon TDCN.
*
* 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.holonplatform.jaxrs.spring.boot.jersey;
import javax.ws.rs.Path;
import javax.ws.rs.ext.Provider;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletProperties;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.holonplatform.jaxrs.spring.boot.jersey.internal.JerseyResourcesPostProcessor;
/**
* Jersey JAX-RS server auto configuration.
* <p>
* If a {@link ResourceConfig} type bean is not already defined, a standard {@link ResourceConfig} bean is automatically
* registered.
* </p>
* <p>
* Any bean annotated with {@link Path} or {@link Provider} is detected and automatically registered as a JAX-RS
* resource. To disable automatic resource scan and registration, the <code>holon.jersey.bean-scan</code> configuration
* property with a <code>false</code> value can be used.
* </p>
* <p>
* Note that {@link Provider} annotated bean must be <em>singleton</em> scoped.
* </p>
*
* @since 5.0.0
*/
@Configuration
@ConditionalOnClass(ResourceConfig.class)
@AutoConfigureBefore(JerseyAutoConfiguration.class)
@EnableConfigurationProperties(JerseyConfigurationProperties.class)
public class JerseyServerAutoConfiguration {
@Configuration
@ConditionalOnMissingBean(ResourceConfig.class)
static class JerseyApplicationConfiguration {
private final JerseyConfigurationProperties configurationProperties;
public JerseyApplicationConfiguration(JerseyConfigurationProperties configurationProperties) {
super();
this.configurationProperties = configurationProperties;
}
@Bean
public ResourceConfig jerseyApplicationConfig() {
ResourceConfig resourceConfig = new ResourceConfig();
if (configurationProperties.isForwardOn404()) {
resourceConfig.property(ServletProperties.FILTER_FORWARD_ON_404, true);
}
return resourceConfig;
}
}
@Configuration
@ConditionalOnProperty(name = "holon.jersey.bean-scan", matchIfMissing = true)
static class ResourcesAutoConfiguration {
@Bean
public static JerseyResourcesPostProcessor jerseyResourcesPostProcessor() {
return new JerseyResourcesPostProcessor();
}
}
}
| spring-boot-jersey/src/main/java/com/holonplatform/jaxrs/spring/boot/jersey/JerseyServerAutoConfiguration.java | /*
* Copyright 2000-2017 Holon TDCN.
*
* 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.holonplatform.jaxrs.spring.boot.jersey;
import javax.ws.rs.Path;
import javax.ws.rs.ext.Provider;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletProperties;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.filter.RequestContextFilter;
import com.holonplatform.jaxrs.spring.boot.jersey.internal.JerseyResourcesPostProcessor;
/**
* Jersey JAX-RS server auto configuration.
* <p>
* If a {@link ResourceConfig} type bean is not already defined, a standard {@link ResourceConfig} bean is automatically
* registered.
* </p>
* <p>
* Any bean annotated with {@link Path} or {@link Provider} is detected and automatically registered as a JAX-RS
* resource. To disable automatic resource scan and registration, the <code>holon.jersey.bean-scan</code> configuration
* property with a <code>false</code> value can be used.
* </p>
* <p>
* Note that {@link Provider} annotated bean must be <em>singleton</em> scoped.
* </p>
*
* @since 5.0.0
*/
@Configuration
@ConditionalOnClass(ResourceConfig.class)
@AutoConfigureBefore(JerseyAutoConfiguration.class)
@EnableConfigurationProperties(JerseyConfigurationProperties.class)
public class JerseyServerAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = { "requestContextFilter" })
public static FilterRegistrationBean<RequestContextFilter> requestContextFilter() {
FilterRegistrationBean<RequestContextFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(new RequestContextFilter());
registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
registration.setName("requestContextFilter");
return registration;
}
@Configuration
@ConditionalOnMissingBean(ResourceConfig.class)
static class JerseyApplicationConfiguration {
private final JerseyConfigurationProperties configurationProperties;
public JerseyApplicationConfiguration(JerseyConfigurationProperties configurationProperties) {
super();
this.configurationProperties = configurationProperties;
}
@Bean
public ResourceConfig jerseyApplicationConfig() {
ResourceConfig resourceConfig = new ResourceConfig();
if (configurationProperties.isForwardOn404()) {
resourceConfig.property(ServletProperties.FILTER_FORWARD_ON_404, true);
}
return resourceConfig;
}
}
@Configuration
@ConditionalOnProperty(name = "holon.jersey.bean-scan", matchIfMissing = true)
static class ResourcesAutoConfiguration {
@Bean
public static JerseyResourcesPostProcessor jerseyResourcesPostProcessor() {
return new JerseyResourcesPostProcessor();
}
}
}
| Closes #47 | spring-boot-jersey/src/main/java/com/holonplatform/jaxrs/spring/boot/jersey/JerseyServerAutoConfiguration.java | Closes #47 | <ide><path>pring-boot-jersey/src/main/java/com/holonplatform/jaxrs/spring/boot/jersey/JerseyServerAutoConfiguration.java
<ide> import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
<ide> import org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration;
<ide> import org.springframework.boot.context.properties.EnableConfigurationProperties;
<del>import org.springframework.boot.web.servlet.FilterRegistrationBean;
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<del>import org.springframework.core.Ordered;
<del>import org.springframework.web.filter.RequestContextFilter;
<ide>
<ide> import com.holonplatform.jaxrs.spring.boot.jersey.internal.JerseyResourcesPostProcessor;
<ide>
<ide> @AutoConfigureBefore(JerseyAutoConfiguration.class)
<ide> @EnableConfigurationProperties(JerseyConfigurationProperties.class)
<ide> public class JerseyServerAutoConfiguration {
<del>
<del> @Bean
<del> @ConditionalOnMissingBean(name = { "requestContextFilter" })
<del> public static FilterRegistrationBean<RequestContextFilter> requestContextFilter() {
<del> FilterRegistrationBean<RequestContextFilter> registration = new FilterRegistrationBean<>();
<del> registration.setFilter(new RequestContextFilter());
<del> registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
<del> registration.setName("requestContextFilter");
<del> return registration;
<del> }
<ide>
<ide> @Configuration
<ide> @ConditionalOnMissingBean(ResourceConfig.class) |
|
Java | mit | 73f6f426f9e3c651693d22a0c03aa012c4d25c1f | 0 | DSG-UniFE/ramp,DSG-UniFE/ramp | package it.unibo.deis.lia.ramp.util;
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import org.apache.commons.io.comparator.NameFileComparator;
import com.opencsv.CSVWriter;
import it.unibo.deis.lia.ramp.RampEntryPoint;
public class Benchmark {
private static String DATE_TIME_FORMAT = new String("yyyy-MM-dd HH:mm:ss");
private static String DATE_FORMAT = new String("yyyy_MM_dd");
private static String TIME_FORMAT = new String("HH:mm:ss");
private static String HEAD = new String("Date#Time#Milliseconds#Type#Packet ID#Sender#Recipient");
private static String BENCH_DIR = "./logs/";
private static String FILENAME = null;
private static String FILE_EXTENSION = ".csv";
private static String BENCH_PATH = null;
private static String ENDS_WITH = "benchmark";
public static void createDirectory() {
try {
if (RampEntryPoint.getAndroidContext() != null) {
System.out.println("--->SONO DENTRO");
if (android.os.Environment.getExternalStorageDirectory() != null) {
BENCH_DIR = android.os.Environment.getExternalStorageDirectory() + "/ramp/logs/";
File dir = new File(BENCH_DIR);
if (!dir.exists())
dir.mkdirs();
}
} else {
if (Files.notExists(Paths.get(BENCH_DIR), LinkOption.NOFOLLOW_LINKS)) {
Files.createDirectories(new File(BENCH_DIR).toPath());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void createFile() {
createDirectory();
int nfiles = getNumberFiles(BENCH_DIR, ENDS_WITH, FILE_EXTENSION);
FILENAME = getDate(DATE_FORMAT.toString()) + "-" + String.format("%02d", nfiles) + "-" + ENDS_WITH
+ FILE_EXTENSION;
BENCH_PATH = BENCH_DIR + FILENAME;
System.out.println("FILENAME: " + FILENAME);
System.out.println("BENCH_DIR: " + BENCH_DIR);
System.out.println("BENCH_PATH: " + BENCH_PATH);
CSVWriter writer;
try {
// writer = new CSVWriter(new
// FileWriter(DATE_TIME_FORMAT.format(date.getTime()) + "-" +
// filename + ".csv"), ';');
writer = new CSVWriter(new FileWriter(BENCH_PATH, true), ';');
String[] entries = HEAD.split("#");
writer.writeNext(entries);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void appendBenchmark(int millis, String type, String packetId, String sender, String recipient) {
File lastFile = getLastFilename(BENCH_DIR, ENDS_WITH, FILE_EXTENSION);
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
String row = dateFormat.format(date.getTime()) + "#" + timeFormat.format(date.getTime()) + "#" + millis + "#"
+ type + "#" + packetId + "#" + sender + "#" + recipient;
CSVWriter writer;
try {
writer = new CSVWriter(new FileWriter(lastFile, true), ';');
writer.writeNext(row.split("#"));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static File getLastFilename(String dirname, String endsWith, String fileExtension) {
File dir = new File(dirname);
File[] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(endsWith + fileExtension);
}
});
Arrays.sort(files, NameFileComparator.NAME_INSENSITIVE_COMPARATOR);
if (files.length != 0)
return files[files.length - 1];
return null;
}
public static int getNumberFiles(String dirname, String endsWith, String fileExtension) {
File dir = new File(dirname);
File[] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(endsWith + fileExtension);
}
});
Arrays.sort(files, NameFileComparator.NAME_INSENSITIVE_COMPARATOR);
return files.length;
}
public static String getDate(String format) {
// example "HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss" ecc...
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.format(new Date());
}
private static String getFileExtension(String filename) {
if (filename.lastIndexOf(".") != -1 && filename.lastIndexOf(".") != 0)
return filename.substring(filename.lastIndexOf(".") + 1);
else
return "";
}
}
| src/it/unibo/deis/lia/ramp/util/Benchmark.java | package it.unibo.deis.lia.ramp.util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import com.opencsv.CSVWriter;
import it.unibo.deis.lia.ramp.RampEntryPoint;
public class Benchmark {
private String filename = "benchmark";
private ArrayList<String> benchmarksList;
private String bench_dir = "temp/benchmark";
private static SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
private static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");
public Benchmark(String filename) {
this.benchmarksList = new ArrayList<String>();
this.setFilename(filename);
this.createDirectory();
this.createFile();
}
private void createDirectory() {
if (RampEntryPoint.getAndroidContext() != null) {
bench_dir = android.os.Environment.getExternalStorageDirectory() + "/benchmark";
File dir = new File(bench_dir);
if(!dir.exists())
dir.mkdirs();
}
}
private void createFile() {
Calendar date = Calendar.getInstance();
CSVWriter writer;
try {
// writer = new CSVWriter(new FileWriter(DATE_TIME_FORMAT.format(date.getTime()) + "-" + filename + ".csv"), ';');
String filenameSaved = bench_dir + filename + ".csv";
writer = new CSVWriter(new FileWriter(filenameSaved, true), ';');
// feed in your array (or convert your data to an array)
String[] entries = "Date#Time#Milliseconds#Type#Packet ID#Sender#Recipient".split("#");
writer.writeNext(entries);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeFile() {
if (RampEntryPoint.getAndroidContext() != null) {
Calendar date = Calendar.getInstance();
CSVWriter writer;
try {
writer = new CSVWriter(new FileWriter(DATE_TIME_FORMAT.format(date.getTime()) + filename + ".csv"), ';');
// feed in your array (or convert your data to an array)
String[] entries = "Date#Time#Packet ID#Sender#Recipient".split("#");
writer.writeNext(entries);
for (String temp : getBenchmarks()) {
writer.writeNext(temp.split("#"));
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void appendBench(Calendar date, String packetId, String sender, String recipient) {
// long millis = System.currentTimeMillis();
String row = DATE_FORMAT.format(date.getTime()) + "#" +
TIME_FORMAT.format(date.getTime()) + "#" +
packetId + "#" +
sender + "#" +
recipient;
CSVWriter writer;
try {
String filenameSaved = bench_dir + filename + ".csv";
writer = new CSVWriter(new FileWriter(filenameSaved, true), ';');
writer.writeNext(row.split("#"));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public void addBenchmark(Calendar date, long millis, String type,
String packetId, String sender, String recipient) {
// long millis = System.currentTimeMillis();
String row = DATE_FORMAT.format(date.getTime()) + "#" +
TIME_FORMAT.format(date.getTime()) + "#" +
millis + "#" +
type + "#" +
packetId + "#" +
sender + "#" +
recipient;
this.benchmarksList.add(row);
}
public void removeLastBenchmark() {
this.benchmarksList.remove(benchmarksList.size() - 1);
}
public ArrayList<String> getBenchmarks() {
return benchmarksList;
}
}
| Fixed class for benchmarks
| src/it/unibo/deis/lia/ramp/util/Benchmark.java | Fixed class for benchmarks | <ide><path>rc/it/unibo/deis/lia/ramp/util/Benchmark.java
<ide>
<ide> import java.io.File;
<ide> import java.io.FileWriter;
<add>import java.io.FilenameFilter;
<ide> import java.io.IOException;
<add>import java.nio.file.Files;
<add>import java.nio.file.LinkOption;
<add>import java.nio.file.Paths;
<ide> import java.text.SimpleDateFormat;
<del>import java.util.ArrayList;
<del>import java.util.Calendar;
<add>import java.util.Arrays;
<add>import java.util.Date;
<add>
<add>import org.apache.commons.io.comparator.NameFileComparator;
<ide>
<ide> import com.opencsv.CSVWriter;
<ide>
<ide> import it.unibo.deis.lia.ramp.RampEntryPoint;
<ide>
<ide> public class Benchmark {
<del>
<del> private String filename = "benchmark";
<del> private ArrayList<String> benchmarksList;
<del> private String bench_dir = "temp/benchmark";
<del> private static SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
<del> private static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
<del> private static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");
<del>
<del> public Benchmark(String filename) {
<del> this.benchmarksList = new ArrayList<String>();
<del> this.setFilename(filename);
<del> this.createDirectory();
<del> this.createFile();
<del>
<add>
<add> private static String DATE_TIME_FORMAT = new String("yyyy-MM-dd HH:mm:ss");
<add> private static String DATE_FORMAT = new String("yyyy_MM_dd");
<add> private static String TIME_FORMAT = new String("HH:mm:ss");
<add>
<add> private static String HEAD = new String("Date#Time#Milliseconds#Type#Packet ID#Sender#Recipient");
<add> private static String BENCH_DIR = "./logs/";
<add> private static String FILENAME = null;
<add> private static String FILE_EXTENSION = ".csv";
<add> private static String BENCH_PATH = null;
<add> private static String ENDS_WITH = "benchmark";
<add>
<add> public static void createDirectory() {
<add> try {
<add> if (RampEntryPoint.getAndroidContext() != null) {
<add> System.out.println("--->SONO DENTRO");
<add> if (android.os.Environment.getExternalStorageDirectory() != null) {
<add> BENCH_DIR = android.os.Environment.getExternalStorageDirectory() + "/ramp/logs/";
<add>
<add> File dir = new File(BENCH_DIR);
<add> if (!dir.exists())
<add> dir.mkdirs();
<add> }
<add> } else {
<add> if (Files.notExists(Paths.get(BENCH_DIR), LinkOption.NOFOLLOW_LINKS)) {
<add> Files.createDirectories(new File(BENCH_DIR).toPath());
<add> }
<add> }
<add> } catch (IOException e) {
<add> e.printStackTrace();
<add> }
<ide> }
<del>
<del> private void createDirectory() {
<del> if (RampEntryPoint.getAndroidContext() != null) {
<del> bench_dir = android.os.Environment.getExternalStorageDirectory() + "/benchmark";
<del> File dir = new File(bench_dir);
<del> if(!dir.exists())
<del> dir.mkdirs();
<del> }
<del> }
<ide>
<del> private void createFile() {
<del> Calendar date = Calendar.getInstance();
<add> public static void createFile() {
<add> createDirectory();
<add>
<add> int nfiles = getNumberFiles(BENCH_DIR, ENDS_WITH, FILE_EXTENSION);
<add> FILENAME = getDate(DATE_FORMAT.toString()) + "-" + String.format("%02d", nfiles) + "-" + ENDS_WITH
<add> + FILE_EXTENSION;
<add> BENCH_PATH = BENCH_DIR + FILENAME;
<add>
<add> System.out.println("FILENAME: " + FILENAME);
<add> System.out.println("BENCH_DIR: " + BENCH_DIR);
<add> System.out.println("BENCH_PATH: " + BENCH_PATH);
<add>
<ide> CSVWriter writer;
<ide> try {
<del>// writer = new CSVWriter(new FileWriter(DATE_TIME_FORMAT.format(date.getTime()) + "-" + filename + ".csv"), ';');
<del> String filenameSaved = bench_dir + filename + ".csv";
<del> writer = new CSVWriter(new FileWriter(filenameSaved, true), ';');
<del> // feed in your array (or convert your data to an array)
<del> String[] entries = "Date#Time#Milliseconds#Type#Packet ID#Sender#Recipient".split("#");
<del> writer.writeNext(entries);
<add> // writer = new CSVWriter(new
<add> // FileWriter(DATE_TIME_FORMAT.format(date.getTime()) + "-" +
<add> // filename + ".csv"), ';');
<add> writer = new CSVWriter(new FileWriter(BENCH_PATH, true), ';');
<add> String[] entries = HEAD.split("#");
<add> writer.writeNext(entries);
<ide> writer.close();
<ide> } catch (IOException e) {
<ide> e.printStackTrace();
<ide> }
<ide> }
<del>
<del> public void writeFile() {
<del> if (RampEntryPoint.getAndroidContext() != null) {
<del> Calendar date = Calendar.getInstance();
<del>
<del> CSVWriter writer;
<del> try {
<del>
<del> writer = new CSVWriter(new FileWriter(DATE_TIME_FORMAT.format(date.getTime()) + filename + ".csv"), ';');
<del> // feed in your array (or convert your data to an array)
<del> String[] entries = "Date#Time#Packet ID#Sender#Recipient".split("#");
<del> writer.writeNext(entries);
<del>
<del> for (String temp : getBenchmarks()) {
<del> writer.writeNext(temp.split("#"));
<del> }
<del>
<del> writer.close();
<del> } catch (IOException e) {
<del> e.printStackTrace();
<del> }
<del> }
<del> }
<del>
<del> public void appendBench(Calendar date, String packetId, String sender, String recipient) {
<del> // long millis = System.currentTimeMillis();
<del> String row = DATE_FORMAT.format(date.getTime()) + "#" +
<del> TIME_FORMAT.format(date.getTime()) + "#" +
<del> packetId + "#" +
<del> sender + "#" +
<del> recipient;
<del>
<add>
<add> public static void appendBenchmark(int millis, String type, String packetId, String sender, String recipient) {
<add> File lastFile = getLastFilename(BENCH_DIR, ENDS_WITH, FILE_EXTENSION);
<add>
<add> Date date = new Date();
<add> SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
<add> SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
<add> String row = dateFormat.format(date.getTime()) + "#" + timeFormat.format(date.getTime()) + "#" + millis + "#"
<add> + type + "#" + packetId + "#" + sender + "#" + recipient;
<add>
<ide> CSVWriter writer;
<ide> try {
<del> String filenameSaved = bench_dir + filename + ".csv";
<del> writer = new CSVWriter(new FileWriter(filenameSaved, true), ';');
<del> writer.writeNext(row.split("#"));
<add> writer = new CSVWriter(new FileWriter(lastFile, true), ';');
<add> writer.writeNext(row.split("#"));
<ide> writer.close();
<ide> } catch (IOException e) {
<ide> e.printStackTrace();
<ide> }
<ide> }
<del>
<del> public String getFilename() {
<del> return filename;
<add>
<add> public static File getLastFilename(String dirname, String endsWith, String fileExtension) {
<add> File dir = new File(dirname);
<add> File[] files = dir.listFiles(new FilenameFilter() {
<add> @Override
<add> public boolean accept(File dir, String name) {
<add> return name.toLowerCase().endsWith(endsWith + fileExtension);
<add> }
<add> });
<add>
<add> Arrays.sort(files, NameFileComparator.NAME_INSENSITIVE_COMPARATOR);
<add>
<add> if (files.length != 0)
<add> return files[files.length - 1];
<add>
<add> return null;
<ide> }
<ide>
<del> public void setFilename(String filename) {
<del> this.filename = filename;
<add> public static int getNumberFiles(String dirname, String endsWith, String fileExtension) {
<add> File dir = new File(dirname);
<add> File[] files = dir.listFiles(new FilenameFilter() {
<add> @Override
<add> public boolean accept(File dir, String name) {
<add> return name.toLowerCase().endsWith(endsWith + fileExtension);
<add> }
<add> });
<add>
<add> Arrays.sort(files, NameFileComparator.NAME_INSENSITIVE_COMPARATOR);
<add>
<add> return files.length;
<ide> }
<ide>
<del> public void addBenchmark(Calendar date, long millis, String type,
<del> String packetId, String sender, String recipient) {
<del> // long millis = System.currentTimeMillis();
<del> String row = DATE_FORMAT.format(date.getTime()) + "#" +
<del> TIME_FORMAT.format(date.getTime()) + "#" +
<del> millis + "#" +
<del> type + "#" +
<del> packetId + "#" +
<del> sender + "#" +
<del> recipient;
<del> this.benchmarksList.add(row);
<add> public static String getDate(String format) {
<add> // example "HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss" ecc...
<add> SimpleDateFormat dateFormat = new SimpleDateFormat(format);
<add> return dateFormat.format(new Date());
<ide> }
<del>
<del> public void removeLastBenchmark() {
<del> this.benchmarksList.remove(benchmarksList.size() - 1);
<del> }
<del>
<del> public ArrayList<String> getBenchmarks() {
<del> return benchmarksList;
<add>
<add> private static String getFileExtension(String filename) {
<add> if (filename.lastIndexOf(".") != -1 && filename.lastIndexOf(".") != 0)
<add> return filename.substring(filename.lastIndexOf(".") + 1);
<add> else
<add> return "";
<ide> }
<ide> } |
|
Java | unlicense | ca3d7e9b6f9f2dbd1e8812db9eadc3ce624b0716 | 0 | EastWest14/CongestionImmitation,EastWest14/CongestionImmitation | package controller;
import analyzer.*;
import java.lang.*;
public class SystemTest {
public static void main(String args[]) {
boolean testPasses = true;
boolean scenario1 = testScenario1();
if (!scenario1) {
testPasses = false;
}
boolean scenario2 = testScenario2();
if (!scenario2) {
testPasses = false;
}
if (testPasses) {
System.out.println("Full System Test: PASS");
System.exit(0);
} else {
System.out.println("Full System Test: FAIL");
System.exit(1);
}
}
//SCENARIO 1: MINIMAL CONGESTION.
private static boolean testScenario1() {
Controller contr = new Controller(1000000, 1000, 10);
contr.run();
Analyzer analyzer = contr.analyzer();
int numReceived = analyzer.numberOfReceivedPackets();
if (numReceived > 1000 || numReceived < 999) {
System.out.println(" Expected 999-1000 received packets. Got: " + numReceived + ".");
return false;
}
int minTravelTime = analyzer.minimumTravelTime();
if (minTravelTime != 10) {
System.out.println(" Expected minimum travel time for packets to be 10. Got: " + minTravelTime + ".");
return false;
}
int maxTravelTime = analyzer.maximumTravelTime();
if (maxTravelTime < 10 || maxTravelTime > 20) {
System.out.println(" Expected maximim travel time for packets to be in range 10-20. Got: " + maxTravelTime + ".");
return false;
}
double averageTravelTime = analyzer.averageTravelTime();
if (averageTravelTime < 10.0 || averageTravelTime > 10.1) {
System.out.println(" Expected average travel time for packets to be in range 10 to 10.1. Got: " + averageTravelTime + ".");
return false;
}
int maxBufferQueue = analyzer.maximumBufferQueueLength();
if (maxBufferQueue < 0 || maxBufferQueue > 2) {
System.out.println(" Expected maximim buffer queue length to be in range 0-2. Got: " + maxBufferQueue + ".");
return false;
}
double averageQueueLength = analyzer.averageBufferQueueLength();
if (averageQueueLength < 0.002 || averageQueueLength > 0.02) {
System.out.println(" Expected average buffer queue length to be in range 0.0 to 0.1. Got: " + averageQueueLength + ".");
return false;
}
return true;
}
//SCENARIO 2: ONLY 1 PACKET SENT.
private static boolean testScenario2() {
Controller contr = new Controller(1000000, 1, 10);
contr.run();
Analyzer analyzer = contr.analyzer();
int numReceived = analyzer.numberOfReceivedPackets();
if (numReceived != 1) {
System.out.println(" Expected 1 received packet. Got: " + numReceived + ".");
return false;
}
int minTravelTime = analyzer.minimumTravelTime();
if (minTravelTime != 10) {
System.out.println(" Expected minimum travel time for packets to be 10. Got: " + minTravelTime + ".");
return false;
}
int maxTravelTime = analyzer.maximumTravelTime();
if (maxTravelTime != 10) {
System.out.println(" Expected maximim travel time for packets to be 10. Got: " + maxTravelTime + ".");
return false;
}
double averageTravelTime = analyzer.averageTravelTime();
if (Math.abs(averageTravelTime - 10.0) > 0.00001) {
System.out.println(" Expected average travel time for packets to be 10.0. Got: " + averageTravelTime + ".");
return false;
}
int maxBufferQueue = analyzer.maximumBufferQueueLength();
if (maxBufferQueue != 0) {
System.out.println(" Expected maximim buffer queue length to be 0. Got: " + maxBufferQueue + ".");
return false;
}
double averageQueueLength = analyzer.averageBufferQueueLength();
if (averageQueueLength > 0.00001) {
System.out.println(" Expected average buffer queue length to be 0.0. Got: " + averageQueueLength + ".");
return false;
}
return true;
}
} | src/controller/SystemTest.java | package controller;
import analyzer.*;
public class SystemTest {
public static void main(String args[]) {
boolean testPasses = true;
boolean scenario1 = testScenario1();
if (!scenario1) {
testPasses = false;
}
if (testPasses) {
System.out.println("Full System Test: PASS");
System.exit(0);
} else {
System.out.println("Full System Test: FAIL");
System.exit(1);
}
}
//SCENARIO 1: MINIMAL CONGESTION.
private static boolean testScenario1() {
Controller contr = new Controller(1000000, 1000, 10);
contr.run();
Analyzer analyzer = contr.analyzer();
int numReceived = analyzer.numberOfReceivedPackets();
if (numReceived > 1000 || numReceived < 999) {
System.out.println(" Expected 999-1000 received packets. Got: " + numReceived + ".");
return false;
}
int minTravelTime = analyzer.minimumTravelTime();
if (minTravelTime != 10) {
System.out.println(" Expected minimum travel time for packets to be 10. Got: " + minTravelTime + ".");
return false;
}
int maxTravelTime = analyzer.maximumTravelTime();
if (maxTravelTime < 10 || maxTravelTime > 20) {
System.out.println(" Expected maximim travel time for packets to be in range 10-20. Got: " + maxTravelTime + ".");
return false;
}
double averageTravelTime = analyzer.averageTravelTime();
if (averageTravelTime < 10.0 || averageTravelTime > 10.1) {
System.out.println(" Expected average travel time for packets to be in range 10 to 10.1. Got: " + averageTravelTime + ".");
return false;
}
int maxBufferQueue = analyzer.maximumBufferQueueLength();
if (maxBufferQueue < 0 || maxBufferQueue > 2) {
System.out.println(" Expected maximim buffer queue length to be in range 0-2. Got: " + maxBufferQueue + ".");
return false;
}
double averageQueueLength = analyzer.averageBufferQueueLength();
if (averageQueueLength < 0.002 || averageQueueLength > 0.02) {
System.out.println(" Expected average buffer queue length to be in range 0.0 to 0.1. Got: " + averageQueueLength + ".");
return false;
}
return true;
}
} | Test scenarion II: One packet sent.
| src/controller/SystemTest.java | Test scenarion II: One packet sent. | <ide><path>rc/controller/SystemTest.java
<ide> package controller;
<ide>
<ide> import analyzer.*;
<add>import java.lang.*;
<ide>
<ide> public class SystemTest {
<ide> public static void main(String args[]) {
<ide>
<ide> boolean scenario1 = testScenario1();
<ide> if (!scenario1) {
<add> testPasses = false;
<add> }
<add>
<add> boolean scenario2 = testScenario2();
<add> if (!scenario2) {
<ide> testPasses = false;
<ide> }
<ide>
<ide>
<ide> return true;
<ide> }
<add>
<add> //SCENARIO 2: ONLY 1 PACKET SENT.
<add> private static boolean testScenario2() {
<add> Controller contr = new Controller(1000000, 1, 10);
<add> contr.run();
<add> Analyzer analyzer = contr.analyzer();
<add>
<add> int numReceived = analyzer.numberOfReceivedPackets();
<add> if (numReceived != 1) {
<add> System.out.println(" Expected 1 received packet. Got: " + numReceived + ".");
<add> return false;
<add> }
<add>
<add> int minTravelTime = analyzer.minimumTravelTime();
<add> if (minTravelTime != 10) {
<add> System.out.println(" Expected minimum travel time for packets to be 10. Got: " + minTravelTime + ".");
<add> return false;
<add> }
<add>
<add> int maxTravelTime = analyzer.maximumTravelTime();
<add> if (maxTravelTime != 10) {
<add> System.out.println(" Expected maximim travel time for packets to be 10. Got: " + maxTravelTime + ".");
<add> return false;
<add> }
<add>
<add> double averageTravelTime = analyzer.averageTravelTime();
<add> if (Math.abs(averageTravelTime - 10.0) > 0.00001) {
<add> System.out.println(" Expected average travel time for packets to be 10.0. Got: " + averageTravelTime + ".");
<add> return false;
<add> }
<add>
<add> int maxBufferQueue = analyzer.maximumBufferQueueLength();
<add> if (maxBufferQueue != 0) {
<add> System.out.println(" Expected maximim buffer queue length to be 0. Got: " + maxBufferQueue + ".");
<add> return false;
<add> }
<add>
<add> double averageQueueLength = analyzer.averageBufferQueueLength();
<add> if (averageQueueLength > 0.00001) {
<add> System.out.println(" Expected average buffer queue length to be 0.0. Got: " + averageQueueLength + ".");
<add> return false;
<add> }
<add>
<add> return true;
<add> }
<ide> } |
|
JavaScript | apache-2.0 | ae36ce63b6561e0ebd940308612ed13f00795c13 | 0 | thurt/arangodb,CoDEmanX/ArangoDB,wiltonlazary/arangodb,graetzer/arangodb,arangodb/arangodb,m0ppers/arangodb,thurt/arangodb,graetzer/arangodb,kangkot/arangodb,baslr/ArangoDB,baslr/ArangoDB,hkernbach/arangodb,Simran-B/arangodb,thurt/arangodb,graetzer/arangodb,hkernbach/arangodb,jsteemann/arangodb,joerg84/arangodb,Simran-B/arangodb,CoDEmanX/ArangoDB,fceller/arangodb,jsteemann/arangodb,fceller/arangodb,kangkot/arangodb,thurt/arangodb,baslr/ArangoDB,graetzer/arangodb,Simran-B/arangodb,CoDEmanX/ArangoDB,wiltonlazary/arangodb,joerg84/arangodb,jsteemann/arangodb,arangodb/arangodb,graetzer/arangodb,jsteemann/arangodb,CoDEmanX/ArangoDB,Simran-B/arangodb,CoDEmanX/ArangoDB,kangkot/arangodb,Simran-B/arangodb,arangodb/arangodb,Simran-B/arangodb,hkernbach/arangodb,m0ppers/arangodb,baslr/ArangoDB,wiltonlazary/arangodb,thurt/arangodb,joerg84/arangodb,hkernbach/arangodb,joerg84/arangodb,joerg84/arangodb,graetzer/arangodb,Simran-B/arangodb,jsteemann/arangodb,joerg84/arangodb,joerg84/arangodb,hkernbach/arangodb,graetzer/arangodb,m0ppers/arangodb,wiltonlazary/arangodb,m0ppers/arangodb,graetzer/arangodb,hkernbach/arangodb,jsteemann/arangodb,graetzer/arangodb,baslr/ArangoDB,kangkot/arangodb,m0ppers/arangodb,baslr/ArangoDB,baslr/ArangoDB,hkernbach/arangodb,baslr/ArangoDB,Simran-B/arangodb,kangkot/arangodb,joerg84/arangodb,jsteemann/arangodb,fceller/arangodb,joerg84/arangodb,joerg84/arangodb,fceller/arangodb,joerg84/arangodb,fceller/arangodb,fceller/arangodb,hkernbach/arangodb,graetzer/arangodb,graetzer/arangodb,hkernbach/arangodb,jsteemann/arangodb,graetzer/arangodb,thurt/arangodb,CoDEmanX/ArangoDB,baslr/ArangoDB,m0ppers/arangodb,kangkot/arangodb,fceller/arangodb,kangkot/arangodb,wiltonlazary/arangodb,hkernbach/arangodb,baslr/ArangoDB,CoDEmanX/ArangoDB,hkernbach/arangodb,arangodb/arangodb,CoDEmanX/ArangoDB,hkernbach/arangodb,kangkot/arangodb,arangodb/arangodb,fceller/arangodb,fceller/arangodb,thurt/arangodb,Simran-B/arangodb,m0ppers/arangodb,graetzer/arangodb,fceller/arangodb,jsteemann/arangodb,jsteemann/arangodb,hkernbach/arangodb,graetzer/arangodb,CoDEmanX/ArangoDB,kangkot/arangodb,CoDEmanX/ArangoDB,m0ppers/arangodb,thurt/arangodb,wiltonlazary/arangodb,baslr/ArangoDB,m0ppers/arangodb,kangkot/arangodb,m0ppers/arangodb,joerg84/arangodb,joerg84/arangodb,Simran-B/arangodb,thurt/arangodb,baslr/ArangoDB,m0ppers/arangodb,baslr/ArangoDB,joerg84/arangodb,hkernbach/arangodb,m0ppers/arangodb,wiltonlazary/arangodb,wiltonlazary/arangodb,arangodb/arangodb,arangodb/arangodb,baslr/ArangoDB,m0ppers/arangodb,arangodb/arangodb,thurt/arangodb | /*jslint indent: 2, nomen: true, maxlen: 80, sloppy: true */
/*global require, assertEqual, assertTrue */
////////////////////////////////////////////////////////////////////////////////
/// @brief test the graph class
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler, Lucas Dohmen
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
var jsunity = require("jsunity");
var arangodb = require("org/arangodb");
var console = require("console");
var ArangoCollection = arangodb.ArangoCollection;
var print = arangodb.print;
// -----------------------------------------------------------------------------
// --SECTION-- graph module
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: Graph Creation
////////////////////////////////////////////////////////////////////////////////
function GraphCreationSuite() {
return {
////////////////////////////////////////////////////////////////////////////////
/// @brief test: Graph Creation
////////////////////////////////////////////////////////////////////////////////
testCreation : function () {
var Graph = require("org/arangodb/graph").Graph,
graph_name = "UnitTestsCollectionGraph",
vertex = "UnitTestsCollectionVertex",
edge = "UnitTestsCollectionEdge",
graph = null;
graph = new Graph(graph_name, vertex, edge);
assertEqual(graph_name, graph._properties._key);
assertTrue(graph._vertices.type() == ArangoCollection.TYPE_DOCUMENT);
assertTrue(graph._edges.type() == ArangoCollection.TYPE_EDGE);
graph.drop();
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: Find Graph
////////////////////////////////////////////////////////////////////////////////
testFindGraph : function () {
var Graph = require("org/arangodb/graph").Graph,
graph_name = "UnitTestsCollectionGraph",
vertex = "UnitTestsCollectionVertex",
edge = "UnitTestsCollectionEdge",
graph1 = null,
graph2 = null;
graph1 = new Graph(graph_name, vertex, edge);
graph2 = new Graph(graph_name);
assertEqual(graph1._properties.name, graph2._properties.name);
assertEqual(graph1._vertices._id, graph2._vertices._id);
assertEqual(graph1._edges._id, graph2._edges._id);
graph1.drop();
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: Find Graph
////////////////////////////////////////////////////////////////////////////////
testCreateGraph : function () {
var Graph = require("org/arangodb/graph").Graph,
graph_name = "UnitTestsCollectionGraph",
vertex = "UnitTestsCollectionVertex",
edge = "UnitTestsCollectionEdge",
one = null,
two = null,
graph = null;
graph = new Graph(graph_name, vertex, edge);
one = graph.addVertex("one");
two = graph.addVertex("two");
graph.addEdge(one, two);
graph.drop();
}
};
}
////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: Graph Basics
////////////////////////////////////////////////////////////////////////////////
function GraphBasicsSuite() {
var Graph = require("org/arangodb/graph").Graph,
graph_name = "UnitTestsCollectionGraph",
vertex = "UnitTestsCollectionVertex",
edge = "UnitTestsCollectionEdge",
graph = null;
return {
////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////
setUp : function () {
try {
try {
graph = new Graph(graph_name);
print("FOUND: ");
printObject(graph);
graph.drop();
} catch (err1) {
}
graph = new Graph(graph_name, vertex, edge);
} catch (err2) {
console.error("[FAILED] setup failed:" + err2);
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////
tearDown : function () {
try {
if (graph !== null) {
graph.drop();
}
} catch (err) {
console.error("[FAILED] tear-down failed:" + err);
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief create a vertex without data
////////////////////////////////////////////////////////////////////////////////
testCreateVertexWithoutData : function () {
var v = graph.addVertex("name1");
assertEqual("name1", v.getId());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief create a vertex
////////////////////////////////////////////////////////////////////////////////
testCreateVertex : function () {
var v = graph.addVertex("name1", { age : 23 });
assertEqual("name1", v.getId());
assertEqual(23, v.getProperty("age"));
},
////////////////////////////////////////////////////////////////////////////////
/// @brief get a vertex
////////////////////////////////////////////////////////////////////////////////
testGetVertex : function () {
var v1 = graph.addVertex("find_me", { age : 23 }),
vid,
v2;
vid = v1.getId();
v2 = graph.getVertex(vid);
assertEqual(23, v2.getProperty("age"));
},
////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////
testChangeProperty : function () {
var v = graph.addVertex("name2", { age : 32 });
assertEqual("name2", v.getId());
assertEqual(32, v.getProperty("age"));
v.setProperty("age", 23);
assertEqual("name2", v.getId());
assertEqual(23, v.getProperty("age"));
},
////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////
testAddEdgeWithoutInfo : function () {
var v1,
v2,
edge;
v1 = graph.addVertex("vertex1");
v2 = graph.addVertex("vertex2");
edge = graph.addEdge(v1, v2);
assertEqual(edge._properties._key, edge.getId());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////
testAddEdge : function () {
var v1,
v2,
edge;
v1 = graph.addVertex("vertex1");
v2 = graph.addVertex("vertex2");
edge = graph.addEdge(v1,
v2,
"edge1",
"label",
{ testProperty: "testValue" });
assertEqual("edge1", edge.getId());
assertEqual("label", edge.getLabel());
assertEqual("testValue", edge.getProperty("testProperty"));
},
////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////
testGetEdges : function () {
var v1,
v2,
edge1,
edge2;
v1 = graph.addVertex("vertex1");
v2 = graph.addVertex("vertex2");
edge1 = graph.addEdge(v1,
v2,
"edge1",
"label",
{ testProperty: "testValue" });
edge2 = graph.getEdges().next();
assertEqual(true, graph.getEdges().hasNext());
assertEqual(edge1.getId(), edge2.getId());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief remove an edge
////////////////////////////////////////////////////////////////////////////////
testRemoveEdges : function () {
var v1,
v2,
edge;
v1 = graph.addVertex("vertex1");
v2 = graph.addVertex("vertex2");
edge = graph.addEdge(v1,
v2,
"edge1",
"label",
{ testProperty: "testValue" });
graph.removeEdge(edge);
assertEqual(false, graph.getEdges().hasNext());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief remove a vertex
////////////////////////////////////////////////////////////////////////////////
testRemoveVertex : function () {
var v1,
v1_id,
v2,
edge;
v1 = graph.addVertex("vertex1");
v1_id = v1.getId();
v2 = graph.addVertex("vertex2");
edge = graph.addEdge(v1,
v2,
"edge1",
"label",
{ testProperty: "testValue" });
graph.removeVertex(v1);
assertEqual(null, graph.getVertex(v1_id));
assertEqual(false, graph.getEdges().hasNext());
}
};
}
////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: Vertex
////////////////////////////////////////////////////////////////////////////////
function VertexSuite() {
var Graph = require("org/arangodb/graph").Graph,
graph_name = "UnitTestsCollectionGraph",
vertex = "UnitTestsCollectionVertex",
edge = "UnitTestsCollectionEdge",
graph = null;
return {
////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////
setUp : function () {
try {
try {
graph = new Graph(graph_name);
print("FOUND: ");
printObject(graph);
graph.drop();
} catch (err1) {
}
graph = new Graph(graph_name, vertex, edge);
} catch (err2) {
console.error("[FAILED] setup failed:" + err2);
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////
tearDown : function () {
try {
if (graph !== null) {
graph.drop();
}
} catch (err) {
console.error("[FAILED] tear-down failed:" + err);
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief add edges
////////////////////////////////////////////////////////////////////////////////
testAddEdges : function () {
var v1,
v2,
v3,
edge1,
edge2;
v1 = graph.addVertex();
v2 = graph.addVertex();
v3 = graph.addVertex();
edge1 = v1.addInEdge(v2);
edge2 = v1.addOutEdge(v3);
assertEqual(v1.getId(), edge1.getInVertex().getId());
assertEqual(v2.getId(), edge1.getOutVertex().getId());
assertEqual(v3.getId(), edge2.getInVertex().getId());
assertEqual(v1.getId(), edge2.getOutVertex().getId());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief get edges
////////////////////////////////////////////////////////////////////////////////
testGetEdges : function () {
var v1,
v2,
edge;
v1 = graph.addVertex();
v2 = graph.addVertex();
edge = graph.addEdge(v1, v2);
assertEqual(edge.getId(), v1.getOutEdges()[0].getId());
assertEqual(edge.getId(), v2.getInEdges()[0].getId());
assertEqual(0, v1.getInEdges().length);
assertEqual(0, v2.getOutEdges().length);
assertEqual(edge.getId(), v1.edges()[0].getId());
assertEqual(edge.getId(), v2.edges()[0].getId());
assertEqual(1, v1.getEdges().length);
},
////////////////////////////////////////////////////////////////////////////////
/// @brief get edges with labels
////////////////////////////////////////////////////////////////////////////////
testGetEdgesWithLabels : function () {
var v1,
v2,
edge1,
edge2;
v1 = graph.addVertex();
v2 = graph.addVertex();
edge1 = graph.addEdge(v1, v2, null, "label_1");
edge2 = graph.addEdge(v1, v2, null, "label_2");
assertEqual(edge2.getId(), v1.getOutEdges("label_2")[0].getId());
assertEqual(1, v2.getInEdges("label_2").length);
},
////////////////////////////////////////////////////////////////////////////////
/// @brief properties
////////////////////////////////////////////////////////////////////////////////
testProperties : function () {
var v1;
v1 = graph.addVertex();
v1.setProperty("myProperty", "myValue");
assertEqual("myValue", v1.getProperty("myProperty"));
assertEqual("myProperty", v1.getPropertyKeys()[0]);
assertEqual(1, v1.getPropertyKeys().length);
assertEqual({myProperty: "myValue"}, v1.properties());
}
};
}
////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: Edges
////////////////////////////////////////////////////////////////////////////////
function EdgeSuite() {
var Graph = require("org/arangodb/graph").Graph,
graph_name = "UnitTestsCollectionGraph",
vertex = "UnitTestsCollectionVertex",
edge = "UnitTestsCollectionEdge",
graph = null;
return {
////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////
setUp : function () {
try {
try {
graph = new Graph(graph_name);
print("FOUND: ");
printObject(graph);
graph.drop();
} catch (err1) {
}
graph = new Graph(graph_name, vertex, edge);
} catch (err2) {
console.error("[FAILED] setup failed:" + err2);
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////
tearDown : function () {
try {
if (graph !== null) {
graph.drop();
}
} catch (err) {
console.error("[FAILED] tear-down failed:" + err);
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief get Vertices
////////////////////////////////////////////////////////////////////////////////
testGetVertices : function () {
var v1,
v2,
edge;
v1 = graph.addVertex();
v2 = graph.addVertex();
edge = graph.addEdge(v1, v2);
assertEqual(v1.getId(), edge.getOutVertex().getId());
assertEqual(v2.getId(), edge.getInVertex().getId());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief get Vertices
////////////////////////////////////////////////////////////////////////////////
testGetLabel : function () {
var v1,
v2,
edge;
v1 = graph.addVertex();
v2 = graph.addVertex();
edge = graph.addEdge(v1, v2, null, "my_label");
assertEqual("my_label", edge.getLabel());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief Properties
////////////////////////////////////////////////////////////////////////////////
testProperties : function () {
var v1,
v2,
edge,
properties;
v1 = graph.addVertex();
v2 = graph.addVertex();
properties = { myProperty: "myValue"};
edge = graph.addEdge(v1, v2, null, "my_label", properties);
assertEqual(properties, edge.properties());
assertEqual("myValue", edge.getProperty("myProperty"));
edge.setProperty("foo", "bar");
assertEqual("bar", edge.getProperty("foo"));
assertEqual(["foo", "myProperty"], edge.getPropertyKeys());
}
};
}
// -----------------------------------------------------------------------------
// --SECTION-- main
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////
jsunity.run(GraphCreationSuite);
jsunity.run(GraphBasicsSuite);
jsunity.run(VertexSuite);
jsunity.run(EdgeSuite);
return jsunity.done();
// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:
| js/common/tests/shell-graph.js | /*jslint indent: 2, nomen: true, maxlen: 80, sloppy: true */
/*global require, assertEqual, assertTrue */
////////////////////////////////////////////////////////////////////////////////
/// @brief test the graph class
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler, Lucas Dohmen
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
var jsunity = require("jsunity");
var arangodb = require("org/arangodb");
var console = require("console");
var ArangoCollection = arangodb.ArangoCollection;
var print = arangodb.print;
// -----------------------------------------------------------------------------
// --SECTION-- graph module
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: Graph Creation
////////////////////////////////////////////////////////////////////////////////
function GraphCreationSuite() {
return {
////////////////////////////////////////////////////////////////////////////////
/// @brief test: Graph Creation
////////////////////////////////////////////////////////////////////////////////
testCreation : function () {
var Graph = require("org/arangodb/graph").Graph,
graph_name = "UnitTestsCollectionGraph",
vertex = "UnitTestsCollectionVertex",
edge = "UnitTestsCollectionEdge",
graph = null;
graph = new Graph(graph_name, vertex, edge);
assertEqual(graph_name, graph._properties._key);
assertTrue(graph._vertices.type() == ArangoCollection.TYPE_DOCUMENT);
assertTrue(graph._edges.type() == ArangoCollection.TYPE_EDGE);
graph.drop();
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: Find Graph
////////////////////////////////////////////////////////////////////////////////
testFindGraph : function () {
var Graph = require("org/arangodb/graph").Graph,
graph_name = "UnitTestsCollectionGraph",
vertex = "UnitTestsCollectionVertex",
edge = "UnitTestsCollectionEdge",
graph1 = null,
graph2 = null;
graph1 = new Graph(graph_name, vertex, edge);
graph2 = new Graph(graph_name);
assertEqual(graph1._properties.name, graph2._properties.name);
assertEqual(graph1._vertices._id, graph2._vertices._id);
assertEqual(graph1._edges._id, graph2._edges._id);
graph1.drop();
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test: Find Graph
////////////////////////////////////////////////////////////////////////////////
testCreateGraph : function () {
var Graph = require("org/arangodb/graph").Graph,
graph_name = "UnitTestsCollectionGraph",
vertex = "UnitTestsCollectionVertex",
edge = "UnitTestsCollectionEdge",
one = null,
two = null,
graph = null;
graph = new Graph(graph_name, vertex, edge);
one = graph.addVertex("one");
two = graph.addVertex("two");
graph.addEdge(one, two);
graph.drop();
}
};
}
////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: Graph Basics
////////////////////////////////////////////////////////////////////////////////
function GraphBasicsSuite() {
var Graph = require("org/arangodb/graph").Graph,
graph_name = "UnitTestsCollectionGraph",
vertex = "UnitTestsCollectionVertex",
edge = "UnitTestsCollectionEdge",
graph = null;
return {
////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////
setUp : function () {
try {
try {
graph = new Graph(graph_name);
print("FOUND: ");
printObject(graph);
graph.drop();
} catch (err1) {
}
graph = new Graph(graph_name, vertex, edge);
} catch (err2) {
console.error("[FAILED] setup failed:" + err2);
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////
tearDown : function () {
try {
if (graph !== null) {
graph.drop();
}
} catch (err) {
console.error("[FAILED] tear-down failed:" + err);
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief create a vertex without data
////////////////////////////////////////////////////////////////////////////////
testCreateVertexWithoutData : function () {
var v = graph.addVertex("name1");
assertEqual("name1", v.getId());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief create a vertex
////////////////////////////////////////////////////////////////////////////////
testCreateVertex : function () {
var v = graph.addVertex("name1", { age : 23 });
assertEqual("name1", v.getId());
assertEqual(23, v.getProperty("age"));
},
////////////////////////////////////////////////////////////////////////////////
/// @brief get a vertex
////////////////////////////////////////////////////////////////////////////////
testGetVertex : function () {
var v1 = graph.addVertex("find_me", { age : 23 }),
vid,
v2;
vid = v1.getId();
v2 = graph.getVertex(vid);
assertEqual(23, v2.getProperty("age"));
},
////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////
testChangeProperty : function () {
var v = graph.addVertex("name2", { age : 32 });
assertEqual("name2", v.getId());
assertEqual(32, v.getProperty("age"));
v.setProperty("age", 23);
assertEqual("name2", v.getId());
assertEqual(23, v.getProperty("age"));
},
////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////
testAddEdgeWithoutInfo : function () {
var v1,
v2,
edge;
v1 = graph.addVertex("vertex1");
v2 = graph.addVertex("vertex2");
edge = graph.addEdge(v1, v2);
assertEqual(edge._properties._key, edge.getId());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////
testAddEdge : function () {
var v1,
v2,
edge;
v1 = graph.addVertex("vertex1");
v2 = graph.addVertex("vertex2");
edge = graph.addEdge(v1,
v2,
"edge1",
"label",
{ testProperty: "testValue" });
assertEqual("edge1", edge.getId());
assertEqual("label", edge.getLabel());
assertEqual("testValue", edge.getProperty("testProperty"));
},
////////////////////////////////////////////////////////////////////////////////
/// @brief change a property
////////////////////////////////////////////////////////////////////////////////
testGetEdges : function () {
var v1,
v2,
edge1,
edge2;
v1 = graph.addVertex("vertex1");
v2 = graph.addVertex("vertex2");
edge1 = graph.addEdge(v1,
v2,
"edge1",
"label",
{ testProperty: "testValue" });
edge2 = graph.getEdges().next();
assertEqual(true, graph.getEdges().hasNext());
assertEqual(edge1.getId(), edge2.getId());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief remove an edge
////////////////////////////////////////////////////////////////////////////////
testRemoveEdges : function () {
var v1,
v2,
edge;
v1 = graph.addVertex("vertex1");
v2 = graph.addVertex("vertex2");
edge = graph.addEdge(v1,
v2,
"edge1",
"label",
{ testProperty: "testValue" });
graph.removeEdge(edge);
assertEqual(false, graph.getEdges().hasNext());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief remove a vertex
////////////////////////////////////////////////////////////////////////////////
testRemoveVertex : function () {
var v1,
v1_id,
v2,
edge;
v1 = graph.addVertex("vertex1");
v1_id = v1.getId();
v2 = graph.addVertex("vertex2");
edge = graph.addEdge(v1,
v2,
"edge1",
"label",
{ testProperty: "testValue" });
graph.removeVertex(v1);
assertEqual(null, graph.getVertex(v1_id));
assertEqual(false, graph.getEdges().hasNext());
}
};
}
////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: Vertex
////////////////////////////////////////////////////////////////////////////////
function VertexSuite() {
var Graph = require("org/arangodb/graph").Graph,
graph_name = "UnitTestsCollectionGraph",
vertex = "UnitTestsCollectionVertex",
edge = "UnitTestsCollectionEdge",
graph = null;
return {
////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////
setUp : function () {
try {
try {
graph = new Graph(graph_name);
print("FOUND: ");
printObject(graph);
graph.drop();
} catch (err1) {
}
graph = new Graph(graph_name, vertex, edge);
} catch (err2) {
console.error("[FAILED] setup failed:" + err2);
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////
tearDown : function () {
try {
if (graph !== null) {
graph.drop();
}
} catch (err) {
console.error("[FAILED] tear-down failed:" + err);
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief add edges
////////////////////////////////////////////////////////////////////////////////
testAddEdges : function () {
var v1,
v2,
v3,
edge1,
edge2;
v1 = graph.addVertex();
v2 = graph.addVertex();
v3 = graph.addVertex();
edge1 = v1.addInEdge(v2);
edge2 = v1.addOutEdge(v3);
assertEqual(v1.getId(), edge1.getInVertex().getId());
assertEqual(v2.getId(), edge1.getOutVertex().getId());
assertEqual(v3.getId(), edge2.getInVertex().getId());
assertEqual(v1.getId(), edge2.getOutVertex().getId());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief get edges
////////////////////////////////////////////////////////////////////////////////
testGetEdges : function () {
var v1,
v2,
edge;
v1 = graph.addVertex();
v2 = graph.addVertex();
edge = graph.addEdge(v1, v2);
assertEqual(edge.getId(), v1.getOutEdges()[0].getId());
assertEqual(edge.getId(), v2.getInEdges()[0].getId());
assertEqual([], v1.getInEdges());
assertEqual([], v2.getOutEdges());
assertEqual(edge.getId(), v1.edges()[0].getId());
assertEqual(edge.getId(), v2.edges()[0].getId());
assertEqual(1, v1.getEdges().length);
},
////////////////////////////////////////////////////////////////////////////////
/// @brief get edges with labels
////////////////////////////////////////////////////////////////////////////////
testGetEdgesWithLabels : function () {
var v1,
v2,
edge1,
edge2;
v1 = graph.addVertex();
v2 = graph.addVertex();
edge1 = graph.addEdge(v1, v2, null, "label_1");
edge2 = graph.addEdge(v1, v2, null, "label_2");
assertEqual(edge2.getId(), v1.getOutEdges("label_2")[0].getId());
assertEqual(1, v2.getInEdges("label_2").length);
},
////////////////////////////////////////////////////////////////////////////////
/// @brief properties
////////////////////////////////////////////////////////////////////////////////
testProperties : function () {
var v1;
v1 = graph.addVertex();
v1.setProperty("myProperty", "myValue");
assertEqual("myValue", v1.getProperty("myProperty"));
assertEqual("myProperty", v1.getPropertyKeys()[0]);
assertEqual(1, v1.getPropertyKeys().length);
assertEqual({myProperty: "myValue"}, v1.properties());
}
};
}
////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: Edges
////////////////////////////////////////////////////////////////////////////////
function EdgeSuite() {
var Graph = require("org/arangodb/graph").Graph,
graph_name = "UnitTestsCollectionGraph",
vertex = "UnitTestsCollectionVertex",
edge = "UnitTestsCollectionEdge",
graph = null;
return {
////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////
setUp : function () {
try {
try {
graph = new Graph(graph_name);
print("FOUND: ");
printObject(graph);
graph.drop();
} catch (err1) {
}
graph = new Graph(graph_name, vertex, edge);
} catch (err2) {
console.error("[FAILED] setup failed:" + err2);
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////
tearDown : function () {
try {
if (graph !== null) {
graph.drop();
}
} catch (err) {
console.error("[FAILED] tear-down failed:" + err);
}
},
////////////////////////////////////////////////////////////////////////////////
/// @brief get Vertices
////////////////////////////////////////////////////////////////////////////////
testGetVertices : function () {
var v1,
v2,
edge;
v1 = graph.addVertex();
v2 = graph.addVertex();
edge = graph.addEdge(v1, v2);
assertEqual(v1.getId(), edge.getOutVertex().getId());
assertEqual(v2.getId(), edge.getInVertex().getId());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief get Vertices
////////////////////////////////////////////////////////////////////////////////
testGetLabel : function () {
var v1,
v2,
edge;
v1 = graph.addVertex();
v2 = graph.addVertex();
edge = graph.addEdge(v1, v2, null, "my_label");
assertEqual("my_label", edge.getLabel());
},
////////////////////////////////////////////////////////////////////////////////
/// @brief Properties
////////////////////////////////////////////////////////////////////////////////
testProperties : function () {
var v1,
v2,
edge,
properties;
v1 = graph.addVertex();
v2 = graph.addVertex();
properties = { myProperty: "myValue"};
edge = graph.addEdge(v1, v2, null, "my_label", properties);
assertEqual(properties, edge.properties());
assertEqual("myValue", edge.getProperty("myProperty"));
edge.setProperty("foo", "bar");
assertEqual("bar", edge.getProperty("foo"));
assertEqual(["foo", "myProperty"], edge.getPropertyKeys());
}
};
}
// -----------------------------------------------------------------------------
// --SECTION-- main
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////
jsunity.run(GraphCreationSuite);
jsunity.run(GraphBasicsSuite);
jsunity.run(VertexSuite);
jsunity.run(EdgeSuite);
return jsunity.done();
// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:
| fixed test
| js/common/tests/shell-graph.js | fixed test | <ide><path>s/common/tests/shell-graph.js
<ide> v2 = graph.addVertex();
<ide>
<ide> edge = graph.addEdge(v1, v2);
<del>
<add>
<ide> assertEqual(edge.getId(), v1.getOutEdges()[0].getId());
<ide> assertEqual(edge.getId(), v2.getInEdges()[0].getId());
<del> assertEqual([], v1.getInEdges());
<del> assertEqual([], v2.getOutEdges());
<add> assertEqual(0, v1.getInEdges().length);
<add> assertEqual(0, v2.getOutEdges().length);
<ide> assertEqual(edge.getId(), v1.edges()[0].getId());
<ide> assertEqual(edge.getId(), v2.edges()[0].getId());
<ide> assertEqual(1, v1.getEdges().length); |
|
JavaScript | mit | 14f097b6c02c4b5eebf5bed51964271340bf002b | 0 | fent/node-ytdl | #!/usr/bin/env node
var url;
const info = require('../package');
const chalk = require('chalk');
const opts = require('commander')
.version(info.version)
.arguments('<url>')
.action((a) => { url = a; })
.option('-q, --quality <ITAG>',
'Video quality to download, default: highest')
.option('-r, --range <INT>..<INT>',
'Byte range to download, ie 10355705-12452856')
.option('-b, --begin <INT>', 'Time to begin video, format by 1:30.123 and 1m30s')
.option('-o, --output <FILE>', 'Save to file, template by {prop}, default: stdout')
.option('--filter <STR>',
'Can be video, videoonly, audio, audioonly',
/^(video|audio)(only)?$/)
.option('--filter-container <REGEXP>', 'Filter in format container')
.option('--unfilter-container <REGEXP>', 'Filter out format container')
.option('--filter-resolution <REGEXP>', 'Filter in format resolution')
.option('--unfilter-resolution <REGEXP>', 'Filter out format resolution')
.option('--filter-encoding <REGEXP>', 'Filter in format encoding')
.option('--unfilter-encoding <REGEXP>', 'Filter out format encoding')
.option('-i, --info', 'Print video info without downloading')
.option('-j, --info-json', 'Print video info as JSON without downloading')
.option('--print-url', 'Print direct download URL')
.option('--no-cache', 'Skip file cache for html5player')
.option('--debug', 'Print debug information')
.parse(process.argv)
;
if (!url) {
opts.outputHelp((help) => {
return chalk.red('\n url argument is required\n') + help;
});
process.exit(1);
}
const path = require('path');
const fs = require('fs');
const ytdl = require('ytdl-core');
const homedir = require('homedir');
const util = require('../lib/util');
const sanitizeName = require('sanitize-filename');
const label = chalk.bold.gray;
if (opts.cache !== false) {
// Keep cache in file.
var cachefile = path.resolve(homedir(), '.ytdl-cache.json');
var cache = {};
fs.readFile(cachefile, (err, contents) => {
if (err) return;
try {
cache = JSON.parse(contents);
} catch (err) {
console.error(`Badly formatted cachefile (${cachefile}): ${err.message}`);
}
});
ytdl.cache.sig.get = key => cache[key];
ytdl.cache.sig.set = (key, value) => {
cache[key] = value;
fs.writeFile(cachefile,
JSON.stringify(cache, null, 2), () => {});
};
}
/**
* Prints basic video information.
*
* @param {Object} info
*/
function printVideoInfo(info) {
console.log();
console.log(label('title: ') + info.title);
console.log(label('author: ') + info.author.name);
console.log(label('average rating: ') + info.avg_rating);
console.log(label('view count: ') + info.view_count);
console.log(label('length: ') + util.toHumanTime(info.length_seconds));
}
if (opts.infoJson) {
ytdl.getInfo(url, { debug: opts.debug }, (err, info) => {
if (err) {
console.error(err.message);
process.exit(1);
return;
}
console.log(JSON.stringify(info));
});
} else if (opts.info) {
const cliff = require('cliff');
ytdl.getInfo(url, { debug: opts.debug }, (err, info) => {
if (err) {
console.error(err.message);
process.exit(1);
return;
}
printVideoInfo(info);
var cols = [
'itag',
'container',
'resolution',
'video enc',
'audio bitrate',
'audio enc'
];
info.formats.forEach((format) => {
format['video enc'] = format.encoding;
format['audio bitrate'] = format.audioBitrate;
format['audio enc'] = format.audioEncoding;
cols.forEach((col) => {
format[col] = format[col] || '';
});
});
console.log(label('formats:'));
var colors = ['green', 'blue', 'green', 'blue', 'green', 'blue'];
console.log(cliff.stringifyObjectRows(info.formats, cols, colors));
});
} else {
var output = opts.output;
var ext = (output || '').match(/(\.\w+)?$/)[1];
if (output) {
if (ext && !opts.quality && !opts.filterContainer) {
opts.filterContainer = '^' + ext.slice(1) + '$';
}
}
var ytdlOptions = {};
ytdlOptions.quality = /,/.test(opts.quality) ?
opts.quality.split(',') : opts.quality;
if (opts.range) {
var s = opts.range.split('-');
ytdlOptions.range = { start: s[0], end: s[1] };
}
ytdlOptions.begin = opts.begin;
// Create filters.
var filters = [];
/**
* @param {String} field
* @param {String} regexpStr
* @param {Boolean|null} negated
*/
var createFilter = (field, regexpStr, negated) => {
try {
var regexp = new RegExp(regexpStr, 'i');
} catch (err) {
console.error(err.message);
process.exit(1);
}
filters.push(format => negated !== regexp.test(format[field]));
};
['container', 'resolution', 'encoding'].forEach((field) => {
var key = 'filter' + field[0].toUpperCase() + field.slice(1);
if (opts[key]) {
createFilter(field, opts[key], false);
}
key = 'un' + key;
if (opts[key]) {
createFilter(field, opts[key], true);
}
});
// Support basic ytdl-core filters manually, so that other
// cli filters are supported when used together.
switch (opts.filter) {
case 'video':
filters.push(format => format.bitrate);
break;
case 'videoonly':
filters.push(format => format.bitrate && !format.audioBitrate);
break;
case 'audio':
filters.push(format => format.audioBitrate);
break;
case 'audioonly':
filters.push(format => !format.bitrate && format.audioBitrate);
break;
}
ytdlOptions.filter = (format) => {
return filters.every(filter => filter(format));
};
if (opts.printUrl) {
ytdl.getInfo(url, { debug: opts.debug }, (err, info) => {
if (err) {
console.error(err.message);
process.exit(1);
return;
}
var format = ytdl.chooseFormat(info.formats, ytdlOptions);
if (format instanceof Error) {
console.error(format.message);
process.exit(1);
return;
}
console.log(format.url);
});
} else {
var readStream = ytdl(url, ytdlOptions);
var liveBroadcast = false;
var stdoutMutable = process.stdout && process.stdout.cursorTo && process.stdout.clearLine;
readStream.on('info', (info, format) => {
if (!output) {
readStream.pipe(process.stdout).on('error', (err) => {
console.error(err.message);
process.exit(1);
});
return;
}
output = util.tmpl(output, [info, format]);
if (!ext && format.container) {
output += '.' + format.container;
}
// Parses & sanitises output filename for any illegal characters
var parsedOutput = path.parse(output);
output = path.format({
dir: parsedOutput.dir,
base: sanitizeName(parsedOutput.base)
});
readStream.pipe(fs.createWriteStream(output))
.on('error', (err) => {
console.error(err.message);
process.exit(1);
});
// Print information about the video if not streaming to stdout.
printVideoInfo(info);
console.log(label('container: ') + format.container);
console.log(label('resolution: ') + format.resolution);
console.log(label('encoding: ') + format.encoding);
liveBroadcast = format.live;
if (!liveBroadcast) { return; }
const throttle = require('lodash.throttle');
var dataRead = 0;
var updateProgress = throttle(() => {
process.stdout.cursorTo(0);
process.stdout.clearLine(1);
process.stdout.write(label('size: ') + util.toHumanSize(dataRead) +
' (' + dataRead +' bytes)');
}, 500);
readStream.on('data', (data) => {
dataRead += data.length;
if (stdoutMutable) {
updateProgress();
}
});
readStream.on('end', () => {
if (stdoutMutable) {
console.log(label('downloaded: ') + util.toHumanSize(dataRead));
}
console.log();
})
});
readStream.on('response', (res) => {
if (!output || liveBroadcast) { return; }
// Print information about the format we're downloading.
var size = parseInt(res.headers['content-length'], 10);
console.log(label('size: ') + util.toHumanSize(size) +
' (' + size +' bytes)');
console.log(label('output: ') + output);
console.log();
if (!stdoutMutable) { return; }
// Create progress bar.
const bar = require('progress-bar').create(process.stdout, 50);
const throttle = require('lodash.throttle');
bar.format = '$bar; $percentage;%';
var lastPercent = null;
var updateBar = () => {
var percent = dataRead / size;
var newPercent = Math.floor(percent * 100);
if (newPercent != lastPercent) {
lastPercent = newPercent;
bar.update(percent);
}
};
var updateBarThrottled = throttle(updateBar, 100, { trailing: false });
// Keep track of progress.
var dataRead = 0;
readStream.on('data', (data) => {
dataRead += data.length;
if (dataRead === size) {
updateBar();
} else {
updateBarThrottled();
}
});
readStream.on('end', () => {
console.log();
});
});
readStream.on('error', (err) => {
console.error(err.message);
process.exit(1);
});
process.on('SIGINT', () => {
console.log();
process.exit();
});
}
}
| bin/ytdl.js | #!/usr/bin/env node
var url;
const info = require('../package');
const chalk = require('chalk');
const opts = require('commander')
.version(info.version)
.arguments('<url>')
.action((a) => { url = a; })
.option('-q, --quality <ITAG>',
'Video quality to download, default: highest')
.option('-r, --range <INT>..<INT>',
'Byte range to download, ie 10355705-12452856')
.option('-b, --begin <INT>', 'Time to begin video, format by 1:30.123 and 1m30s')
.option('-o, --output <FILE>', 'Save to file, template by {prop}, default: stdout')
.option('--filter <STR>',
'Can be video, videoonly, audio, audioonly',
/^(video|audio)(only)?$/)
.option('--filter-container <REGEXP>', 'Filter in format container')
.option('--unfilter-container <REGEXP>', 'Filter out format container')
.option('--filter-resolution <REGEXP>', 'Filter in format resolution')
.option('--unfilter-resolution <REGEXP>', 'Filter out format resolution')
.option('--filter-encoding <REGEXP>', 'Filter in format encoding')
.option('--unfilter-encoding <REGEXP>', 'Filter out format encoding')
.option('-i, --info', 'Print video info without downloading')
.option('-j, --info-json', 'Print video info as JSON without downloading')
.option('--print-url', 'Print direct download URL')
.option('--no-cache', 'Skip file cache for html5player')
.option('--debug', 'Print debug information')
.parse(process.argv)
;
if (!url) {
opts.outputHelp((help) => {
return chalk.red('\n url argument is required\n') + help;
});
process.exit(1);
}
const path = require('path');
const fs = require('fs');
const ytdl = require('ytdl-core');
const homedir = require('homedir');
const util = require('../lib/util');
const sanitizeName = require('sanitize-filename');
const label = chalk.bold.gray;
if (opts.cache !== false) {
// Keep cache in file.
var cachefile = path.resolve(homedir(), '.ytdl-cache.json');
var cache = {};
fs.readFile(cachefile, (err, contents) => {
if (err) return;
try {
cache = JSON.parse(contents);
} catch (err) {
console.error(`Badly formatted cachefile (${cachefile}): ${err.message}`);
}
});
ytdl.cache.get = key => cache[key];
ytdl.cache.set = (key, value) => {
cache[key] = value;
fs.writeFile(cachefile,
JSON.stringify(cache, null, 2), () => {});
};
}
/**
* Prints basic video information.
*
* @param {Object} info
*/
function printVideoInfo(info) {
console.log();
console.log(label('title: ') + info.title);
console.log(label('author: ') + info.author.name);
console.log(label('average rating: ') + info.avg_rating);
console.log(label('view count: ') + info.view_count);
console.log(label('length: ') + util.toHumanTime(info.length_seconds));
}
if (opts.infoJson) {
ytdl.getInfo(url, { debug: opts.debug }, (err, info) => {
if (err) {
console.error(err.message);
process.exit(1);
return;
}
console.log(JSON.stringify(info));
});
} else if (opts.info) {
const cliff = require('cliff');
ytdl.getInfo(url, { debug: opts.debug }, (err, info) => {
if (err) {
console.error(err.message);
process.exit(1);
return;
}
printVideoInfo(info);
var cols = [
'itag',
'container',
'resolution',
'video enc',
'audio bitrate',
'audio enc'
];
info.formats.forEach((format) => {
format['video enc'] = format.encoding;
format['audio bitrate'] = format.audioBitrate;
format['audio enc'] = format.audioEncoding;
cols.forEach((col) => {
format[col] = format[col] || '';
});
});
console.log(label('formats:'));
var colors = ['green', 'blue', 'green', 'blue', 'green', 'blue'];
console.log(cliff.stringifyObjectRows(info.formats, cols, colors));
});
} else {
var output = opts.output;
var ext = (output || '').match(/(\.\w+)?$/)[1];
if (output) {
if (ext && !opts.quality && !opts.filterContainer) {
opts.filterContainer = '^' + ext.slice(1) + '$';
}
}
var ytdlOptions = {};
ytdlOptions.quality = /,/.test(opts.quality) ?
opts.quality.split(',') : opts.quality;
if (opts.range) {
var s = opts.range.split('-');
ytdlOptions.range = { start: s[0], end: s[1] };
}
ytdlOptions.begin = opts.begin;
// Create filters.
var filters = [];
/**
* @param {String} field
* @param {String} regexpStr
* @param {Boolean|null} negated
*/
var createFilter = (field, regexpStr, negated) => {
try {
var regexp = new RegExp(regexpStr, 'i');
} catch (err) {
console.error(err.message);
process.exit(1);
}
filters.push(format => negated !== regexp.test(format[field]));
};
['container', 'resolution', 'encoding'].forEach((field) => {
var key = 'filter' + field[0].toUpperCase() + field.slice(1);
if (opts[key]) {
createFilter(field, opts[key], false);
}
key = 'un' + key;
if (opts[key]) {
createFilter(field, opts[key], true);
}
});
// Support basic ytdl-core filters manually, so that other
// cli filters are supported when used together.
switch (opts.filter) {
case 'video':
filters.push(format => format.bitrate);
break;
case 'videoonly':
filters.push(format => format.bitrate && !format.audioBitrate);
break;
case 'audio':
filters.push(format => format.audioBitrate);
break;
case 'audioonly':
filters.push(format => !format.bitrate && format.audioBitrate);
break;
}
ytdlOptions.filter = (format) => {
return filters.every(filter => filter(format));
};
if (opts.printUrl) {
ytdl.getInfo(url, { debug: opts.debug }, (err, info) => {
if (err) {
console.error(err.message);
process.exit(1);
return;
}
var format = ytdl.chooseFormat(info.formats, ytdlOptions);
if (format instanceof Error) {
console.error(format.message);
process.exit(1);
return;
}
console.log(format.url);
});
} else {
var readStream = ytdl(url, ytdlOptions);
var liveBroadcast = false;
var stdoutMutable = process.stdout && process.stdout.cursorTo && process.stdout.clearLine;
readStream.on('info', (info, format) => {
if (!output) {
readStream.pipe(process.stdout).on('error', (err) => {
console.error(err.message);
process.exit(1);
});
return;
}
output = util.tmpl(output, [info, format]);
if (!ext && format.container) {
output += '.' + format.container;
}
// Parses & sanitises output filename for any illegal characters
var parsedOutput = path.parse(output);
output = path.format({
dir: parsedOutput.dir,
base: sanitizeName(parsedOutput.base)
});
readStream.pipe(fs.createWriteStream(output))
.on('error', (err) => {
console.error(err.message);
process.exit(1);
});
// Print information about the video if not streaming to stdout.
printVideoInfo(info);
console.log(label('container: ') + format.container);
console.log(label('resolution: ') + format.resolution);
console.log(label('encoding: ') + format.encoding);
liveBroadcast = format.live;
if (!liveBroadcast) { return; }
const throttle = require('lodash.throttle');
var dataRead = 0;
var updateProgress = throttle(() => {
process.stdout.cursorTo(0);
process.stdout.clearLine(1);
process.stdout.write(label('size: ') + util.toHumanSize(dataRead) +
' (' + dataRead +' bytes)');
}, 500);
readStream.on('data', (data) => {
dataRead += data.length;
if (stdoutMutable) {
updateProgress();
}
});
readStream.on('end', () => {
if (stdoutMutable) {
console.log(label('downloaded: ') + util.toHumanSize(dataRead));
}
console.log();
})
});
readStream.on('response', (res) => {
if (!output || liveBroadcast) { return; }
// Print information about the format we're downloading.
var size = parseInt(res.headers['content-length'], 10);
console.log(label('size: ') + util.toHumanSize(size) +
' (' + size +' bytes)');
console.log(label('output: ') + output);
console.log();
if (!stdoutMutable) { return; }
// Create progress bar.
const bar = require('progress-bar').create(process.stdout, 50);
const throttle = require('lodash.throttle');
bar.format = '$bar; $percentage;%';
var lastPercent = null;
var updateBar = () => {
var percent = dataRead / size;
var newPercent = Math.floor(percent * 100);
if (newPercent != lastPercent) {
lastPercent = newPercent;
bar.update(percent);
}
};
var updateBarThrottled = throttle(updateBar, 100, { trailing: false });
// Keep track of progress.
var dataRead = 0;
readStream.on('data', (data) => {
dataRead += data.length;
if (dataRead === size) {
updateBar();
} else {
updateBarThrottled();
}
});
readStream.on('end', () => {
console.log();
});
});
readStream.on('error', (err) => {
console.error(err.message);
process.exit(1);
});
process.on('SIGINT', () => {
console.log();
process.exit();
});
}
}
| fix: update path of ytdl-core sig cache
| bin/ytdl.js | fix: update path of ytdl-core sig cache | <ide><path>in/ytdl.js
<ide> }
<ide> });
<ide>
<del> ytdl.cache.get = key => cache[key];
<del> ytdl.cache.set = (key, value) => {
<add> ytdl.cache.sig.get = key => cache[key];
<add> ytdl.cache.sig.set = (key, value) => {
<ide> cache[key] = value;
<ide> fs.writeFile(cachefile,
<ide> JSON.stringify(cache, null, 2), () => {}); |
|
Java | apache-2.0 | 8203ac01b9ce478f3bbfcc0092e53c09c6487c65 | 0 | k21/buck,darkforestzero/buck,zhan-xiong/buck,zhan-xiong/buck,kageiit/buck,nguyentruongtho/buck,robbertvanginkel/buck,robbertvanginkel/buck,justinmuller/buck,grumpyjames/buck,zpao/buck,k21/buck,dsyang/buck,marcinkwiatkowski/buck,daedric/buck,vschs007/buck,romanoid/buck,daedric/buck,shybovycha/buck,darkforestzero/buck,darkforestzero/buck,vschs007/buck,SeleniumHQ/buck,sdwilsh/buck,zhan-xiong/buck,dsyang/buck,davido/buck,shybovycha/buck,justinmuller/buck,rmaz/buck,shybovycha/buck,darkforestzero/buck,shs96c/buck,LegNeato/buck,shs96c/buck,vschs007/buck,shybovycha/buck,romanoid/buck,davido/buck,dsyang/buck,daedric/buck,kageiit/buck,brettwooldridge/buck,zpao/buck,clonetwin26/buck,justinmuller/buck,brettwooldridge/buck,grumpyjames/buck,robbertvanginkel/buck,kageiit/buck,nguyentruongtho/buck,kageiit/buck,SeleniumHQ/buck,daedric/buck,LegNeato/buck,brettwooldridge/buck,SeleniumHQ/buck,shs96c/buck,rmaz/buck,shybovycha/buck,LegNeato/buck,grumpyjames/buck,davido/buck,justinmuller/buck,marcinkwiatkowski/buck,shybovycha/buck,facebook/buck,facebook/buck,JoelMarcey/buck,JoelMarcey/buck,robbertvanginkel/buck,grumpyjames/buck,k21/buck,grumpyjames/buck,daedric/buck,facebook/buck,romanoid/buck,Addepar/buck,LegNeato/buck,dsyang/buck,daedric/buck,Addepar/buck,clonetwin26/buck,rmaz/buck,LegNeato/buck,zpao/buck,daedric/buck,grumpyjames/buck,justinmuller/buck,rmaz/buck,zhan-xiong/buck,JoelMarcey/buck,darkforestzero/buck,vschs007/buck,zpao/buck,SeleniumHQ/buck,rmaz/buck,grumpyjames/buck,grumpyjames/buck,sdwilsh/buck,dsyang/buck,darkforestzero/buck,zhan-xiong/buck,SeleniumHQ/buck,sdwilsh/buck,brettwooldridge/buck,marcinkwiatkowski/buck,ilya-klyuchnikov/buck,romanoid/buck,sdwilsh/buck,nguyentruongtho/buck,brettwooldridge/buck,Addepar/buck,vschs007/buck,robbertvanginkel/buck,marcinkwiatkowski/buck,daedric/buck,darkforestzero/buck,shs96c/buck,brettwooldridge/buck,zpao/buck,vschs007/buck,robbertvanginkel/buck,ilya-klyuchnikov/buck,davido/buck,JoelMarcey/buck,romanoid/buck,marcinkwiatkowski/buck,brettwooldridge/buck,daedric/buck,rmaz/buck,robbertvanginkel/buck,vschs007/buck,clonetwin26/buck,Addepar/buck,shs96c/buck,rmaz/buck,kageiit/buck,k21/buck,shybovycha/buck,k21/buck,Addepar/buck,facebook/buck,davido/buck,LegNeato/buck,clonetwin26/buck,darkforestzero/buck,JoelMarcey/buck,darkforestzero/buck,shybovycha/buck,rmaz/buck,zhan-xiong/buck,robbertvanginkel/buck,marcinkwiatkowski/buck,justinmuller/buck,nguyentruongtho/buck,k21/buck,clonetwin26/buck,robbertvanginkel/buck,sdwilsh/buck,romanoid/buck,clonetwin26/buck,SeleniumHQ/buck,clonetwin26/buck,davido/buck,k21/buck,sdwilsh/buck,sdwilsh/buck,ilya-klyuchnikov/buck,shs96c/buck,JoelMarcey/buck,JoelMarcey/buck,zhan-xiong/buck,rmaz/buck,robbertvanginkel/buck,LegNeato/buck,shs96c/buck,rmaz/buck,JoelMarcey/buck,vschs007/buck,sdwilsh/buck,nguyentruongtho/buck,ilya-klyuchnikov/buck,shs96c/buck,romanoid/buck,clonetwin26/buck,daedric/buck,darkforestzero/buck,justinmuller/buck,shs96c/buck,Addepar/buck,marcinkwiatkowski/buck,zpao/buck,k21/buck,brettwooldridge/buck,daedric/buck,daedric/buck,Addepar/buck,justinmuller/buck,zhan-xiong/buck,marcinkwiatkowski/buck,JoelMarcey/buck,nguyentruongtho/buck,k21/buck,kageiit/buck,JoelMarcey/buck,grumpyjames/buck,clonetwin26/buck,Addepar/buck,justinmuller/buck,darkforestzero/buck,sdwilsh/buck,k21/buck,facebook/buck,romanoid/buck,SeleniumHQ/buck,SeleniumHQ/buck,davido/buck,romanoid/buck,zhan-xiong/buck,ilya-klyuchnikov/buck,SeleniumHQ/buck,ilya-klyuchnikov/buck,SeleniumHQ/buck,romanoid/buck,davido/buck,justinmuller/buck,romanoid/buck,vschs007/buck,marcinkwiatkowski/buck,robbertvanginkel/buck,SeleniumHQ/buck,shs96c/buck,justinmuller/buck,sdwilsh/buck,darkforestzero/buck,ilya-klyuchnikov/buck,SeleniumHQ/buck,LegNeato/buck,LegNeato/buck,brettwooldridge/buck,davido/buck,zhan-xiong/buck,shs96c/buck,Addepar/buck,justinmuller/buck,ilya-klyuchnikov/buck,shybovycha/buck,dsyang/buck,facebook/buck,romanoid/buck,shs96c/buck,vschs007/buck,vschs007/buck,marcinkwiatkowski/buck,justinmuller/buck,robbertvanginkel/buck,JoelMarcey/buck,ilya-klyuchnikov/buck,LegNeato/buck,romanoid/buck,sdwilsh/buck,marcinkwiatkowski/buck,ilya-klyuchnikov/buck,LegNeato/buck,ilya-klyuchnikov/buck,robbertvanginkel/buck,vschs007/buck,LegNeato/buck,ilya-klyuchnikov/buck,rmaz/buck,vschs007/buck,sdwilsh/buck,dsyang/buck,clonetwin26/buck,Addepar/buck,Addepar/buck,zhan-xiong/buck,davido/buck,sdwilsh/buck,grumpyjames/buck,rmaz/buck,dsyang/buck,grumpyjames/buck,clonetwin26/buck,brettwooldridge/buck,davido/buck,davido/buck,k21/buck,shybovycha/buck,shs96c/buck,k21/buck,darkforestzero/buck,brettwooldridge/buck,Addepar/buck,facebook/buck,zhan-xiong/buck,kageiit/buck,davido/buck,JoelMarcey/buck,dsyang/buck,grumpyjames/buck,ilya-klyuchnikov/buck,rmaz/buck,brettwooldridge/buck,daedric/buck,k21/buck,shybovycha/buck,dsyang/buck,brettwooldridge/buck,dsyang/buck,dsyang/buck,Addepar/buck,JoelMarcey/buck,shybovycha/buck,clonetwin26/buck,LegNeato/buck,SeleniumHQ/buck,nguyentruongtho/buck,marcinkwiatkowski/buck,clonetwin26/buck,shybovycha/buck,zhan-xiong/buck,zpao/buck,dsyang/buck,marcinkwiatkowski/buck | /*
* Copyright 2013-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.event.listener;
import com.facebook.buck.artifact_cache.ArtifactCacheEvent;
import com.facebook.buck.distributed.DistBuildStatus;
import com.facebook.buck.distributed.DistBuildStatusEvent;
import com.facebook.buck.distributed.thrift.BuildStatus;
import com.facebook.buck.distributed.thrift.LogRecord;
import com.facebook.buck.event.ActionGraphEvent;
import com.facebook.buck.event.ArtifactCompressionEvent;
import com.facebook.buck.event.ConsoleEvent;
import com.facebook.buck.event.DaemonEvent;
import com.facebook.buck.event.LeafEvent;
import com.facebook.buck.event.NetworkEvent;
import com.facebook.buck.event.ParsingEvent;
import com.facebook.buck.event.WatchmanStatusEvent;
import com.facebook.buck.httpserver.WebServer;
import com.facebook.buck.log.Logger;
import com.facebook.buck.model.Pair;
import com.facebook.buck.rules.BuildEvent;
import com.facebook.buck.rules.BuildRuleCacheEvent;
import com.facebook.buck.rules.BuildRuleEvent;
import com.facebook.buck.rules.TestRunEvent;
import com.facebook.buck.rules.TestStatusMessageEvent;
import com.facebook.buck.rules.TestSummaryEvent;
import com.facebook.buck.step.StepEvent;
import com.facebook.buck.test.TestResultSummary;
import com.facebook.buck.test.TestResultSummaryVerbosity;
import com.facebook.buck.test.TestResults;
import com.facebook.buck.test.TestStatusMessage;
import com.facebook.buck.test.result.type.ResultType;
import com.facebook.buck.timing.Clock;
import com.facebook.buck.util.Console;
import com.facebook.buck.util.MoreIterables;
import com.facebook.buck.util.environment.ExecutionEnvironment;
import com.facebook.buck.util.unit.SizeUnit;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.eventbus.Subscribe;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import javax.annotation.Nullable;
/**
* Console that provides rich, updating ansi output about the current build.
*/
public class SuperConsoleEventBusListener extends AbstractConsoleEventBusListener {
/**
* Maximum expected rendered line length so we can start with a decent
* size of line rendering buffer.
*/
private static final int EXPECTED_MAXIMUM_RENDERED_LINE_LENGTH = 128;
private static final Logger LOG = Logger.get(SuperConsoleEventBusListener.class);
@VisibleForTesting
static final String EMOJI_BUNNY = "\uD83D\uDC07";
@VisibleForTesting
static final String EMOJI_SNAIL = "\uD83D\uDC0C";
@VisibleForTesting
static final String EMOJI_WHALE = "\uD83D\uDC33";
@VisibleForTesting
static final Optional<String> NEW_DAEMON_INSTANCE_MSG =
createParsingMessage(EMOJI_WHALE, "New buck daemon");
private final Locale locale;
private final Function<Long, String> formatTimeFunction;
private final Optional<WebServer> webServer;
private final ConcurrentMap<Long, Optional<? extends TestSummaryEvent>>
threadsToRunningTestSummaryEvent;
private final ConcurrentMap<Long, Optional<? extends TestStatusMessageEvent>>
threadsToRunningTestStatusMessageEvent;
private final ConcurrentMap<Long, Optional<? extends LeafEvent>> threadsToRunningStep;
private final ConcurrentLinkedQueue<ConsoleEvent> logEvents;
private final ScheduledExecutorService renderScheduler;
private final TestResultFormatter testFormatter;
private final AtomicInteger testPasses = new AtomicInteger(0);
private final AtomicInteger testFailures = new AtomicInteger(0);
private final AtomicInteger testSkips = new AtomicInteger(0);
private final AtomicReference<TestRunEvent.Started> testRunStarted;
private final AtomicReference<TestRunEvent.Finished> testRunFinished;
private final ImmutableList.Builder<String> testReportBuilder = ImmutableList.builder();
private final ImmutableList.Builder<TestStatusMessage> testStatusMessageBuilder =
ImmutableList.builder();
private final AtomicBoolean anyWarningsPrinted = new AtomicBoolean(false);
private final AtomicBoolean anyErrorsPrinted = new AtomicBoolean(false);
private final int defaultThreadLineLimit;
private final int threadLineLimitOnWarning;
private final int threadLineLimitOnError;
private final boolean shouldAlwaysSortThreadsByTime;
private Optional<DistBuildStatus> distBuildStatus;
private final DateFormat dateFormat;
private int lastNumLinesPrinted;
protected Optional<String> parsingStatus = Optional.empty();
public SuperConsoleEventBusListener(
SuperConsoleConfig config,
Console console,
Clock clock,
TestResultSummaryVerbosity summaryVerbosity,
ExecutionEnvironment executionEnvironment,
Optional<WebServer> webServer,
Locale locale,
Path testLogPath,
TimeZone timeZone) {
super(console, clock, locale, executionEnvironment);
this.locale = locale;
this.formatTimeFunction = this::formatElapsedTime;
this.webServer = webServer;
this.threadsToRunningTestSummaryEvent = new ConcurrentHashMap<>(
executionEnvironment.getAvailableCores());
this.threadsToRunningTestStatusMessageEvent = new ConcurrentHashMap<>(
executionEnvironment.getAvailableCores());
this.threadsToRunningStep = new ConcurrentHashMap<>(executionEnvironment.getAvailableCores());
this.logEvents = new ConcurrentLinkedQueue<>();
this.renderScheduler = Executors.newScheduledThreadPool(1,
new ThreadFactoryBuilder().setNameFormat(getClass().getSimpleName() + "-%d").build());
this.testFormatter = new TestResultFormatter(
console.getAnsi(),
console.getVerbosity(),
summaryVerbosity,
locale,
Optional.of(testLogPath));
this.testRunStarted = new AtomicReference<>();
this.testRunFinished = new AtomicReference<>();
this.defaultThreadLineLimit = config.getThreadLineLimit();
this.threadLineLimitOnWarning = config.getThreadLineLimitOnWarning();
this.threadLineLimitOnError = config.getThreadLineLimitOnError();
this.shouldAlwaysSortThreadsByTime = config.shouldAlwaysSortThreadsByTime();
this.distBuildStatus = Optional.empty();
this.dateFormat = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss.SSS]", this.locale);
this.dateFormat.setTimeZone(timeZone);
}
/**
* Schedules a runnable that updates the console output at a fixed interval.
*/
public void startRenderScheduler(long renderInterval, TimeUnit timeUnit) {
LOG.debug("Starting render scheduler (interval %d ms)", timeUnit.toMillis(renderInterval));
renderScheduler.scheduleAtFixedRate(() -> {
try {
SuperConsoleEventBusListener.this.render();
} catch (Error | RuntimeException e) {
LOG.error(e, "Rendering exception");
throw e;
}
}, /* initialDelay */ renderInterval, /* period */ renderInterval, timeUnit);
}
/**
* Shuts down the thread pool and cancels the fixed interval runnable.
*/
private synchronized void stopRenderScheduler() {
LOG.debug("Stopping render scheduler");
renderScheduler.shutdownNow();
}
@VisibleForTesting
synchronized void render() {
LOG.verbose("Rendering");
String lastRenderClear = clearLastRender();
ImmutableList<String> lines = createRenderLinesAtTime(clock.currentTimeMillis());
ImmutableList<String> logLines = createLogRenderLines();
lastNumLinesPrinted = lines.size();
// Synchronize on the DirtyPrintStreamDecorator to prevent interlacing of output.
// We don't log immediately so we avoid locking the console handler to avoid deadlocks.
boolean stdoutDirty;
boolean stderrDirty;
synchronized (console.getStdOut()) {
synchronized (console.getStdErr()) {
// If another source has written to stderr or stdout, stop rendering with the SuperConsole.
// We need to do this to keep our updates consistent.
stdoutDirty = console.getStdOut().isDirty();
stderrDirty = console.getStdErr().isDirty();
if (stdoutDirty || stderrDirty) {
stopRenderScheduler();
} else if (!lastRenderClear.isEmpty() || !lines.isEmpty() || !logLines.isEmpty()) {
Iterable<String> renderedLines = Iterables.concat(
MoreIterables.zipAndConcat(
logLines,
Iterables.cycle("\n")),
ansi.asNoWrap(
MoreIterables.zipAndConcat(
lines,
Iterables.cycle("\n"))));
StringBuilder fullFrame = new StringBuilder(lastRenderClear);
for (String part : renderedLines) {
fullFrame.append(part);
}
console.getStdErr().getRawStream().print(fullFrame);
}
}
}
if (stdoutDirty || stderrDirty) {
LOG.debug(
"Stopping console output (stdout dirty %s, stderr dirty %s).",
stdoutDirty, stderrDirty);
}
}
/**
* Creates a list of lines to be rendered at a given time.
* @param currentTimeMillis The time in ms to use when computing elapsed times.
*/
@VisibleForTesting
ImmutableList<String> createRenderLinesAtTime(long currentTimeMillis) {
ImmutableList.Builder<String> lines = ImmutableList.builder();
// Print latest distributed build debug info lines
if (buildStarted != null && buildStarted.isDistributedBuild()) {
getDistBuildDebugInfo(lines);
}
// If we have not yet started processing the BUCK files, show parse times
if (parseStarted.isEmpty() && parseFinished.isEmpty()) {
logEventPair(
"PARSING BUCK FILES",
/* suffix */ Optional.empty(),
currentTimeMillis,
/* offsetMs */ 0L,
projectBuildFileParseStarted,
projectBuildFileParseFinished,
getEstimatedProgressOfProcessingBuckFiles(),
lines);
}
long parseTime = logEventPair("PROCESSING BUCK FILES",
/* suffix */ parsingStatus,
currentTimeMillis,
/* offsetMs */ 0L,
buckFilesProcessing.values(),
getEstimatedProgressOfProcessingBuckFiles(),
lines);
logEventPair(
"GENERATING PROJECT",
Optional.empty(),
currentTimeMillis,
/* offsetMs */ 0L,
projectGenerationStarted,
projectGenerationFinished,
getEstimatedProgressOfGeneratingProjectFiles(),
lines);
// If parsing has not finished, then there is no build rule information to print yet.
if (parseTime != UNFINISHED_EVENT_PAIR) {
lines.add(getNetworkStatsLine(buildFinished));
if (buildStarted != null && buildStarted.isDistributedBuild()) {
lines.add(getDistBuildStatusLine());
}
// Log build time, excluding time spent in parsing.
String jobSummary = null;
if (ruleCount.isPresent()) {
List<String> columns = Lists.newArrayList();
columns.add(String.format(locale, "%d/%d JOBS", numRulesCompleted.get(), ruleCount.get()));
CacheRateStatsKeeper.CacheRateStatsUpdateEvent cacheRateStats =
cacheRateStatsKeeper.getStats();
columns.add(String.format(
locale,
"%d UPDATED",
cacheRateStats.getUpdatedRulesCount()));
if (ruleCount.orElse(0) > 0) {
columns.add(
String.format(
locale,
"%d [%.1f%%] CACHE MISS",
cacheRateStats.getCacheMissCount(),
cacheRateStats.getCacheMissRate()));
if (cacheRateStats.getCacheErrorCount() > 0) {
columns.add(
String.format(
locale,
"%d [%.1f%%] CACHE ERRORS",
cacheRateStats.getCacheErrorCount(),
cacheRateStats.getCacheErrorRate()));
}
}
jobSummary = "(" + Joiner.on(", ").join(columns) + ")";
}
// If the Daemon is running and serving web traffic, print the URL to the Chrome Trace.
String buildTrace = null;
if (buildFinished != null && webServer.isPresent()) {
Optional<Integer> port = webServer.get().getPort();
if (port.isPresent()) {
buildTrace = String.format(
locale,
"Details: http://localhost:%s/trace/%s",
port.get(),
buildFinished.getBuildId());
}
}
if (buildStarted == null) {
// All steps past this point require a build.
return lines.build();
}
String suffix = Joiner.on("\n ")
.join(FluentIterable.of(new String[] {jobSummary, buildTrace})
.filter(Objects::nonNull));
Optional<String> suffixOptional =
suffix.isEmpty() ? Optional.empty() : Optional.of(suffix);
// Check to see if the build encompasses the time spent parsing. This is true for runs of
// buck build but not so for runs of e.g. buck project. If so, subtract parse times
// from the build time.
long buildStartedTime = buildStarted.getTimestamp();
long buildFinishedTime = buildFinished != null
? buildFinished.getTimestamp()
: currentTimeMillis;
Collection<EventPair> processingEvents = getEventsBetween(buildStartedTime,
buildFinishedTime,
buckFilesProcessing.values());
long offsetMs = getTotalCompletedTimeFromEventPairs(processingEvents);
long buildTime = logEventPair(
"BUILDING",
suffixOptional,
currentTimeMillis,
offsetMs, // parseTime,
this.buildStarted,
this.buildFinished,
getApproximateBuildProgress(),
lines);
int maxThreadLines = defaultThreadLineLimit;
if (anyWarningsPrinted.get() && threadLineLimitOnWarning < maxThreadLines) {
maxThreadLines = threadLineLimitOnWarning;
}
if (anyErrorsPrinted.get() && threadLineLimitOnError < maxThreadLines) {
maxThreadLines = threadLineLimitOnError;
}
if (buildTime == UNFINISHED_EVENT_PAIR) {
ThreadStateRenderer renderer = new BuildThreadStateRenderer(
ansi,
formatTimeFunction,
currentTimeMillis,
threadsToRunningStep,
accumulatedTimeTracker);
renderLines(renderer, lines, maxThreadLines, shouldAlwaysSortThreadsByTime);
}
long testRunTime = logEventPair(
"TESTING",
renderTestSuffix(),
currentTimeMillis,
0, /* offsetMs */
testRunStarted.get(),
testRunFinished.get(),
Optional.empty(),
lines);
if (testRunTime == UNFINISHED_EVENT_PAIR) {
ThreadStateRenderer renderer = new TestThreadStateRenderer(
ansi,
formatTimeFunction,
currentTimeMillis,
threadsToRunningTestSummaryEvent,
threadsToRunningTestStatusMessageEvent,
threadsToRunningStep,
accumulatedTimeTracker);
renderLines(renderer, lines, maxThreadLines, shouldAlwaysSortThreadsByTime);
}
logEventPair("INSTALLING",
/* suffix */ Optional.empty(),
currentTimeMillis,
0L,
installStarted,
installFinished,
Optional.empty(),
lines);
logHttpCacheUploads(lines);
}
return lines.build();
}
private String getNetworkStatsLine(
@Nullable BuildEvent.Finished finishedEvent) {
String parseLine = (finishedEvent != null ? "[-] " : "[+] ") + "DOWNLOADING" + "...";
List<String> columns = Lists.newArrayList();
if (finishedEvent != null) {
Pair<Double, SizeUnit> avgDownloadSpeed =
networkStatsKeeper.getAverageDownloadSpeed();
Pair<Double, SizeUnit> readableSpeed =
SizeUnit.getHumanReadableSize(
avgDownloadSpeed.getFirst(),
avgDownloadSpeed.getSecond());
columns.add(
String.format(
locale,
"%s/S " + "AVG",
SizeUnit.toHumanReadableString(readableSpeed, locale)
)
);
} else {
Pair<Double, SizeUnit> downloadSpeed = networkStatsKeeper.getDownloadSpeed();
Pair<Double, SizeUnit> readableDownloadSpeed =
SizeUnit.getHumanReadableSize(downloadSpeed.getFirst(), downloadSpeed.getSecond());
columns.add(
String.format(
locale,
"%s/S",
SizeUnit.toHumanReadableString(readableDownloadSpeed, locale)
)
);
}
Pair<Long, SizeUnit> bytesDownloaded = networkStatsKeeper.getBytesDownloaded();
Pair<Double, SizeUnit> readableBytesDownloaded =
SizeUnit.getHumanReadableSize(
bytesDownloaded.getFirst(),
bytesDownloaded.getSecond());
columns.add(
String.format(
locale,
"TOTAL: %s",
SizeUnit.toHumanReadableString(readableBytesDownloaded, locale)
)
);
columns.add(
String.format(
locale,
"%d Artifacts",
networkStatsKeeper.getDownloadedArtifactDownloaded()));
return parseLine + " " + "(" + Joiner.on(", ").join(columns) + ")";
}
private String getDistBuildStatusLine() {
// create a local reference to avoid inconsistencies
Optional<DistBuildStatus> distBuildStatus = this.distBuildStatus;
boolean finished = distBuildStatus.isPresent() &&
(distBuildStatus.get().getStatus() == BuildStatus.FINISHED_SUCCESSFULLY ||
distBuildStatus.get().getStatus() == BuildStatus.FAILED);
String parseLine = finished ? "[-] " : "[+] ";
parseLine += "DISTBUILD STATUS: ";
if (!distBuildStatus.isPresent()) {
parseLine += "INIT...";
return parseLine;
}
parseLine += distBuildStatus.get().getStatus().toString() + "...";
if (!finished) {
parseLine += " ETA: " + formatElapsedTime(distBuildStatus.get().getETAMillis());
}
if (distBuildStatus.get().getMessage().isPresent()) {
parseLine += " (" + distBuildStatus.get().getMessage().get() + ")";
}
return parseLine;
}
private void getDistBuildDebugInfo(ImmutableList.Builder<String> lines) {
// create a local reference to avoid inconsistencies
Optional<DistBuildStatus> distBuildStatus = this.distBuildStatus;
if (distBuildStatus.isPresent() && distBuildStatus.get().getLogBook().isPresent()) {
lines.add(ansi.asWarningText("Distributed build debug info:"));
for (LogRecord log : distBuildStatus.get().getLogBook().get()) {
String dateString = dateFormat.format(new Date(log.getTimestampMillis()));
lines.add(ansi.asWarningText(dateString + " " + log.getName()));
}
anyWarningsPrinted.set(true);
}
}
/**
* Adds log messages for rendering.
*/
@VisibleForTesting
ImmutableList<String> createLogRenderLines() {
ImmutableList.Builder<String> logEventLinesBuilder = ImmutableList.builder();
ConsoleEvent logEvent;
while ((logEvent = logEvents.poll()) != null) {
formatConsoleEvent(logEvent, logEventLinesBuilder);
if (logEvent.getLevel().equals(Level.WARNING)) {
anyWarningsPrinted.set(true);
} else if (logEvent.getLevel().equals(Level.SEVERE)) {
anyErrorsPrinted.set(true);
}
}
return logEventLinesBuilder.build();
}
public void renderLines(
ThreadStateRenderer renderer,
ImmutableList.Builder<String> lines,
int maxLines,
boolean alwaysSortByTime) {
int threadCount = renderer.getThreadCount();
int fullLines = threadCount;
boolean useCompressedLine = false;
if (threadCount > maxLines) {
// One line will be used for the remaining threads that don't get their own line.
fullLines = maxLines - 1;
useCompressedLine = true;
}
int threadsWithShortStatus = threadCount - fullLines;
boolean sortByTime = alwaysSortByTime || useCompressedLine;
ImmutableList<Long> threadIds = renderer.getSortedThreadIds(sortByTime);
StringBuilder lineBuilder = new StringBuilder(EXPECTED_MAXIMUM_RENDERED_LINE_LENGTH);
for (int i = 0; i < fullLines; ++i) {
long threadId = threadIds.get(i);
lines.add(renderer.renderStatusLine(threadId, lineBuilder));
}
if (useCompressedLine) {
lineBuilder.delete(0, lineBuilder.length());
lineBuilder.append(" |=> ");
lineBuilder.append(threadsWithShortStatus);
if (fullLines == 0) {
lineBuilder.append(" THREADS:");
} else {
lineBuilder.append(" MORE THREADS:");
}
for (int i = fullLines; i < threadIds.size(); ++i) {
long threadId = threadIds.get(i);
lineBuilder.append(" ");
lineBuilder.append(renderer.renderShortStatus(threadId));
}
lines.add(lineBuilder.toString());
}
}
private Optional<String> renderTestSuffix() {
int testPassesVal = testPasses.get();
int testFailuresVal = testFailures.get();
int testSkipsVal = testSkips.get();
if (testSkipsVal > 0) {
return Optional.of(
String.format(
locale,
"(%d PASS/%d SKIP/%d FAIL)",
testPassesVal,
testSkipsVal,
testFailuresVal));
} else if (testPassesVal > 0 || testFailuresVal > 0) {
return Optional.of(
String.format(
locale,
"(%d PASS/%d FAIL)",
testPassesVal,
testFailuresVal));
} else {
return Optional.empty();
}
}
/**
* @return A string of ansi characters that will clear the last set of lines printed by
* {@link SuperConsoleEventBusListener#createRenderLinesAtTime(long)}.
*/
private String clearLastRender() {
StringBuilder result = new StringBuilder();
for (int i = 0; i < lastNumLinesPrinted; ++i) {
result.append(ansi.cursorPreviousLine(1));
result.append(ansi.clearLine());
}
return result.toString();
}
@Override
@Subscribe
public void buildRuleStarted(BuildRuleEvent.Started started) {
super.buildRuleStarted(started);
}
@Override
@Subscribe
public void buildRuleSuspended(BuildRuleEvent.Suspended suspended) {
super.buildRuleSuspended(suspended);
}
@Override
@Subscribe
public void buildRuleResumed(BuildRuleEvent.Resumed resumed) {
super.buildRuleResumed(resumed);
}
@Subscribe
public void stepStarted(StepEvent.Started started) {
threadsToRunningStep.put(started.getThreadId(), Optional.of(started));
}
@Subscribe
public void stepFinished(StepEvent.Finished finished) {
threadsToRunningStep.put(finished.getThreadId(), Optional.empty());
}
@Subscribe
public void artifactCacheStarted(ArtifactCacheEvent.Started started) {
if (started.getInvocationType() == ArtifactCacheEvent.InvocationType.SYNCHRONOUS) {
threadsToRunningStep.put(started.getThreadId(), Optional.of(started));
}
}
@Subscribe
public void artifactCacheFinished(ArtifactCacheEvent.Finished finished) {
if (finished.getInvocationType() == ArtifactCacheEvent.InvocationType.SYNCHRONOUS) {
threadsToRunningStep.put(finished.getThreadId(), Optional.empty());
}
}
@Subscribe
public void cacheCheckStarted(BuildRuleCacheEvent.CacheStepStarted started) {
threadsToRunningStep.put(started.getThreadId(), Optional.of(started));
}
@Subscribe
public void cacheCheckFinished(BuildRuleCacheEvent.CacheStepFinished finished) {
threadsToRunningStep.put(finished.getThreadId(), Optional.empty());
}
@Subscribe
public void artifactCompressionStarted(ArtifactCompressionEvent.Started started) {
threadsToRunningStep.put(started.getThreadId(), Optional.of(started));
}
@Subscribe
public void artifactCompressionFinished(ArtifactCompressionEvent.Finished finished) {
threadsToRunningStep.put(finished.getThreadId(), Optional.empty());
}
@Override
@Subscribe
public void distributedBuildStatus(DistBuildStatusEvent event) {
super.distributedBuildStatus(event);
distBuildStatus = Optional.of(event.getStatus());
}
@Subscribe
public void testRunStarted(TestRunEvent.Started event) {
boolean set = testRunStarted.compareAndSet(null, event);
Preconditions.checkState(set, "Test run should not start while test run in progress");
ImmutableList.Builder<String> builder = ImmutableList.builder();
testFormatter.runStarted(builder,
event.isRunAllTests(),
event.getTestSelectorList(),
event.shouldExplainTestSelectorList(),
event.getTargetNames(),
TestResultFormatter.FormatMode.AFTER_TEST_RUN);
synchronized (testReportBuilder) {
testReportBuilder.addAll(builder.build());
}
}
@Subscribe
public void testRunFinished(TestRunEvent.Finished finished) {
boolean set = testRunFinished.compareAndSet(null, finished);
Preconditions.checkState(set, "Test run should not finish after test run already finished");
ImmutableList.Builder<String> builder = ImmutableList.builder();
for (TestResults results : finished.getResults()) {
testFormatter.reportResult(builder, results);
}
ImmutableList<TestStatusMessage> testStatusMessages;
synchronized (testStatusMessageBuilder) {
testStatusMessages = testStatusMessageBuilder.build();
}
testFormatter.runComplete(builder, finished.getResults(), testStatusMessages);
String testOutput;
synchronized (testReportBuilder) {
testReportBuilder.addAll(builder.build());
testOutput = Joiner.on('\n').join(testReportBuilder.build());
}
// We're about to write to stdout, so make sure we render the final frame before we do.
render();
synchronized (console.getStdOut()) {
console.getStdOut().println(testOutput);
}
}
@Subscribe
public void testStatusMessageStarted(TestStatusMessageEvent.Started started) {
threadsToRunningTestStatusMessageEvent.put(started.getThreadId(), Optional.of(started));
synchronized (testStatusMessageBuilder) {
testStatusMessageBuilder.add(started.getTestStatusMessage());
}
}
@Subscribe
public void testStatusMessageFinished(TestStatusMessageEvent.Finished finished) {
threadsToRunningTestStatusMessageEvent.put(
finished.getThreadId(),
Optional.empty());
synchronized (testStatusMessageBuilder) {
testStatusMessageBuilder.add(finished.getTestStatusMessage());
}
}
@Subscribe
public void testSummaryStarted(TestSummaryEvent.Started started) {
threadsToRunningTestSummaryEvent.put(started.getThreadId(), Optional.of(started));
}
@Subscribe
public void testSummaryFinished(TestSummaryEvent.Finished finished) {
threadsToRunningTestSummaryEvent.put(
finished.getThreadId(),
Optional.empty());
TestResultSummary testResult = finished.getTestResultSummary();
ResultType resultType = testResult.getType();
switch (resultType) {
case SUCCESS:
testPasses.incrementAndGet();
break;
case FAILURE:
testFailures.incrementAndGet();
// We don't use TestResultFormatter.reportResultSummary() here since that also
// includes the stack trace and stdout/stderr.
logEvents.add(
ConsoleEvent.severe(
String.format(
locale,
"%s %s %s: %s",
testResult.getType().toString(),
testResult.getTestCaseName(),
testResult.getTestName(),
testResult.getMessage())));
break;
case ASSUMPTION_VIOLATION:
testSkips.incrementAndGet();
break;
case DISABLED:
break;
case DRY_RUN:
break;
case EXCLUDED:
break;
}
}
@Subscribe
public void logEvent(ConsoleEvent event) {
logEvents.add(event);
}
@Override
public void printSevereWarningDirectly(String line) {
logEvents.add(ConsoleEvent.severe(line));
}
@Subscribe
public void bytesReceived(NetworkEvent.BytesReceivedEvent bytesReceivedEvent) {
networkStatsKeeper.bytesReceived(bytesReceivedEvent);
}
@Subscribe
@SuppressWarnings("unused")
public void actionGraphCacheHit(ActionGraphEvent.Cache.Hit event) {
parsingStatus = createParsingMessage(EMOJI_BUNNY, "");
}
@Subscribe
public void watchmanOverflow(WatchmanStatusEvent.Overflow event) {
parsingStatus = createParsingMessage(EMOJI_SNAIL, event.getReason());
}
@Subscribe
@SuppressWarnings("unused")
public void watchmanFileCreation(WatchmanStatusEvent.FileCreation event) {
parsingStatus = createParsingMessage(EMOJI_SNAIL, "File added");
}
@Subscribe
@SuppressWarnings("unused")
public void watchmanFileDeletion(WatchmanStatusEvent.FileDeletion event) {
parsingStatus = createParsingMessage(EMOJI_SNAIL, "File removed");
}
@Subscribe
@SuppressWarnings("unused")
public void daemonNewInstance(DaemonEvent.NewDaemonInstance event) {
parsingStatus = NEW_DAEMON_INSTANCE_MSG;
}
@Subscribe
@SuppressWarnings("unused")
public void symlinkInvalidation(ParsingEvent.SymlinkInvalidation event) {
parsingStatus = createParsingMessage(EMOJI_WHALE, "Symlink caused cache invalidation");
}
@Subscribe
public void envVariableChange(ParsingEvent.EnvVariableChange event) {
parsingStatus = createParsingMessage(EMOJI_SNAIL, "Environment variable changes: " +
event.getDiff());
}
@VisibleForTesting
static Optional<String> createParsingMessage(String emoji, String reason) {
if (Charset.defaultCharset().equals(Charsets.UTF_8)) {
return Optional.of(emoji + " " + reason);
} else {
if (emoji.equals(EMOJI_BUNNY)) {
return Optional.of("(FAST)");
} else {
return Optional.of("(SLOW) " + reason);
}
}
}
@VisibleForTesting
Optional<String> getParsingStatus() {
return parsingStatus;
}
@Override
public synchronized void close() throws IOException {
stopRenderScheduler();
networkStatsKeeper.stopScheduler();
render(); // Ensure final frame is rendered.
}
}
| src/com/facebook/buck/event/listener/SuperConsoleEventBusListener.java | /*
* Copyright 2013-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.event.listener;
import com.facebook.buck.artifact_cache.ArtifactCacheEvent;
import com.facebook.buck.distributed.DistBuildStatus;
import com.facebook.buck.distributed.DistBuildStatusEvent;
import com.facebook.buck.distributed.thrift.BuildStatus;
import com.facebook.buck.distributed.thrift.LogRecord;
import com.facebook.buck.event.ActionGraphEvent;
import com.facebook.buck.event.ArtifactCompressionEvent;
import com.facebook.buck.event.ConsoleEvent;
import com.facebook.buck.event.DaemonEvent;
import com.facebook.buck.event.LeafEvent;
import com.facebook.buck.event.NetworkEvent;
import com.facebook.buck.event.ParsingEvent;
import com.facebook.buck.event.WatchmanStatusEvent;
import com.facebook.buck.httpserver.WebServer;
import com.facebook.buck.log.Logger;
import com.facebook.buck.model.Pair;
import com.facebook.buck.rules.BuildEvent;
import com.facebook.buck.rules.BuildRuleCacheEvent;
import com.facebook.buck.rules.BuildRuleEvent;
import com.facebook.buck.rules.TestRunEvent;
import com.facebook.buck.rules.TestStatusMessageEvent;
import com.facebook.buck.rules.TestSummaryEvent;
import com.facebook.buck.step.StepEvent;
import com.facebook.buck.test.TestResultSummary;
import com.facebook.buck.test.TestResultSummaryVerbosity;
import com.facebook.buck.test.TestResults;
import com.facebook.buck.test.TestStatusMessage;
import com.facebook.buck.test.result.type.ResultType;
import com.facebook.buck.timing.Clock;
import com.facebook.buck.util.Console;
import com.facebook.buck.util.MoreIterables;
import com.facebook.buck.util.environment.ExecutionEnvironment;
import com.facebook.buck.util.unit.SizeUnit;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.eventbus.Subscribe;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import javax.annotation.Nullable;
/**
* Console that provides rich, updating ansi output about the current build.
*/
public class SuperConsoleEventBusListener extends AbstractConsoleEventBusListener {
/**
* Maximum expected rendered line length so we can start with a decent
* size of line rendering buffer.
*/
private static final int EXPECTED_MAXIMUM_RENDERED_LINE_LENGTH = 128;
private static final Logger LOG = Logger.get(SuperConsoleEventBusListener.class);
@VisibleForTesting
static final String EMOJI_BUNNY = "\uD83D\uDC07";
@VisibleForTesting
static final String EMOJI_SNAIL = "\uD83D\uDC0C";
@VisibleForTesting
static final String EMOJI_WHALE = "\uD83D\uDC33";
@VisibleForTesting
static final Optional<String> NEW_DAEMON_INSTANCE_MSG =
createParsingMessage(EMOJI_WHALE, "New buck daemon");
private final Locale locale;
private final Function<Long, String> formatTimeFunction;
private final Optional<WebServer> webServer;
private final ConcurrentMap<Long, Optional<? extends TestSummaryEvent>>
threadsToRunningTestSummaryEvent;
private final ConcurrentMap<Long, Optional<? extends TestStatusMessageEvent>>
threadsToRunningTestStatusMessageEvent;
private final ConcurrentMap<Long, Optional<? extends LeafEvent>> threadsToRunningStep;
private final ConcurrentLinkedQueue<ConsoleEvent> logEvents;
private final ScheduledExecutorService renderScheduler;
private final TestResultFormatter testFormatter;
private final AtomicInteger testPasses = new AtomicInteger(0);
private final AtomicInteger testFailures = new AtomicInteger(0);
private final AtomicInteger testSkips = new AtomicInteger(0);
private final AtomicReference<TestRunEvent.Started> testRunStarted;
private final AtomicReference<TestRunEvent.Finished> testRunFinished;
private final ImmutableList.Builder<String> testReportBuilder = ImmutableList.builder();
private final ImmutableList.Builder<TestStatusMessage> testStatusMessageBuilder =
ImmutableList.builder();
private final AtomicBoolean anyWarningsPrinted = new AtomicBoolean(false);
private final AtomicBoolean anyErrorsPrinted = new AtomicBoolean(false);
private final int defaultThreadLineLimit;
private final int threadLineLimitOnWarning;
private final int threadLineLimitOnError;
private final boolean shouldAlwaysSortThreadsByTime;
private Optional<DistBuildStatus> distBuildStatus;
private final DateFormat dateFormat;
private int lastNumLinesPrinted;
protected Optional<String> parsingStatus = Optional.empty();
public SuperConsoleEventBusListener(
SuperConsoleConfig config,
Console console,
Clock clock,
TestResultSummaryVerbosity summaryVerbosity,
ExecutionEnvironment executionEnvironment,
Optional<WebServer> webServer,
Locale locale,
Path testLogPath,
TimeZone timeZone) {
super(console, clock, locale, executionEnvironment);
this.locale = locale;
this.formatTimeFunction = this::formatElapsedTime;
this.webServer = webServer;
this.threadsToRunningTestSummaryEvent = new ConcurrentHashMap<>(
executionEnvironment.getAvailableCores());
this.threadsToRunningTestStatusMessageEvent = new ConcurrentHashMap<>(
executionEnvironment.getAvailableCores());
this.threadsToRunningStep = new ConcurrentHashMap<>(executionEnvironment.getAvailableCores());
this.logEvents = new ConcurrentLinkedQueue<>();
this.renderScheduler = Executors.newScheduledThreadPool(1,
new ThreadFactoryBuilder().setNameFormat(getClass().getSimpleName() + "-%d").build());
this.testFormatter = new TestResultFormatter(
console.getAnsi(),
console.getVerbosity(),
summaryVerbosity,
locale,
Optional.of(testLogPath));
this.testRunStarted = new AtomicReference<>();
this.testRunFinished = new AtomicReference<>();
this.defaultThreadLineLimit = config.getThreadLineLimit();
this.threadLineLimitOnWarning = config.getThreadLineLimitOnWarning();
this.threadLineLimitOnError = config.getThreadLineLimitOnError();
this.shouldAlwaysSortThreadsByTime = config.shouldAlwaysSortThreadsByTime();
this.distBuildStatus = Optional.empty();
this.dateFormat = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss.SSS]", this.locale);
this.dateFormat.setTimeZone(timeZone);
}
/**
* Schedules a runnable that updates the console output at a fixed interval.
*/
public void startRenderScheduler(long renderInterval, TimeUnit timeUnit) {
LOG.debug("Starting render scheduler (interval %d ms)", timeUnit.toMillis(renderInterval));
renderScheduler.scheduleAtFixedRate(() -> {
try {
SuperConsoleEventBusListener.this.render();
} catch (Error | RuntimeException e) {
LOG.error(e, "Rendering exception");
throw e;
}
}, /* initialDelay */ renderInterval, /* period */ renderInterval, timeUnit);
}
/**
* Shuts down the thread pool and cancels the fixed interval runnable.
*/
private synchronized void stopRenderScheduler() {
LOG.debug("Stopping render scheduler");
renderScheduler.shutdownNow();
}
@VisibleForTesting
synchronized void render() {
LOG.verbose("Rendering");
String lastRenderClear = clearLastRender();
ImmutableList<String> lines = createRenderLinesAtTime(clock.currentTimeMillis());
ImmutableList<String> logLines = createLogRenderLines();
lastNumLinesPrinted = lines.size();
// Synchronize on the DirtyPrintStreamDecorator to prevent interlacing of output.
// We don't log immediately so we avoid locking the console handler to avoid deadlocks.
boolean stdoutDirty;
boolean stderrDirty;
synchronized (console.getStdOut()) {
synchronized (console.getStdErr()) {
// If another source has written to stderr or stdout, stop rendering with the SuperConsole.
// We need to do this to keep our updates consistent.
stdoutDirty = console.getStdOut().isDirty();
stderrDirty = console.getStdErr().isDirty();
if (stdoutDirty || stderrDirty) {
stopRenderScheduler();
} else if (!lastRenderClear.isEmpty() || !lines.isEmpty() || !logLines.isEmpty()) {
Iterable<String> renderedLines = Iterables.concat(
MoreIterables.zipAndConcat(
logLines,
Iterables.cycle("\n")),
ansi.asNoWrap(
MoreIterables.zipAndConcat(
lines,
Iterables.cycle("\n"))));
StringBuilder fullFrame = new StringBuilder(lastRenderClear);
for (String part : renderedLines) {
fullFrame.append(part);
}
console.getStdErr().getRawStream().print(fullFrame);
}
}
}
if (stdoutDirty || stderrDirty) {
LOG.debug(
"Stopping console output (stdout dirty %s, stderr dirty %s).",
stdoutDirty, stderrDirty);
}
}
/**
* Creates a list of lines to be rendered at a given time.
* @param currentTimeMillis The time in ms to use when computing elapsed times.
*/
@VisibleForTesting
ImmutableList<String> createRenderLinesAtTime(long currentTimeMillis) {
ImmutableList.Builder<String> lines = ImmutableList.builder();
// Print latest distributed build debug info lines
if (buildStarted != null && buildStarted.isDistributedBuild()) {
getDistBuildDebugInfo(lines);
}
// If we have not yet started processing the BUCK files, show parse times
if (parseStarted.isEmpty() && parseFinished.isEmpty()) {
logEventPair(
"PARSING BUCK FILES",
/* suffix */ Optional.empty(),
currentTimeMillis,
/* offsetMs */ 0L,
projectBuildFileParseStarted,
projectBuildFileParseFinished,
getEstimatedProgressOfProcessingBuckFiles(),
lines);
}
long parseTime = logEventPair("PROCESSING BUCK FILES",
/* suffix */ parsingStatus,
currentTimeMillis,
/* offsetMs */ 0L,
buckFilesProcessing.values(),
getEstimatedProgressOfProcessingBuckFiles(),
lines);
logEventPair(
"GENERATING PROJECT",
Optional.empty(),
currentTimeMillis,
/* offsetMs */ 0L,
projectGenerationStarted,
projectGenerationFinished,
getEstimatedProgressOfGeneratingProjectFiles(),
lines);
// If parsing has not finished, then there is no build rule information to print yet.
if (parseTime != UNFINISHED_EVENT_PAIR) {
lines.add(getNetworkStatsLine(buildFinished));
if (buildStarted != null && buildStarted.isDistributedBuild()) {
lines.add(getDistBuildStatusLine());
}
// Log build time, excluding time spent in parsing.
String jobSummary = null;
if (ruleCount.isPresent()) {
List<String> columns = Lists.newArrayList();
columns.add(String.format(locale, "%d/%d JOBS", numRulesCompleted.get(), ruleCount.get()));
CacheRateStatsKeeper.CacheRateStatsUpdateEvent cacheRateStats =
cacheRateStatsKeeper.getStats();
columns.add(String.format(
locale,
"%d UPDATED",
cacheRateStats.getUpdatedRulesCount()));
if (ruleCount.orElse(0) > 0) {
columns.add(
String.format(
locale,
"%d [%.1f%%] CACHE MISS",
cacheRateStats.getCacheMissCount(),
cacheRateStats.getCacheMissRate()));
if (cacheRateStats.getCacheErrorCount() > 0) {
columns.add(
String.format(
locale,
"%d [%.1f%%] CACHE ERRORS",
cacheRateStats.getCacheErrorCount(),
cacheRateStats.getCacheErrorRate()));
}
}
jobSummary = "(" + Joiner.on(", ").join(columns) + ")";
}
// If the Daemon is running and serving web traffic, print the URL to the Chrome Trace.
String buildTrace = null;
if (buildFinished != null && webServer.isPresent()) {
Optional<Integer> port = webServer.get().getPort();
if (port.isPresent()) {
buildTrace = String.format(
locale,
"Details: http://localhost:%s/trace/%s",
port.get(),
buildFinished.getBuildId());
}
}
if (buildStarted == null) {
// All steps past this point require a build.
return lines.build();
}
String suffix = Joiner.on(" ")
.join(FluentIterable.of(new String[] {jobSummary, buildTrace})
.filter(Objects::nonNull));
Optional<String> suffixOptional =
suffix.isEmpty() ? Optional.empty() : Optional.of(suffix);
// Check to see if the build encompasses the time spent parsing. This is true for runs of
// buck build but not so for runs of e.g. buck project. If so, subtract parse times
// from the build time.
long buildStartedTime = buildStarted.getTimestamp();
long buildFinishedTime = buildFinished != null
? buildFinished.getTimestamp()
: currentTimeMillis;
Collection<EventPair> processingEvents = getEventsBetween(buildStartedTime,
buildFinishedTime,
buckFilesProcessing.values());
long offsetMs = getTotalCompletedTimeFromEventPairs(processingEvents);
long buildTime = logEventPair(
"BUILDING",
suffixOptional,
currentTimeMillis,
offsetMs, // parseTime,
this.buildStarted,
this.buildFinished,
getApproximateBuildProgress(),
lines);
int maxThreadLines = defaultThreadLineLimit;
if (anyWarningsPrinted.get() && threadLineLimitOnWarning < maxThreadLines) {
maxThreadLines = threadLineLimitOnWarning;
}
if (anyErrorsPrinted.get() && threadLineLimitOnError < maxThreadLines) {
maxThreadLines = threadLineLimitOnError;
}
if (buildTime == UNFINISHED_EVENT_PAIR) {
ThreadStateRenderer renderer = new BuildThreadStateRenderer(
ansi,
formatTimeFunction,
currentTimeMillis,
threadsToRunningStep,
accumulatedTimeTracker);
renderLines(renderer, lines, maxThreadLines, shouldAlwaysSortThreadsByTime);
}
long testRunTime = logEventPair(
"TESTING",
renderTestSuffix(),
currentTimeMillis,
0, /* offsetMs */
testRunStarted.get(),
testRunFinished.get(),
Optional.empty(),
lines);
if (testRunTime == UNFINISHED_EVENT_PAIR) {
ThreadStateRenderer renderer = new TestThreadStateRenderer(
ansi,
formatTimeFunction,
currentTimeMillis,
threadsToRunningTestSummaryEvent,
threadsToRunningTestStatusMessageEvent,
threadsToRunningStep,
accumulatedTimeTracker);
renderLines(renderer, lines, maxThreadLines, shouldAlwaysSortThreadsByTime);
}
logEventPair("INSTALLING",
/* suffix */ Optional.empty(),
currentTimeMillis,
0L,
installStarted,
installFinished,
Optional.empty(),
lines);
logHttpCacheUploads(lines);
}
return lines.build();
}
private String getNetworkStatsLine(
@Nullable BuildEvent.Finished finishedEvent) {
String parseLine = (finishedEvent != null ? "[-] " : "[+] ") + "DOWNLOADING" + "...";
List<String> columns = Lists.newArrayList();
if (finishedEvent != null) {
Pair<Double, SizeUnit> avgDownloadSpeed =
networkStatsKeeper.getAverageDownloadSpeed();
Pair<Double, SizeUnit> readableSpeed =
SizeUnit.getHumanReadableSize(
avgDownloadSpeed.getFirst(),
avgDownloadSpeed.getSecond());
columns.add(
String.format(
locale,
"%s/S " + "AVG",
SizeUnit.toHumanReadableString(readableSpeed, locale)
)
);
} else {
Pair<Double, SizeUnit> downloadSpeed = networkStatsKeeper.getDownloadSpeed();
Pair<Double, SizeUnit> readableDownloadSpeed =
SizeUnit.getHumanReadableSize(downloadSpeed.getFirst(), downloadSpeed.getSecond());
columns.add(
String.format(
locale,
"%s/S",
SizeUnit.toHumanReadableString(readableDownloadSpeed, locale)
)
);
}
Pair<Long, SizeUnit> bytesDownloaded = networkStatsKeeper.getBytesDownloaded();
Pair<Double, SizeUnit> readableBytesDownloaded =
SizeUnit.getHumanReadableSize(
bytesDownloaded.getFirst(),
bytesDownloaded.getSecond());
columns.add(
String.format(
locale,
"TOTAL: %s",
SizeUnit.toHumanReadableString(readableBytesDownloaded, locale)
)
);
columns.add(
String.format(
locale,
"%d Artifacts",
networkStatsKeeper.getDownloadedArtifactDownloaded()));
return parseLine + " " + "(" + Joiner.on(", ").join(columns) + ")";
}
private String getDistBuildStatusLine() {
// create a local reference to avoid inconsistencies
Optional<DistBuildStatus> distBuildStatus = this.distBuildStatus;
boolean finished = distBuildStatus.isPresent() &&
(distBuildStatus.get().getStatus() == BuildStatus.FINISHED_SUCCESSFULLY ||
distBuildStatus.get().getStatus() == BuildStatus.FAILED);
String parseLine = finished ? "[-] " : "[+] ";
parseLine += "DISTBUILD STATUS: ";
if (!distBuildStatus.isPresent()) {
parseLine += "INIT...";
return parseLine;
}
parseLine += distBuildStatus.get().getStatus().toString() + "...";
if (!finished) {
parseLine += " ETA: " + formatElapsedTime(distBuildStatus.get().getETAMillis());
}
if (distBuildStatus.get().getMessage().isPresent()) {
parseLine += " (" + distBuildStatus.get().getMessage().get() + ")";
}
return parseLine;
}
private void getDistBuildDebugInfo(ImmutableList.Builder<String> lines) {
// create a local reference to avoid inconsistencies
Optional<DistBuildStatus> distBuildStatus = this.distBuildStatus;
if (distBuildStatus.isPresent() && distBuildStatus.get().getLogBook().isPresent()) {
lines.add(ansi.asWarningText("Distributed build debug info:"));
for (LogRecord log : distBuildStatus.get().getLogBook().get()) {
String dateString = dateFormat.format(new Date(log.getTimestampMillis()));
lines.add(ansi.asWarningText(dateString + " " + log.getName()));
}
anyWarningsPrinted.set(true);
}
}
/**
* Adds log messages for rendering.
*/
@VisibleForTesting
ImmutableList<String> createLogRenderLines() {
ImmutableList.Builder<String> logEventLinesBuilder = ImmutableList.builder();
ConsoleEvent logEvent;
while ((logEvent = logEvents.poll()) != null) {
formatConsoleEvent(logEvent, logEventLinesBuilder);
if (logEvent.getLevel().equals(Level.WARNING)) {
anyWarningsPrinted.set(true);
} else if (logEvent.getLevel().equals(Level.SEVERE)) {
anyErrorsPrinted.set(true);
}
}
return logEventLinesBuilder.build();
}
public void renderLines(
ThreadStateRenderer renderer,
ImmutableList.Builder<String> lines,
int maxLines,
boolean alwaysSortByTime) {
int threadCount = renderer.getThreadCount();
int fullLines = threadCount;
boolean useCompressedLine = false;
if (threadCount > maxLines) {
// One line will be used for the remaining threads that don't get their own line.
fullLines = maxLines - 1;
useCompressedLine = true;
}
int threadsWithShortStatus = threadCount - fullLines;
boolean sortByTime = alwaysSortByTime || useCompressedLine;
ImmutableList<Long> threadIds = renderer.getSortedThreadIds(sortByTime);
StringBuilder lineBuilder = new StringBuilder(EXPECTED_MAXIMUM_RENDERED_LINE_LENGTH);
for (int i = 0; i < fullLines; ++i) {
long threadId = threadIds.get(i);
lines.add(renderer.renderStatusLine(threadId, lineBuilder));
}
if (useCompressedLine) {
lineBuilder.delete(0, lineBuilder.length());
lineBuilder.append(" |=> ");
lineBuilder.append(threadsWithShortStatus);
if (fullLines == 0) {
lineBuilder.append(" THREADS:");
} else {
lineBuilder.append(" MORE THREADS:");
}
for (int i = fullLines; i < threadIds.size(); ++i) {
long threadId = threadIds.get(i);
lineBuilder.append(" ");
lineBuilder.append(renderer.renderShortStatus(threadId));
}
lines.add(lineBuilder.toString());
}
}
private Optional<String> renderTestSuffix() {
int testPassesVal = testPasses.get();
int testFailuresVal = testFailures.get();
int testSkipsVal = testSkips.get();
if (testSkipsVal > 0) {
return Optional.of(
String.format(
locale,
"(%d PASS/%d SKIP/%d FAIL)",
testPassesVal,
testSkipsVal,
testFailuresVal));
} else if (testPassesVal > 0 || testFailuresVal > 0) {
return Optional.of(
String.format(
locale,
"(%d PASS/%d FAIL)",
testPassesVal,
testFailuresVal));
} else {
return Optional.empty();
}
}
/**
* @return A string of ansi characters that will clear the last set of lines printed by
* {@link SuperConsoleEventBusListener#createRenderLinesAtTime(long)}.
*/
private String clearLastRender() {
StringBuilder result = new StringBuilder();
for (int i = 0; i < lastNumLinesPrinted; ++i) {
result.append(ansi.cursorPreviousLine(1));
result.append(ansi.clearLine());
}
return result.toString();
}
@Override
@Subscribe
public void buildRuleStarted(BuildRuleEvent.Started started) {
super.buildRuleStarted(started);
}
@Override
@Subscribe
public void buildRuleSuspended(BuildRuleEvent.Suspended suspended) {
super.buildRuleSuspended(suspended);
}
@Override
@Subscribe
public void buildRuleResumed(BuildRuleEvent.Resumed resumed) {
super.buildRuleResumed(resumed);
}
@Subscribe
public void stepStarted(StepEvent.Started started) {
threadsToRunningStep.put(started.getThreadId(), Optional.of(started));
}
@Subscribe
public void stepFinished(StepEvent.Finished finished) {
threadsToRunningStep.put(finished.getThreadId(), Optional.empty());
}
@Subscribe
public void artifactCacheStarted(ArtifactCacheEvent.Started started) {
if (started.getInvocationType() == ArtifactCacheEvent.InvocationType.SYNCHRONOUS) {
threadsToRunningStep.put(started.getThreadId(), Optional.of(started));
}
}
@Subscribe
public void artifactCacheFinished(ArtifactCacheEvent.Finished finished) {
if (finished.getInvocationType() == ArtifactCacheEvent.InvocationType.SYNCHRONOUS) {
threadsToRunningStep.put(finished.getThreadId(), Optional.empty());
}
}
@Subscribe
public void cacheCheckStarted(BuildRuleCacheEvent.CacheStepStarted started) {
threadsToRunningStep.put(started.getThreadId(), Optional.of(started));
}
@Subscribe
public void cacheCheckFinished(BuildRuleCacheEvent.CacheStepFinished finished) {
threadsToRunningStep.put(finished.getThreadId(), Optional.empty());
}
@Subscribe
public void artifactCompressionStarted(ArtifactCompressionEvent.Started started) {
threadsToRunningStep.put(started.getThreadId(), Optional.of(started));
}
@Subscribe
public void artifactCompressionFinished(ArtifactCompressionEvent.Finished finished) {
threadsToRunningStep.put(finished.getThreadId(), Optional.empty());
}
@Override
@Subscribe
public void distributedBuildStatus(DistBuildStatusEvent event) {
super.distributedBuildStatus(event);
distBuildStatus = Optional.of(event.getStatus());
}
@Subscribe
public void testRunStarted(TestRunEvent.Started event) {
boolean set = testRunStarted.compareAndSet(null, event);
Preconditions.checkState(set, "Test run should not start while test run in progress");
ImmutableList.Builder<String> builder = ImmutableList.builder();
testFormatter.runStarted(builder,
event.isRunAllTests(),
event.getTestSelectorList(),
event.shouldExplainTestSelectorList(),
event.getTargetNames(),
TestResultFormatter.FormatMode.AFTER_TEST_RUN);
synchronized (testReportBuilder) {
testReportBuilder.addAll(builder.build());
}
}
@Subscribe
public void testRunFinished(TestRunEvent.Finished finished) {
boolean set = testRunFinished.compareAndSet(null, finished);
Preconditions.checkState(set, "Test run should not finish after test run already finished");
ImmutableList.Builder<String> builder = ImmutableList.builder();
for (TestResults results : finished.getResults()) {
testFormatter.reportResult(builder, results);
}
ImmutableList<TestStatusMessage> testStatusMessages;
synchronized (testStatusMessageBuilder) {
testStatusMessages = testStatusMessageBuilder.build();
}
testFormatter.runComplete(builder, finished.getResults(), testStatusMessages);
String testOutput;
synchronized (testReportBuilder) {
testReportBuilder.addAll(builder.build());
testOutput = Joiner.on('\n').join(testReportBuilder.build());
}
// We're about to write to stdout, so make sure we render the final frame before we do.
render();
synchronized (console.getStdOut()) {
console.getStdOut().println(testOutput);
}
}
@Subscribe
public void testStatusMessageStarted(TestStatusMessageEvent.Started started) {
threadsToRunningTestStatusMessageEvent.put(started.getThreadId(), Optional.of(started));
synchronized (testStatusMessageBuilder) {
testStatusMessageBuilder.add(started.getTestStatusMessage());
}
}
@Subscribe
public void testStatusMessageFinished(TestStatusMessageEvent.Finished finished) {
threadsToRunningTestStatusMessageEvent.put(
finished.getThreadId(),
Optional.empty());
synchronized (testStatusMessageBuilder) {
testStatusMessageBuilder.add(finished.getTestStatusMessage());
}
}
@Subscribe
public void testSummaryStarted(TestSummaryEvent.Started started) {
threadsToRunningTestSummaryEvent.put(started.getThreadId(), Optional.of(started));
}
@Subscribe
public void testSummaryFinished(TestSummaryEvent.Finished finished) {
threadsToRunningTestSummaryEvent.put(
finished.getThreadId(),
Optional.empty());
TestResultSummary testResult = finished.getTestResultSummary();
ResultType resultType = testResult.getType();
switch (resultType) {
case SUCCESS:
testPasses.incrementAndGet();
break;
case FAILURE:
testFailures.incrementAndGet();
// We don't use TestResultFormatter.reportResultSummary() here since that also
// includes the stack trace and stdout/stderr.
logEvents.add(
ConsoleEvent.severe(
String.format(
locale,
"%s %s %s: %s",
testResult.getType().toString(),
testResult.getTestCaseName(),
testResult.getTestName(),
testResult.getMessage())));
break;
case ASSUMPTION_VIOLATION:
testSkips.incrementAndGet();
break;
case DISABLED:
break;
case DRY_RUN:
break;
case EXCLUDED:
break;
}
}
@Subscribe
public void logEvent(ConsoleEvent event) {
logEvents.add(event);
}
@Override
public void printSevereWarningDirectly(String line) {
logEvents.add(ConsoleEvent.severe(line));
}
@Subscribe
public void bytesReceived(NetworkEvent.BytesReceivedEvent bytesReceivedEvent) {
networkStatsKeeper.bytesReceived(bytesReceivedEvent);
}
@Subscribe
@SuppressWarnings("unused")
public void actionGraphCacheHit(ActionGraphEvent.Cache.Hit event) {
parsingStatus = createParsingMessage(EMOJI_BUNNY, "");
}
@Subscribe
public void watchmanOverflow(WatchmanStatusEvent.Overflow event) {
parsingStatus = createParsingMessage(EMOJI_SNAIL, event.getReason());
}
@Subscribe
@SuppressWarnings("unused")
public void watchmanFileCreation(WatchmanStatusEvent.FileCreation event) {
parsingStatus = createParsingMessage(EMOJI_SNAIL, "File added");
}
@Subscribe
@SuppressWarnings("unused")
public void watchmanFileDeletion(WatchmanStatusEvent.FileDeletion event) {
parsingStatus = createParsingMessage(EMOJI_SNAIL, "File removed");
}
@Subscribe
@SuppressWarnings("unused")
public void daemonNewInstance(DaemonEvent.NewDaemonInstance event) {
parsingStatus = NEW_DAEMON_INSTANCE_MSG;
}
@Subscribe
@SuppressWarnings("unused")
public void symlinkInvalidation(ParsingEvent.SymlinkInvalidation event) {
parsingStatus = createParsingMessage(EMOJI_WHALE, "Symlink caused cache invalidation");
}
@Subscribe
public void envVariableChange(ParsingEvent.EnvVariableChange event) {
parsingStatus = createParsingMessage(EMOJI_SNAIL, "Environment variable changes: " +
event.getDiff());
}
@VisibleForTesting
static Optional<String> createParsingMessage(String emoji, String reason) {
if (Charset.defaultCharset().equals(Charsets.UTF_8)) {
return Optional.of(emoji + " " + reason);
} else {
if (emoji.equals(EMOJI_BUNNY)) {
return Optional.of("(FAST)");
} else {
return Optional.of("(SLOW) " + reason);
}
}
}
@VisibleForTesting
Optional<String> getParsingStatus() {
return parsingStatus;
}
@Override
public synchronized void close() throws IOException {
stopRenderScheduler();
networkStatsKeeper.stopScheduler();
render(); // Ensure final frame is rendered.
}
}
| Print Details link on own line to prevent truncating
Summary: The "Details" link in builds often gets truncated by the terminal for going over width. Put it on a new line so this doesn't happen.
Test Plan: run "buck build" with a webserver port set. observe that "Details" gets printed on a new line and does not get truncated.
Reviewed By: marcinkosiba
fbshipit-source-id: ff36e96
| src/com/facebook/buck/event/listener/SuperConsoleEventBusListener.java | Print Details link on own line to prevent truncating | <ide><path>rc/com/facebook/buck/event/listener/SuperConsoleEventBusListener.java
<ide> // All steps past this point require a build.
<ide> return lines.build();
<ide> }
<del> String suffix = Joiner.on(" ")
<add> String suffix = Joiner.on("\n ")
<ide> .join(FluentIterable.of(new String[] {jobSummary, buildTrace})
<ide> .filter(Objects::nonNull));
<ide> Optional<String> suffixOptional = |
|
Java | apache-2.0 | dc03d503ce7cf5e78e0e82d27704780a53ed180a | 0 | SeleniumHQ/htmlunit-driver | // 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.htmlunit.javascript;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.WebDriverTestCase;
import org.openqa.selenium.htmlunit.junit.BrowserRunner;
import org.openqa.selenium.htmlunit.junit.BrowserRunner.Alerts;
@RunWith(BrowserRunner.class)
public class History2Test extends WebDriverTestCase {
/**
* @throws Exception if an error occurs
*/
@Test
@Alerts({"[object PopStateEvent] # {\"hi\":\"there\"}",
"[object PopStateEvent] # {\"hi\":\"there\"}",
"[object PopStateEvent] # null",
"[object PopStateEvent] # null",
"[object PopStateEvent] # {\"hi\":\"there\"}",
"[object PopStateEvent] # {\"hi\":\"there\"}",
"[object PopStateEvent] # {\"hi2\":\"there2\"}",
"[object PopStateEvent] # {\"hi2\":\"there2\"}"})
public void pushState() throws Exception {
final String html = "<html>\n"
+ "<head>\n"
+ "<script>\n"
+ " function test() {\n"
+ " if (window.history.pushState) {\n"
+ " var stateObj = { hi: 'there' };\n"
+ " window.history.pushState(stateObj, 'page 2', 'bar.html');\n"
+ " }\n"
+ " }\n"
+ " function test2() {\n"
+ " if (window.history.pushState) {\n"
+ " var stateObj = { hi2: 'there2' };\n"
+ " window.history.pushState(stateObj, 'page 3', 'bar2.html');\n"
+ " }\n"
+ " }\n"
+ " function popMe(event) {\n"
+ " var e = event ? event : window.event;\n"
+ " alert(e + ' # ' + JSON.stringify(e.state));\n"
+ " }\n"
+ " function setWindowName() {\n"
+ " window.name = window.name + 'a';\n"
+ " }\n"
+ " window.addEventListener('popstate', popMe);\n"
+ "</script>\n"
+ "</head>\n"
+ "<body onpopstate='popMe(event)' onload='setWindowName()' onbeforeunload='setWindowName()' "
+ "onunload='setWindowName()'>\n"
+ " <button id=myId onclick='test()'>Click me</button>\n"
+ " <button id=myId2 onclick='test2()'>Click me</button>\n"
+ "</body></html>";
final String[] expectedAlerts = getExpectedAlerts();
int i = 0;
final WebDriver driver = loadPage2(html);
assertEquals(URL_FIRST.toString(), driver.getCurrentUrl());
assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
final long start = (Long) ((JavascriptExecutor) driver).executeScript("return window.history.length");
driver.findElement(By.id("myId")).click();
assertEquals(URL_FIRST + "bar.html", driver.getCurrentUrl());
assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
assertEquals(start + 1, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
driver.findElement(By.id("myId2")).click();
assertEquals(URL_FIRST + "bar2.html", driver.getCurrentUrl());
assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
assertEquals(start + 2, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
driver.navigate().back();
assertEquals(URL_FIRST + "bar.html", driver.getCurrentUrl());
verifyAlerts(DEFAULT_WAIT_TIME * 2, driver, expectedAlerts[i++], expectedAlerts[i++]);
assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
assertEquals(start + 2, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
driver.navigate().back();
assertEquals(URL_FIRST.toString(), driver.getCurrentUrl());
verifyAlerts(DEFAULT_WAIT_TIME * 2, driver, expectedAlerts[i++], expectedAlerts[i++]);
assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
assertEquals(start + 2, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
driver.navigate().forward();
assertEquals(URL_FIRST + "bar.html", driver.getCurrentUrl());
verifyAlerts(DEFAULT_WAIT_TIME * 2, driver, expectedAlerts[i++], expectedAlerts[i++]);
assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
assertEquals(start + 2, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
driver.navigate().forward();
assertEquals(URL_FIRST + "bar2.html", driver.getCurrentUrl());
verifyAlerts(DEFAULT_WAIT_TIME * 2, driver, expectedAlerts[i++], expectedAlerts[i++]);
assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
assertEquals(start + 2, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
assertEquals(1, getMockWebConnection().getRequestCount());
// because we have changed the window name
releaseResources();
shutDownAll();
}
}
| src/test/java/org/openqa/selenium/htmlunit/javascript/History2Test.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.htmlunit.javascript;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.WebDriverTestCase;
import org.openqa.selenium.htmlunit.junit.BrowserRunner;
import org.openqa.selenium.htmlunit.junit.BrowserRunner.Alerts;
@RunWith(BrowserRunner.class)
public class History2Test extends WebDriverTestCase {
/**
* @throws Exception if an error occurs
*/
@Test
@Alerts({"[object PopStateEvent] # {\"hi\":\"there\"}",
"[object PopStateEvent] # {\"hi\":\"there\"}",
"[object PopStateEvent] # null",
"[object PopStateEvent] # null",
"[object PopStateEvent] # {\"hi\":\"there\"}",
"[object PopStateEvent] # {\"hi\":\"there\"}",
"[object PopStateEvent] # {\"hi2\":\"there2\"}",
"[object PopStateEvent] # {\"hi2\":\"there2\"}"})
public void pushState() throws Exception {
final String html = "<html>\n"
+ "<head>\n"
+ "<script>\n"
+ " function test() {\n"
+ " if (window.history.pushState) {\n"
+ " var stateObj = { hi: 'there' };\n"
+ " window.history.pushState(stateObj, 'page 2', 'bar.html');\n"
+ " }\n"
+ " }\n"
+ " function test2() {\n"
+ " if (window.history.pushState) {\n"
+ " var stateObj = { hi2: 'there2' };\n"
+ " window.history.pushState(stateObj, 'page 3', 'bar2.html');\n"
+ " }\n"
+ " }\n"
+ " function popMe(event) {\n"
+ " var e = event ? event : window.event;\n"
+ " alert(e + ' # ' + JSON.stringify(e.state));\n"
+ " }\n"
+ " function setWindowName() {\n"
+ " window.name = window.name + 'a';\n"
+ " }\n"
+ " window.addEventListener('popstate', popMe);\n"
+ "</script>\n"
+ "</head>\n"
+ "<body onpopstate='popMe(event)' onload='setWindowName()' onbeforeunload='setWindowName()' "
+ "onunload='setWindowName()'>\n"
+ " <button id=myId onclick='test()'>Click me</button>\n"
+ " <button id=myId2 onclick='test2()'>Click me</button>\n"
+ "</body></html>";
final String[] expectedAlerts = getExpectedAlerts();
int i = 0;
final WebDriver driver = loadPage2(html);
assertEquals(URL_FIRST.toString(), driver.getCurrentUrl());
assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
final long start = (Long) ((JavascriptExecutor) driver).executeScript("return window.history.length");
driver.findElement(By.id("myId")).click();
assertEquals(URL_FIRST + "bar.html", driver.getCurrentUrl());
assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
assertEquals(start + 1, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
driver.findElement(By.id("myId2")).click();
assertEquals(URL_FIRST + "bar2.html", driver.getCurrentUrl());
assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
assertEquals(start + 2, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
driver.navigate().back();
assertEquals(URL_FIRST + "bar.html", driver.getCurrentUrl());
verifyAlerts(driver, expectedAlerts[i++], expectedAlerts[i++]);
assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
assertEquals(start + 2, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
driver.navigate().back();
assertEquals(URL_FIRST.toString(), driver.getCurrentUrl());
verifyAlerts(driver, expectedAlerts[i++], expectedAlerts[i++]);
assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
assertEquals(start + 2, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
driver.navigate().forward();
assertEquals(URL_FIRST + "bar.html", driver.getCurrentUrl());
verifyAlerts(driver, expectedAlerts[i++], expectedAlerts[i++]);
assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
assertEquals(start + 2, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
driver.navigate().forward();
assertEquals(URL_FIRST + "bar2.html", driver.getCurrentUrl());
verifyAlerts(driver, expectedAlerts[i++], expectedAlerts[i++]);
assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
assertEquals(start + 2, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
assertEquals(1, getMockWebConnection().getRequestCount());
// because we have changed the window name
releaseResources();
shutDownAll();
}
}
| next try
| src/test/java/org/openqa/selenium/htmlunit/javascript/History2Test.java | next try | <ide><path>rc/test/java/org/openqa/selenium/htmlunit/javascript/History2Test.java
<ide>
<ide> driver.navigate().back();
<ide> assertEquals(URL_FIRST + "bar.html", driver.getCurrentUrl());
<del> verifyAlerts(driver, expectedAlerts[i++], expectedAlerts[i++]);
<add> verifyAlerts(DEFAULT_WAIT_TIME * 2, driver, expectedAlerts[i++], expectedAlerts[i++]);
<ide> assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
<ide> assertEquals(start + 2, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
<ide>
<ide> driver.navigate().back();
<ide> assertEquals(URL_FIRST.toString(), driver.getCurrentUrl());
<del> verifyAlerts(driver, expectedAlerts[i++], expectedAlerts[i++]);
<add> verifyAlerts(DEFAULT_WAIT_TIME * 2, driver, expectedAlerts[i++], expectedAlerts[i++]);
<ide> assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
<ide> assertEquals(start + 2, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
<ide>
<ide> driver.navigate().forward();
<ide> assertEquals(URL_FIRST + "bar.html", driver.getCurrentUrl());
<del> verifyAlerts(driver, expectedAlerts[i++], expectedAlerts[i++]);
<add> verifyAlerts(DEFAULT_WAIT_TIME * 2, driver, expectedAlerts[i++], expectedAlerts[i++]);
<ide> assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
<ide> assertEquals(start + 2, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
<ide>
<ide> driver.navigate().forward();
<ide> assertEquals(URL_FIRST + "bar2.html", driver.getCurrentUrl());
<del> verifyAlerts(driver, expectedAlerts[i++], expectedAlerts[i++]);
<add> verifyAlerts(DEFAULT_WAIT_TIME * 2, driver, expectedAlerts[i++], expectedAlerts[i++]);
<ide> assertEquals("a", ((JavascriptExecutor) driver).executeScript("return window.name"));
<ide> assertEquals(start + 2, ((JavascriptExecutor) driver).executeScript("return window.history.length"));
<ide> |
|
Java | apache-2.0 | fbbda80ec3300c06baf7894c2be2781325c839c7 | 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 | platform/util/src/com/intellij/util/io/DupOutputStream.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.intellij.util.io;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.io.OutputStream;
public final class DupOutputStream extends OutputStream {
private final OutputStream myStream1;
private final OutputStream myStream2;
public DupOutputStream(@NotNull OutputStream stream1, @NotNull OutputStream stream2) {
myStream1 = stream1;
myStream2 = stream2;
}
@Override
public void write(final int b) throws IOException {
myStream1.write(b);
myStream2.write(b);
}
@Override
public void close() throws IOException {
myStream1.close();
myStream2.close();
}
@Override
public void flush() throws IOException {
myStream1.flush();
myStream2.flush();
}
@Override
public void write(final byte[] b) throws IOException {
myStream1.write(b);
myStream2.write(b);
}
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
myStream1.write(b, off, len);
myStream2.write(b, off, len);
}
}
| delete DupOutputStream
GitOrigin-RevId: cd8ad0a47f83278d55d1f0f14165f209cc1df72c | platform/util/src/com/intellij/util/io/DupOutputStream.java | delete DupOutputStream | <ide><path>latform/util/src/com/intellij/util/io/DupOutputStream.java
<del>// 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.
<del>package com.intellij.util.io;
<del>
<del>import org.jetbrains.annotations.NotNull;
<del>
<del>import java.io.IOException;
<del>import java.io.OutputStream;
<del>
<del>public final class DupOutputStream extends OutputStream {
<del> private final OutputStream myStream1;
<del> private final OutputStream myStream2;
<del>
<del> public DupOutputStream(@NotNull OutputStream stream1, @NotNull OutputStream stream2) {
<del> myStream1 = stream1;
<del> myStream2 = stream2;
<del> }
<del>
<del> @Override
<del> public void write(final int b) throws IOException {
<del> myStream1.write(b);
<del> myStream2.write(b);
<del> }
<del>
<del> @Override
<del> public void close() throws IOException {
<del> myStream1.close();
<del> myStream2.close();
<del> }
<del>
<del> @Override
<del> public void flush() throws IOException {
<del> myStream1.flush();
<del> myStream2.flush();
<del> }
<del>
<del> @Override
<del> public void write(final byte[] b) throws IOException {
<del> myStream1.write(b);
<del> myStream2.write(b);
<del> }
<del>
<del> @Override
<del> public void write(final byte[] b, final int off, final int len) throws IOException {
<del> myStream1.write(b, off, len);
<del> myStream2.write(b, off, len);
<del> }
<del>} |
||
Java | apache-2.0 | aa4fd4d1da6fb6fa2e27f446408033256af64137 | 0 | bhb27/KA27,bhb27/KA27 | /*
* Copyright (C) 2015 Willi Ye
*
* 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.grarak.kerneladiutor.utils.kernel;
import android.content.Context;
import com.grarak.kerneladiutor.utils.Constants;
import com.grarak.kerneladiutor.utils.Utils;
import com.grarak.kerneladiutor.utils.root.Control;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Created by willi on 26.12.14.
*/
public class GPU implements Constants {
private static String GPU_2D_CUR_FREQ;
private static String GPU_2D_MAX_FREQ;
private static String GPU_2D_AVAILABLE_FREQS;
private static String GPU_2D_SCALING_GOVERNOR;
private static String[] mAvail_2D_Govs;
private static Integer[] mGpu2dFreqs;
private static int mGPU_Min_Pwr = 20;
private static String GPU_CUR_FREQ;
private static String GPU_MAX_FREQ;
private static String GPU_MIN_FREQ;
private static String GPU_AVAILABLE_FREQS;
private static String GPU_SCALING_GOVERNOR;
private static String[] GPU_AVAILABLE_GOVERNORS;
private static Integer[] mGpuFreqs;
public static void setAdrenoIdlerIdleWorkload(int value, Context context) {
Control.runCommand(String.valueOf(value * 1000), ADRENO_IDLER_IDLEWORKLOAD, Control.CommandType.GENERIC, context);
}
public static int getAdrenoIdlerIdleWorkload() {
return Utils.stringToInt(Utils.readFile(ADRENO_IDLER_IDLEWORKLOAD)) / 1000;
}
public static void setAdrenoIdlerIdleWait(int value, Context context) {
Control.runCommand(String.valueOf(value), ADRENO_IDLER_IDLEWAIT, Control.CommandType.GENERIC, context);
}
public static int getAdrenoIdlerIdleWait() {
return Utils.stringToInt(Utils.readFile(ADRENO_IDLER_IDLEWAIT));
}
public static void setAdrenoIdlerDownDiff(int value, Context context) {
Control.runCommand(String.valueOf(value), ADRENO_IDLER_DOWNDIFFERENTIAL, Control.CommandType.GENERIC, context);
}
public static int getAdrenoIdlerDownDiff() {
return Utils.stringToInt(Utils.readFile(ADRENO_IDLER_DOWNDIFFERENTIAL));
}
public static void activateAdrenoIdler(boolean active, Context context) {
if (Utils.isLetter(Utils.readFile(ADRENO_IDLER_ACTIVATE))) {
Control.runCommand(active ? "Y" : "N", ADRENO_IDLER_ACTIVATE, Control.CommandType.GENERIC, context);
} else {
Control.runCommand(active ? "1" : "0", ADRENO_IDLER_ACTIVATE, Control.CommandType.GENERIC, context);
}
}
public static boolean isAdrenoIdlerActive() {
return Utils.readFile(ADRENO_IDLER_ACTIVATE).equals(Utils.isLetter(Utils.readFile(ADRENO_IDLER_ACTIVATE)) ? "Y" :"1");
}
public static boolean hasAdrenoIdler() {
return Utils.existFile(ADRENO_IDLER_PARAMETERS);
}
public static void activateSimpleOndemandScaling(boolean active, Context context) {
Control.runCommand(active ? "1" : "0", SIMPLE_ONDEMAND_SCALING, Control.CommandType.GENERIC, context);
}
public static boolean isSimpleOndemandScalingActive() {
return Utils.readFile(SIMPLE_ONDEMAND_SCALING).equals("1");
}
public static boolean hasSimpleOndemandScaling() {
return Utils.existFile(SIMPLE_ONDEMAND_PARAMETERS);
}
public static void setSimpleOndemandDownDiff(int value, Context context) {
Control.runCommand(String.valueOf(value), SIMPLE_ONDEMAND_DOWNDIFFERENTIAL, Control.CommandType.GENERIC, context);
}
public static int getSimpleOndemandDownDiff() {
return Utils.stringToInt(Utils.readFile(SIMPLE_ONDEMAND_DOWNDIFFERENTIAL));
}
public static void setSimpleOndemandUpthreshold(int value, Context context) {
Control.runCommand(String.valueOf(value), SIMPLE_ONDEMAND_UPTHRESHOLD, Control.CommandType.GENERIC, context);
}
public static int getSimpleOndemandUpthreshold() {
return Utils.stringToInt(Utils.readFile(SIMPLE_ONDEMAND_UPTHRESHOLD));
}
public static void setSimpleGpuRampThreshold(int value, Context context) {
Control.runCommand(String.valueOf(value * 1000), SIMPLE_RAMP_THRESHOLD, Control.CommandType.GENERIC, context);
}
public static int getSimpleGpuRampThreshold() {
return Utils.stringToInt(Utils.readFile(SIMPLE_RAMP_THRESHOLD)) / 1000;
}
public static void setSimpleGpuLaziness(int value, Context context) {
Control.runCommand(String.valueOf(value), SIMPLE_GPU_LAZINESS, Control.CommandType.GENERIC, context);
}
public static int getSimpleGpuLaziness() {
return Utils.stringToInt(Utils.readFile(SIMPLE_GPU_LAZINESS));
}
public static void activateSimpleGpu(boolean active, Context context) {
Control.runCommand(active ? "1" : "0", SIMPLE_GPU_ACTIVATE, Control.CommandType.GENERIC, context);
}
public static boolean isSimpleGpuActive() {
return Utils.readFile(SIMPLE_GPU_ACTIVATE).equals("1");
}
public static boolean hasSimpleGpu() {
return Utils.existFile(SIMPLE_GPU_PARAMETERS);
}
public static void activateGamingMode(boolean active, Context context) {
Control.runCommand(active ? "0" : Integer.toString(mGPU_Min_Pwr) , GPU_MIN_POWER_LEVEL, Control.CommandType.GENERIC, context);
}
public static boolean isGamingModeActive() {
return Utils.readFile(GPU_MIN_POWER_LEVEL).equals("0");
}
public static boolean hasGPUMinPowerLevel() {
if (Utils.existFile(GPU_NUM_POWER_LEVELS)) {
mGPU_Min_Pwr = Utils.stringToInt(Utils.readFile(GPU_NUM_POWER_LEVELS)) - 1;
}
return Utils.existFile(GPU_MIN_POWER_LEVEL);
}
public static void setGpu2dGovernor(String governor, Context context) {
if (GPU_2D_SCALING_GOVERNOR != null)
Control.runCommand(governor, GPU_2D_SCALING_GOVERNOR, Control.CommandType.GENERIC, context);
}
public static List<String> getGpu2dGovernors() {
if (mAvail_2D_Govs == null) mAvail_2D_Govs = new String[0];
String value = Utils.readFile(GPU_GENERIC_GOVERNORS);
if (value != null) {
mAvail_2D_Govs = value.split(" ");
Collections.sort(Arrays.asList(mAvail_2D_Govs), String.CASE_INSENSITIVE_ORDER);
}
return new ArrayList<>(Arrays.asList(mAvail_2D_Govs));
}
public static String getGpu2dGovernor() {
if (GPU_2D_SCALING_GOVERNOR != null)
if (Utils.existFile(GPU_2D_SCALING_GOVERNOR)) {
String value = Utils.readFile(GPU_2D_SCALING_GOVERNOR);
if (value != null) return value;
}
return "";
}
public static boolean hasGpu2dGovernor() {
if (GPU_2D_SCALING_GOVERNOR == null)
for (String file : GPU_2D_SCALING_GOVERNOR_ARRAY)
if (Utils.existFile(file)) GPU_2D_SCALING_GOVERNOR = file;
return GPU_2D_SCALING_GOVERNOR != null;
}
public static void setGpu2dMaxFreq(int freq, Context context) {
if (GPU_2D_MAX_FREQ != null)
Control.runCommand(String.valueOf(freq), GPU_2D_MAX_FREQ, Control.CommandType.GENERIC, context);
}
public static List<Integer> getGpu2dFreqs() {
if (GPU_2D_AVAILABLE_FREQS != null)
if (mGpu2dFreqs == null)
if (Utils.existFile(GPU_2D_AVAILABLE_FREQS)) {
String value = Utils.readFile(GPU_2D_AVAILABLE_FREQS);
if (value != null) {
String[] freqs = value.split(" ");
mGpu2dFreqs = new Integer[freqs.length];
for (int i = 0; i < mGpu2dFreqs.length; i++)
mGpu2dFreqs[i] = Utils.stringToInt(freqs[i]);
}
}
return new ArrayList<>(Arrays.asList(mGpu2dFreqs));
}
public static boolean hasGpu2dFreqs() {
if (GPU_2D_AVAILABLE_FREQS == null) {
for (String file : GPU_2D_AVAILABLE_FREQS_ARRAY)
if (Utils.existFile(file)) GPU_2D_AVAILABLE_FREQS = file;
}
String value = Utils.readFile(GPU_2D_AVAILABLE_FREQS);
if (value == null) value = "";
return !value.isEmpty();
}
public static int getGpu2dMaxFreq() {
if (GPU_2D_MAX_FREQ != null) if (Utils.existFile(GPU_2D_MAX_FREQ)) {
String value = Utils.readFile(GPU_2D_MAX_FREQ);
if (value != null) return Utils.stringToInt(value);
}
return 0;
}
public static boolean hasGpu2dMaxFreq() {
if (GPU_2D_MAX_FREQ == null) {
for (String file : GPU_2D_MAX_FREQ_ARRAY)
if (Utils.existFile(file)) GPU_2D_MAX_FREQ = file;
}
return GPU_2D_MAX_FREQ != null;
}
public static int getGpu2dCurFreq() {
if (GPU_2D_CUR_FREQ != null) if (Utils.existFile(GPU_2D_CUR_FREQ)) {
String value = Utils.readFile(GPU_2D_CUR_FREQ);
if (value != null) return Utils.stringToInt(value);
}
return 0;
}
public static boolean hasGpu2dCurFreq() {
if (GPU_2D_CUR_FREQ == null) {
for (String file : GPU_2D_CUR_FREQ_ARRAY)
if (Utils.existFile(file)) GPU_2D_CUR_FREQ = file;
}
return GPU_2D_CUR_FREQ != null;
}
public static void setGpuGovernor(String governor, Context context) {
if (GPU_SCALING_GOVERNOR != null)
Control.runCommand(governor, GPU_SCALING_GOVERNOR, Control.CommandType.GENERIC, context);
}
public static List<String> getGpuGovernors() {
if (GPU_AVAILABLE_GOVERNORS == null)
for (String file : GPU_AVAILABLE_GOVERNORS_ARRAY)
if (GPU_AVAILABLE_GOVERNORS == null)
if (Utils.existFile(file)) {
String value = Utils.readFile(file);
if (value != null)
GPU_AVAILABLE_GOVERNORS = value.split(" ");
Collections.sort(Arrays.asList(GPU_AVAILABLE_GOVERNORS), String.CASE_INSENSITIVE_ORDER);
}
return new ArrayList<>(Arrays.asList(GPU_AVAILABLE_GOVERNORS == null ? GPU_GENERIC_GOVERNORS
.split(" ") : GPU_AVAILABLE_GOVERNORS));
}
public static String getGpuGovernor() {
if (GPU_SCALING_GOVERNOR != null)
if (Utils.existFile(GPU_SCALING_GOVERNOR)) {
String value = Utils.readFile(GPU_SCALING_GOVERNOR);
if (value != null) return value;
}
return "";
}
public static boolean hasGpuGovernor() {
if (GPU_SCALING_GOVERNOR == null)
for (String file : GPU_SCALING_GOVERNOR_ARRAY)
if (Utils.existFile(file)) GPU_SCALING_GOVERNOR = file;
return GPU_SCALING_GOVERNOR != null;
}
public static void setGpuMinFreq(int freq, Context context) {
if (GPU_MIN_FREQ != null)
Control.runCommand(String.valueOf(freq), GPU_MIN_FREQ, Control.CommandType.GENERIC, context);
}
public static void setGpuMaxFreq(int freq, Context context) {
if (GPU_MAX_FREQ != null)
Control.runCommand(String.valueOf(freq), GPU_MAX_FREQ, Control.CommandType.GENERIC, context);
}
public static List<Integer> getGpuFreqs() {
if (GPU_AVAILABLE_FREQS != null)
if (mGpuFreqs == null)
if (Utils.existFile(GPU_AVAILABLE_FREQS)) {
String value = Utils.readFile(GPU_AVAILABLE_FREQS);
if (value != null) {
String[] freqs = value.split(" ");
mGpuFreqs = new Integer[freqs.length];
for (int i = 0; i < mGpuFreqs.length; i++)
mGpuFreqs[i] = Utils.stringToInt(freqs[i]);
}
}
return new ArrayList<>(Arrays.asList(mGpuFreqs));
}
public static boolean hasGpuFreqs() {
if (GPU_AVAILABLE_FREQS == null) {
for (String file : GPU_AVAILABLE_FREQS_ARRAY)
if (Utils.existFile(file)) GPU_AVAILABLE_FREQS = file;
}
return GPU_AVAILABLE_FREQS != null;
}
public static int getGpuMinFreq() {
if (GPU_MIN_FREQ != null) if (Utils.existFile(GPU_MIN_FREQ)) {
String value = Utils.readFile(GPU_MIN_FREQ);
if (value != null) return Utils.stringToInt(value);
}
return 0;
}
public static boolean hasGpuMinFreq() {
if (GPU_MIN_FREQ == null) {
for (String file : GPU_MIN_FREQ_ARRAY)
if (Utils.existFile(file)) GPU_MIN_FREQ = file;
}
return GPU_MIN_FREQ != null;
}
public static int getGpuMaxFreq() {
if (GPU_MAX_FREQ != null) if (Utils.existFile(GPU_MAX_FREQ)) {
String value = Utils.readFile(GPU_MAX_FREQ);
if (value != null) return Utils.stringToInt(value);
}
return 0;
}
public static boolean hasGpuMaxFreq() {
if (GPU_MAX_FREQ == null) {
for (String file : GPU_MAX_FREQ_ARRAY)
if (Utils.existFile(file)) GPU_MAX_FREQ = file;
}
return GPU_MAX_FREQ != null;
}
public static int getGpuCurFreq() {
if (GPU_CUR_FREQ != null) if (Utils.existFile(GPU_CUR_FREQ)) {
String value = Utils.readFile(GPU_CUR_FREQ);
if (value != null) return Utils.stringToInt(value);
}
return 0;
}
public static boolean hasGpuCurFreq() {
if (GPU_CUR_FREQ == null) {
for (String file : GPU_CUR_FREQ_ARRAY)
if (Utils.existFile(file)) GPU_CUR_FREQ = file;
}
return GPU_CUR_FREQ != null;
}
public static boolean hasGpuControl() {
for (String[] files : GPU_ARRAY)
for (String file : files) if (Utils.existFile(file)) return true;
return false;
}
}
| app/src/main/java/com/grarak/kerneladiutor/utils/kernel/GPU.java | /*
* Copyright (C) 2015 Willi Ye
*
* 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.grarak.kerneladiutor.utils.kernel;
import android.content.Context;
import com.grarak.kerneladiutor.utils.Constants;
import com.grarak.kerneladiutor.utils.Utils;
import com.grarak.kerneladiutor.utils.root.Control;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Created by willi on 26.12.14.
*/
public class GPU implements Constants {
private static String GPU_2D_CUR_FREQ;
private static String GPU_2D_MAX_FREQ;
private static String GPU_2D_AVAILABLE_FREQS;
private static String GPU_2D_SCALING_GOVERNOR;
private static String[] mAvail_2D_Govs;
private static Integer[] mGpu2dFreqs;
private static int mGPU_Min_Pwr = 20;
private static String GPU_CUR_FREQ;
private static String GPU_MAX_FREQ;
private static String GPU_MIN_FREQ;
private static String GPU_AVAILABLE_FREQS;
private static String GPU_SCALING_GOVERNOR;
private static String[] GPU_AVAILABLE_GOVERNORS;
private static Integer[] mGpuFreqs;
public static void setAdrenoIdlerIdleWorkload(int value, Context context) {
Control.runCommand(String.valueOf(value * 1000), ADRENO_IDLER_IDLEWORKLOAD, Control.CommandType.GENERIC, context);
}
public static int getAdrenoIdlerIdleWorkload() {
return Utils.stringToInt(Utils.readFile(ADRENO_IDLER_IDLEWORKLOAD)) / 1000;
}
public static void setAdrenoIdlerIdleWait(int value, Context context) {
Control.runCommand(String.valueOf(value), ADRENO_IDLER_IDLEWAIT, Control.CommandType.GENERIC, context);
}
public static int getAdrenoIdlerIdleWait() {
return Utils.stringToInt(Utils.readFile(ADRENO_IDLER_IDLEWAIT));
}
public static void setAdrenoIdlerDownDiff(int value, Context context) {
Control.runCommand(String.valueOf(value), ADRENO_IDLER_DOWNDIFFERENTIAL, Control.CommandType.GENERIC, context);
}
public static int getAdrenoIdlerDownDiff() {
return Utils.stringToInt(Utils.readFile(ADRENO_IDLER_DOWNDIFFERENTIAL));
}
public static void activateAdrenoIdler(boolean active, Context context) {
Control.runCommand(active ? "Y" : "N", ADRENO_IDLER_ACTIVATE, Control.CommandType.GENERIC, context);
}
public static boolean isAdrenoIdlerActive() {
return Utils.readFile(ADRENO_IDLER_ACTIVATE).equals("Y");
}
public static boolean hasAdrenoIdler() {
return Utils.existFile(ADRENO_IDLER_PARAMETERS);
}
public static void activateSimpleOndemandScaling(boolean active, Context context) {
Control.runCommand(active ? "1" : "0", SIMPLE_ONDEMAND_SCALING, Control.CommandType.GENERIC, context);
}
public static boolean isSimpleOndemandScalingActive() {
return Utils.readFile(SIMPLE_ONDEMAND_SCALING).equals("1");
}
public static boolean hasSimpleOndemandScaling() {
return Utils.existFile(SIMPLE_ONDEMAND_PARAMETERS);
}
public static void setSimpleOndemandDownDiff(int value, Context context) {
Control.runCommand(String.valueOf(value), SIMPLE_ONDEMAND_DOWNDIFFERENTIAL, Control.CommandType.GENERIC, context);
}
public static int getSimpleOndemandDownDiff() {
return Utils.stringToInt(Utils.readFile(SIMPLE_ONDEMAND_DOWNDIFFERENTIAL));
}
public static void setSimpleOndemandUpthreshold(int value, Context context) {
Control.runCommand(String.valueOf(value), SIMPLE_ONDEMAND_UPTHRESHOLD, Control.CommandType.GENERIC, context);
}
public static int getSimpleOndemandUpthreshold() {
return Utils.stringToInt(Utils.readFile(SIMPLE_ONDEMAND_UPTHRESHOLD));
}
public static void setSimpleGpuRampThreshold(int value, Context context) {
Control.runCommand(String.valueOf(value * 1000), SIMPLE_RAMP_THRESHOLD, Control.CommandType.GENERIC, context);
}
public static int getSimpleGpuRampThreshold() {
return Utils.stringToInt(Utils.readFile(SIMPLE_RAMP_THRESHOLD)) / 1000;
}
public static void setSimpleGpuLaziness(int value, Context context) {
Control.runCommand(String.valueOf(value), SIMPLE_GPU_LAZINESS, Control.CommandType.GENERIC, context);
}
public static int getSimpleGpuLaziness() {
return Utils.stringToInt(Utils.readFile(SIMPLE_GPU_LAZINESS));
}
public static void activateSimpleGpu(boolean active, Context context) {
Control.runCommand(active ? "1" : "0", SIMPLE_GPU_ACTIVATE, Control.CommandType.GENERIC, context);
}
public static boolean isSimpleGpuActive() {
return Utils.readFile(SIMPLE_GPU_ACTIVATE).equals("1");
}
public static boolean hasSimpleGpu() {
return Utils.existFile(SIMPLE_GPU_PARAMETERS);
}
public static void activateGamingMode(boolean active, Context context) {
Control.runCommand(active ? "0" : Integer.toString(mGPU_Min_Pwr) , GPU_MIN_POWER_LEVEL, Control.CommandType.GENERIC, context);
}
public static boolean isGamingModeActive() {
return Utils.readFile(GPU_MIN_POWER_LEVEL).equals("0");
}
public static boolean hasGPUMinPowerLevel() {
if (Utils.existFile(GPU_NUM_POWER_LEVELS)) {
mGPU_Min_Pwr = Utils.stringToInt(Utils.readFile(GPU_NUM_POWER_LEVELS)) - 1;
}
return Utils.existFile(GPU_MIN_POWER_LEVEL);
}
public static void setGpu2dGovernor(String governor, Context context) {
if (GPU_2D_SCALING_GOVERNOR != null)
Control.runCommand(governor, GPU_2D_SCALING_GOVERNOR, Control.CommandType.GENERIC, context);
}
public static List<String> getGpu2dGovernors() {
if (mAvail_2D_Govs == null) mAvail_2D_Govs = new String[0];
String value = Utils.readFile(GPU_GENERIC_GOVERNORS);
if (value != null) {
mAvail_2D_Govs = value.split(" ");
Collections.sort(Arrays.asList(mAvail_2D_Govs), String.CASE_INSENSITIVE_ORDER);
}
return new ArrayList<>(Arrays.asList(mAvail_2D_Govs));
}
public static String getGpu2dGovernor() {
if (GPU_2D_SCALING_GOVERNOR != null)
if (Utils.existFile(GPU_2D_SCALING_GOVERNOR)) {
String value = Utils.readFile(GPU_2D_SCALING_GOVERNOR);
if (value != null) return value;
}
return "";
}
public static boolean hasGpu2dGovernor() {
if (GPU_2D_SCALING_GOVERNOR == null)
for (String file : GPU_2D_SCALING_GOVERNOR_ARRAY)
if (Utils.existFile(file)) GPU_2D_SCALING_GOVERNOR = file;
return GPU_2D_SCALING_GOVERNOR != null;
}
public static void setGpu2dMaxFreq(int freq, Context context) {
if (GPU_2D_MAX_FREQ != null)
Control.runCommand(String.valueOf(freq), GPU_2D_MAX_FREQ, Control.CommandType.GENERIC, context);
}
public static List<Integer> getGpu2dFreqs() {
if (GPU_2D_AVAILABLE_FREQS != null)
if (mGpu2dFreqs == null)
if (Utils.existFile(GPU_2D_AVAILABLE_FREQS)) {
String value = Utils.readFile(GPU_2D_AVAILABLE_FREQS);
if (value != null) {
String[] freqs = value.split(" ");
mGpu2dFreqs = new Integer[freqs.length];
for (int i = 0; i < mGpu2dFreqs.length; i++)
mGpu2dFreqs[i] = Utils.stringToInt(freqs[i]);
}
}
return new ArrayList<>(Arrays.asList(mGpu2dFreqs));
}
public static boolean hasGpu2dFreqs() {
if (GPU_2D_AVAILABLE_FREQS == null) {
for (String file : GPU_2D_AVAILABLE_FREQS_ARRAY)
if (Utils.existFile(file)) GPU_2D_AVAILABLE_FREQS = file;
}
String value = Utils.readFile(GPU_2D_AVAILABLE_FREQS);
if (value == null) value = "";
return !value.isEmpty();
}
public static int getGpu2dMaxFreq() {
if (GPU_2D_MAX_FREQ != null) if (Utils.existFile(GPU_2D_MAX_FREQ)) {
String value = Utils.readFile(GPU_2D_MAX_FREQ);
if (value != null) return Utils.stringToInt(value);
}
return 0;
}
public static boolean hasGpu2dMaxFreq() {
if (GPU_2D_MAX_FREQ == null) {
for (String file : GPU_2D_MAX_FREQ_ARRAY)
if (Utils.existFile(file)) GPU_2D_MAX_FREQ = file;
}
return GPU_2D_MAX_FREQ != null;
}
public static int getGpu2dCurFreq() {
if (GPU_2D_CUR_FREQ != null) if (Utils.existFile(GPU_2D_CUR_FREQ)) {
String value = Utils.readFile(GPU_2D_CUR_FREQ);
if (value != null) return Utils.stringToInt(value);
}
return 0;
}
public static boolean hasGpu2dCurFreq() {
if (GPU_2D_CUR_FREQ == null) {
for (String file : GPU_2D_CUR_FREQ_ARRAY)
if (Utils.existFile(file)) GPU_2D_CUR_FREQ = file;
}
return GPU_2D_CUR_FREQ != null;
}
public static void setGpuGovernor(String governor, Context context) {
if (GPU_SCALING_GOVERNOR != null)
Control.runCommand(governor, GPU_SCALING_GOVERNOR, Control.CommandType.GENERIC, context);
}
public static List<String> getGpuGovernors() {
if (GPU_AVAILABLE_GOVERNORS == null)
for (String file : GPU_AVAILABLE_GOVERNORS_ARRAY)
if (GPU_AVAILABLE_GOVERNORS == null)
if (Utils.existFile(file)) {
String value = Utils.readFile(file);
if (value != null)
GPU_AVAILABLE_GOVERNORS = value.split(" ");
Collections.sort(Arrays.asList(GPU_AVAILABLE_GOVERNORS), String.CASE_INSENSITIVE_ORDER);
}
return new ArrayList<>(Arrays.asList(GPU_AVAILABLE_GOVERNORS == null ? GPU_GENERIC_GOVERNORS
.split(" ") : GPU_AVAILABLE_GOVERNORS));
}
public static String getGpuGovernor() {
if (GPU_SCALING_GOVERNOR != null)
if (Utils.existFile(GPU_SCALING_GOVERNOR)) {
String value = Utils.readFile(GPU_SCALING_GOVERNOR);
if (value != null) return value;
}
return "";
}
public static boolean hasGpuGovernor() {
if (GPU_SCALING_GOVERNOR == null)
for (String file : GPU_SCALING_GOVERNOR_ARRAY)
if (Utils.existFile(file)) GPU_SCALING_GOVERNOR = file;
return GPU_SCALING_GOVERNOR != null;
}
public static void setGpuMinFreq(int freq, Context context) {
if (GPU_MIN_FREQ != null)
Control.runCommand(String.valueOf(freq), GPU_MIN_FREQ, Control.CommandType.GENERIC, context);
}
public static void setGpuMaxFreq(int freq, Context context) {
if (GPU_MAX_FREQ != null)
Control.runCommand(String.valueOf(freq), GPU_MAX_FREQ, Control.CommandType.GENERIC, context);
}
public static List<Integer> getGpuFreqs() {
if (GPU_AVAILABLE_FREQS != null)
if (mGpuFreqs == null)
if (Utils.existFile(GPU_AVAILABLE_FREQS)) {
String value = Utils.readFile(GPU_AVAILABLE_FREQS);
if (value != null) {
String[] freqs = value.split(" ");
mGpuFreqs = new Integer[freqs.length];
for (int i = 0; i < mGpuFreqs.length; i++)
mGpuFreqs[i] = Utils.stringToInt(freqs[i]);
}
}
return new ArrayList<>(Arrays.asList(mGpuFreqs));
}
public static boolean hasGpuFreqs() {
if (GPU_AVAILABLE_FREQS == null) {
for (String file : GPU_AVAILABLE_FREQS_ARRAY)
if (Utils.existFile(file)) GPU_AVAILABLE_FREQS = file;
}
return GPU_AVAILABLE_FREQS != null;
}
public static int getGpuMinFreq() {
if (GPU_MIN_FREQ != null) if (Utils.existFile(GPU_MIN_FREQ)) {
String value = Utils.readFile(GPU_MIN_FREQ);
if (value != null) return Utils.stringToInt(value);
}
return 0;
}
public static boolean hasGpuMinFreq() {
if (GPU_MIN_FREQ == null) {
for (String file : GPU_MIN_FREQ_ARRAY)
if (Utils.existFile(file)) GPU_MIN_FREQ = file;
}
return GPU_MIN_FREQ != null;
}
public static int getGpuMaxFreq() {
if (GPU_MAX_FREQ != null) if (Utils.existFile(GPU_MAX_FREQ)) {
String value = Utils.readFile(GPU_MAX_FREQ);
if (value != null) return Utils.stringToInt(value);
}
return 0;
}
public static boolean hasGpuMaxFreq() {
if (GPU_MAX_FREQ == null) {
for (String file : GPU_MAX_FREQ_ARRAY)
if (Utils.existFile(file)) GPU_MAX_FREQ = file;
}
return GPU_MAX_FREQ != null;
}
public static int getGpuCurFreq() {
if (GPU_CUR_FREQ != null) if (Utils.existFile(GPU_CUR_FREQ)) {
String value = Utils.readFile(GPU_CUR_FREQ);
if (value != null) return Utils.stringToInt(value);
}
return 0;
}
public static boolean hasGpuCurFreq() {
if (GPU_CUR_FREQ == null) {
for (String file : GPU_CUR_FREQ_ARRAY)
if (Utils.existFile(file)) GPU_CUR_FREQ = file;
}
return GPU_CUR_FREQ != null;
}
public static boolean hasGpuControl() {
for (String[] files : GPU_ARRAY)
for (String file : files) if (Utils.existFile(file)) return true;
return false;
}
}
| GPU: Fix Adreno Idler taking 1/0 or y/n
per https://github.com/yoinx/kernel_adiutor/issues/70
Signed-off-by: Felipe Leon <[email protected]>
| app/src/main/java/com/grarak/kerneladiutor/utils/kernel/GPU.java | GPU: Fix Adreno Idler taking 1/0 or y/n | <ide><path>pp/src/main/java/com/grarak/kerneladiutor/utils/kernel/GPU.java
<ide> }
<ide>
<ide> public static void activateAdrenoIdler(boolean active, Context context) {
<del> Control.runCommand(active ? "Y" : "N", ADRENO_IDLER_ACTIVATE, Control.CommandType.GENERIC, context);
<add> if (Utils.isLetter(Utils.readFile(ADRENO_IDLER_ACTIVATE))) {
<add> Control.runCommand(active ? "Y" : "N", ADRENO_IDLER_ACTIVATE, Control.CommandType.GENERIC, context);
<add> } else {
<add> Control.runCommand(active ? "1" : "0", ADRENO_IDLER_ACTIVATE, Control.CommandType.GENERIC, context);
<add> }
<ide> }
<ide>
<ide> public static boolean isAdrenoIdlerActive() {
<del> return Utils.readFile(ADRENO_IDLER_ACTIVATE).equals("Y");
<add> return Utils.readFile(ADRENO_IDLER_ACTIVATE).equals(Utils.isLetter(Utils.readFile(ADRENO_IDLER_ACTIVATE)) ? "Y" :"1");
<ide> }
<ide>
<ide> public static boolean hasAdrenoIdler() { |
|
Java | apache-2.0 | 46885a049dc4fd96a1d78f6d5cf7126f6110192f | 0 | tokee/lucene,tokee/lucene,tokee/lucene,tokee/lucene | package org.apache.lucene.search.payloads;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermPositions;
import org.apache.lucene.search.*;
import org.apache.lucene.search.spans.SpanScorer;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.search.spans.SpanWeight;
import org.apache.lucene.search.spans.TermSpans;
import java.io.IOException;
/**
* Copyright 2004 The Apache Software Foundation
* <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.
*/
/**
* The BoostingTermQuery is very similar to the {@link org.apache.lucene.search.spans.SpanTermQuery} except
* that it factors in the value of the payload located at each of the positions where the
* {@link org.apache.lucene.index.Term} occurs.
* <p>
* In order to take advantage of this, you must override {@link org.apache.lucene.search.Similarity#scorePayload(String, byte[],int,int)}
* which returns 1 by default.
* <p>
* Payload scores are averaged across term occurrences in the document.
*
* @see org.apache.lucene.search.Similarity#scorePayload(String, byte[], int, int)
*/
public class BoostingTermQuery extends SpanTermQuery{
public BoostingTermQuery(Term term) {
super(term);
}
protected Weight createWeight(Searcher searcher) throws IOException {
return new BoostingTermWeight(this, searcher);
}
protected class BoostingTermWeight extends SpanWeight implements Weight {
public BoostingTermWeight(BoostingTermQuery query, Searcher searcher) throws IOException {
super(query, searcher);
}
public Scorer scorer(IndexReader reader) throws IOException {
return new BoostingSpanScorer((TermSpans)query.getSpans(reader), this, similarity,
reader.norms(query.getField()));
}
class BoostingSpanScorer extends SpanScorer {
//TODO: is this the best way to allocate this?
byte[] payload = new byte[256];
private TermPositions positions;
protected float payloadScore;
private int payloadsSeen;
public BoostingSpanScorer(TermSpans spans, Weight weight,
Similarity similarity, byte[] norms) throws IOException {
super(spans, weight, similarity, norms);
positions = spans.getPositions();
}
protected boolean setFreqCurrentDoc() throws IOException {
if (!more) {
return false;
}
doc = spans.doc();
freq = 0.0f;
payloadScore = 0;
payloadsSeen = 0;
Similarity similarity1 = getSimilarity();
while (more && doc == spans.doc()) {
int matchLength = spans.end() - spans.start();
freq += similarity1.sloppyFreq(matchLength);
processPayload(similarity1);
more = spans.next();//this moves positions to the next match in this document
}
return more || (freq != 0);
}
protected void processPayload(Similarity similarity) throws IOException {
if (positions.isPayloadAvailable()) {
payload = positions.getPayload(payload, 0);
payloadScore += similarity.scorePayload(term.field(), payload, 0, positions.getPayloadLength());
payloadsSeen++;
} else {
//zero out the payload?
}
}
public float score() throws IOException {
return super.score() * (payloadsSeen > 0 ? (payloadScore / payloadsSeen) : 1);
}
public Explanation explain(final int doc) throws IOException {
Explanation result = new Explanation();
Explanation nonPayloadExpl = super.explain(doc);
result.addDetail(nonPayloadExpl);
//QUESTION: Is there a wau to avoid this skipTo call? We need to know whether to load the payload or not
Explanation payloadBoost = new Explanation();
result.addDetail(payloadBoost);
/*
if (skipTo(doc) == true) {
processPayload();
}
*/
float avgPayloadScore = (payloadsSeen > 0 ? (payloadScore / payloadsSeen) : 1);
payloadBoost.setValue(avgPayloadScore);
//GSI: I suppose we could toString the payload, but I don't think that would be a good idea
payloadBoost.setDescription("scorePayload(...)");
result.setValue(nonPayloadExpl.getValue() * avgPayloadScore);
result.setDescription("btq, product of:");
return result;
}
}
}
public boolean equals(Object o) {
if (!(o instanceof BoostingTermQuery))
return false;
BoostingTermQuery other = (BoostingTermQuery) o;
return (this.getBoost() == other.getBoost())
&& this.term.equals(other.term);
}
}
| src/java/org/apache/lucene/search/payloads/BoostingTermQuery.java | package org.apache.lucene.search.payloads;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermPositions;
import org.apache.lucene.search.*;
import org.apache.lucene.search.spans.SpanScorer;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.search.spans.SpanWeight;
import org.apache.lucene.search.spans.TermSpans;
import java.io.IOException;
/**
* Copyright 2004 The Apache Software Foundation
* <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.
*/
/**
* The BoostingTermQuery is very similar to the {@link org.apache.lucene.search.spans.SpanTermQuery} except
* that it factors in the value of the payload located at each of the positions where the
* {@link org.apache.lucene.index.Term} occurs.
* <p>
* In order to take advantage of this, you must override {@link org.apache.lucene.search.Similarity#scorePayload(String, byte[],int,int)}
* which returns 1 by default.
* <p>
* Payload scores are averaged across term occurrences in the document.
*
* @see org.apache.lucene.search.Similarity#scorePayload(String, byte[], int, int)
*/
public class BoostingTermQuery extends SpanTermQuery{
public BoostingTermQuery(Term term) {
super(term);
}
protected Weight createWeight(Searcher searcher) throws IOException {
return new BoostingTermWeight(this, searcher);
}
protected class BoostingTermWeight extends SpanWeight implements Weight {
public BoostingTermWeight(BoostingTermQuery query, Searcher searcher) throws IOException {
super(query, searcher);
}
public Scorer scorer(IndexReader reader) throws IOException {
return new BoostingSpanScorer((TermSpans)query.getSpans(reader), this, similarity,
reader.norms(query.getField()));
}
class BoostingSpanScorer extends SpanScorer {
//TODO: is this the best way to allocate this?
byte[] payload = new byte[256];
private TermPositions positions;
protected float payloadScore;
private int payloadsSeen;
public BoostingSpanScorer(TermSpans spans, Weight weight,
Similarity similarity, byte[] norms) throws IOException {
super(spans, weight, similarity, norms);
positions = spans.getPositions();
}
/**
* Go to the next document
*
*/
/*public boolean next() throws IOException {
boolean result = super.next();
//set the payload. super.next() properly increments the term positions
if (result) {
//Load the payloads for all
processPayload();
}
return result;
}
public boolean skipTo(int target) throws IOException {
boolean result = super.skipTo(target);
if (result) {
processPayload();
}
return result;
}*/
protected boolean setFreqCurrentDoc() throws IOException {
if (!more) {
return false;
}
doc = spans.doc();
freq = 0.0f;
payloadScore = 0;
payloadsSeen = 0;
Similarity similarity1 = getSimilarity();
while (more && doc == spans.doc()) {
int matchLength = spans.end() - spans.start();
freq += similarity1.sloppyFreq(matchLength);
processPayload(similarity1);
more = spans.next();//this moves positions to the next match in this document
}
return more || (freq != 0);
}
protected void processPayload(Similarity similarity) throws IOException {
if (positions.isPayloadAvailable()) {
payload = positions.getPayload(payload, 0);
payloadScore += similarity.scorePayload(term.field(), payload, 0, positions.getPayloadLength());
payloadsSeen++;
} else {
//zero out the payload?
}
}
public float score() throws IOException {
return super.score() * (payloadsSeen > 0 ? (payloadScore / payloadsSeen) : 1);
}
public Explanation explain(final int doc) throws IOException {
Explanation result = new Explanation();
Explanation nonPayloadExpl = super.explain(doc);
result.addDetail(nonPayloadExpl);
//QUESTION: Is there a wau to avoid this skipTo call? We need to know whether to load the payload or not
Explanation payloadBoost = new Explanation();
result.addDetail(payloadBoost);
/*
if (skipTo(doc) == true) {
processPayload();
}
*/
float avgPayloadScore = (payloadsSeen > 0 ? (payloadScore / payloadsSeen) : 1);
payloadBoost.setValue(avgPayloadScore);
//GSI: I suppose we could toString the payload, but I don't think that would be a good idea
payloadBoost.setDescription("scorePayload(...)");
result.setValue(nonPayloadExpl.getValue() * avgPayloadScore);
result.setDescription("btq, product of:");
return result;
}
}
}
public boolean equals(Object o) {
if (!(o instanceof BoostingTermQuery))
return false;
BoostingTermQuery other = (BoostingTermQuery) o;
return (this.getBoost() == other.getBoost())
&& this.term.equals(other.term);
}
}
| remove commented out code
git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@603057 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/lucene/search/payloads/BoostingTermQuery.java | remove commented out code | <ide><path>rc/java/org/apache/lucene/search/payloads/BoostingTermQuery.java
<ide>
<ide> }
<ide>
<del> /**
<del> * Go to the next document
<del> *
<del> */
<del> /*public boolean next() throws IOException {
<del>
<del> boolean result = super.next();
<del> //set the payload. super.next() properly increments the term positions
<del> if (result) {
<del> //Load the payloads for all
<del> processPayload();
<del> }
<del>
<del> return result;
<del> }
<del>
<del> public boolean skipTo(int target) throws IOException {
<del> boolean result = super.skipTo(target);
<del>
<del> if (result) {
<del> processPayload();
<del> }
<del>
<del> return result;
<del> }*/
<del>
<ide> protected boolean setFreqCurrentDoc() throws IOException {
<ide> if (!more) {
<ide> return false; |
|
Java | apache-2.0 | f82825db9c673b1786951012a3f13223f6f1d578 | 0 | ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma | /*
* The Gemma project.
*
* Copyright (c) 2006 University of British Columbia
*
* 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 ubic.gemma.model.genome.biosequence;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.CacheMode;
import org.hibernate.Criteria;
import org.hibernate.FlushMode;
import org.hibernate.Hibernate;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import ubic.gemma.model.association.BioSequence2GeneProduct;
import ubic.gemma.model.common.description.DatabaseEntry;
import ubic.gemma.model.common.description.ExternalDatabase;
import ubic.gemma.model.genome.Gene;
import ubic.gemma.model.genome.Taxon;
import ubic.gemma.model.genome.sequenceAnalysis.BlatAssociation;
import ubic.gemma.util.BusinessKey;
/**
* @author pavlidis
* @version $Id$
* @see ubic.gemma.model.genome.biosequence.BioSequence
*/
@Repository
public class BioSequenceDaoImpl extends ubic.gemma.model.genome.biosequence.BioSequenceDaoBase {
private static Log log = LogFactory.getLog( BioSequenceDaoImpl.class.getName() );
@Autowired
public BioSequenceDaoImpl( SessionFactory sessionFactory ) {
super.setSessionFactory( sessionFactory );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#find(ubic.gemma
* .model.genome.biosequence.BioSequence)
*/
@SuppressWarnings("unchecked")
@Override
public BioSequence find( BioSequence bioSequence ) {
BusinessKey.checkValidKey( bioSequence );
try {
Criteria queryObject = BusinessKey.createQueryObject( this.getSession( false ), bioSequence );
/*
* this initially matches on name and taxon only.
*/
java.util.List results = queryObject.list();
Object result = null;
if ( results != null ) {
if ( results.size() > 1 ) {
debug( bioSequence, results );
// Try to find the best match. See BusinessKey for more
// explanation of why this is needed.
BioSequence match = null;
for ( BioSequence res : ( Collection<BioSequence> ) results ) {
if ( res.equals( bioSequence ) ) {
if ( match != null ) {
log.warn( "More than one sequence in the database matches " + bioSequence
+ ", returning arbitrary match: " + match );
break;
}
match = res;
}
}
return match;
} else if ( results.size() == 1 ) {
result = results.iterator().next();
}
}
return ( BioSequence ) result;
} catch ( org.hibernate.HibernateException ex ) {
throw super.convertHibernateAccessException( ex );
}
}
/*
* (non-Javadoc)
*
* @seeubic.gemma.model.genome.biosequence.BioSequenceDaoBase#findByAccession (ubic.gemma.model.common.description.
* DatabaseEntry)
*/
@SuppressWarnings("unchecked")
@Override
public BioSequence findByAccession( DatabaseEntry databaseEntry ) {
BusinessKey.checkValidKey( databaseEntry );
String queryString = "";
List<BioSequence> results = null;
if ( databaseEntry.getId() != null ) {
queryString = "select b from BioSequenceImpl b inner join fetch b.sequenceDatabaseEntry d inner join fetch d.externalDatabase e where d=:dbe";
results = this.getHibernateTemplate().findByNamedParam( queryString, "dbe", databaseEntry );
} else {
queryString = "select b from BioSequenceImpl b inner join fetch b.sequenceDatabaseEntry d "
+ "inner join fetch d.externalDatabase e where d.accession = :acc and e.name = :dbname";
results = this.getHibernateTemplate().findByNamedParam( queryString, new String[] { "acc", "dbname" },
new Object[] { databaseEntry.getAccession(), databaseEntry.getExternalDatabase().getName() } );
}
if ( results.size() > 1 ) {
debug( null, results );
log.warn( "More than one instance of '" + BioSequence.class.getName()
+ "' was found when executing query for accession=" + databaseEntry.getAccession() );
// favor the one with name matching the accession.
for ( Object object : results ) {
BioSequence bs = ( BioSequence ) object;
if ( bs.getName().equals( databaseEntry.getAccession() ) ) {
return bs;
}
}
log.error( "No biosequence really matches " + databaseEntry.getAccession() );
return null;
} else if ( results.size() == 1 ) {
return results.iterator().next();
} else {
return null;
}
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#findOrCreate(ubic
* .gemma.model.genome.biosequence.BioSequence )
*/
@Override
public BioSequence findOrCreate( BioSequence bioSequence ) {
BioSequence existingBioSequence = this.find( bioSequence );
if ( existingBioSequence != null ) {
return existingBioSequence;
}
if ( log.isDebugEnabled() ) log.debug( "Creating new: " + bioSequence );
return create( bioSequence );
}
@Override
protected Integer handleCountAll() throws Exception {
final String query = "select count(*) from BioSequenceImpl";
return ( ( Long ) getHibernateTemplate().find( query ).iterator().next() ).intValue();
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#handleGetGenesByName (java.lang.String)
*/
@SuppressWarnings("unchecked")
@Override
protected Map<Gene, Collection<BioSequence>> handleFindByGenes( Collection<Gene> genes ) throws Exception {
if ( genes == null || genes.isEmpty() ) return new HashMap<Gene, Collection<BioSequence>>();
Map<Gene, Collection<BioSequence>> results = new HashMap<Gene, Collection<BioSequence>>();
int batchsize = 500;
if ( genes.size() <= batchsize ) {
findByGenesBatch( genes, results );
return results;
}
Collection<Gene> batch = new HashSet<Gene>();
for ( Gene gene : genes ) {
batch.add( gene );
if ( batch.size() == batchsize ) {
findByGenesBatch( genes, results );
batch.clear();
}
}
if ( !batch.isEmpty() ) {
findByGenesBatch( genes, results );
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected Collection<BioSequence> handleFindByName( String name ) throws Exception {
if ( name == null ) return null;
final String query = "from BioSequenceImpl b where b.name = :name";
return getHibernateTemplate().findByNamedParam( query, "name", name );
}
/*
* (non-Javadoc)
*
* @seeubic.gemma.model.genome.biosequence.BioSequenceDaoBase# handleGetGenesByAccession(java.lang.String)
*/
@SuppressWarnings("unchecked")
@Override
protected Collection handleGetGenesByAccession( String search ) throws Exception {
final String queryString = "select distinct gene from GeneImpl as gene inner join gene.products gp, BioSequence2GeneProductImpl as bs2gp"
+ " inner join bs2gp.bioSequence bs "
+ "inner join bs.sequenceDatabaseEntry de where gp=bs2gp.geneProduct " + " and de.accession = :search ";
return getHibernateTemplate().findByNamedParam( queryString, "search", search );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#handleGetGenesByName (java.lang.String)
*/
@SuppressWarnings("unchecked")
@Override
protected Collection handleGetGenesByName( String search ) throws Exception {
Collection<Gene> genes = null;
final String queryString = "select distinct gene from GeneImpl as gene inner join gene.products gp, BioSequence2GeneProductImpl as bs2gp where gp=bs2gp.geneProduct "
+ " and bs2gp.bioSequence.name like :search ";
try {
org.hibernate.Query queryObject = super.getSession().createQuery( queryString );
queryObject.setString( "search", search );
genes = queryObject.list();
} catch ( org.hibernate.HibernateException ex ) {
throw super.convertHibernateAccessException( ex );
}
return genes;
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#handleLoad(java .util.Collection)
*/
@SuppressWarnings("unchecked")
@Override
protected Collection handleLoad( Collection ids ) throws Exception {
final String queryString = "select distinct bs from BioSequenceImpl bs where bs.id in (:ids)";
return getHibernateTemplate().findByNamedParam( queryString, "ids", ids );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#handleThaw(ubic
* .gemma.model.genome.biosequence.BioSequence )
*/
@Override
protected BioSequence handleThaw( final BioSequence bioSequence ) throws Exception {
if ( bioSequence == null ) return null;
if ( bioSequence.getId() == null ) return bioSequence;
List<?> res = this
.getHibernateTemplate()
.findByNamedParam(
"select b from BioSequenceImpl b "
+ " left join fetch b.taxon tax left join fetch tax.parentTaxon left join fetch b.sequenceDatabaseEntry s "
+ " left join fetch s.externalDatabase"
+ " left join fetch b.bioSequence2GeneProduct bs2gp "
+ " left join fetch bs2gp.geneProduct gp left join fetch gp.gene g"
+ " left join fetch g.aliases left join fetch g.accessions where b.id=:bid", "bid",
bioSequence.getId() );
BioSequence thawedBioSequence = ( BioSequence ) res.iterator().next();
return thawedBioSequence;
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#handleThaw(java .util.Collection)
*/
@Override
protected void handleThaw( final Collection<BioSequence> bioSequences ) throws Exception {
doThaw( bioSequences, true );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#handleThaw(java .util.Collection)
*/
@Override
protected void handleThawLite( final Collection<BioSequence> bioSequences ) throws Exception {
doThaw( bioSequences, false );
}
/**
* @param results
*/
private void debug( BioSequence query, List<BioSequence> results ) {
StringBuilder sb = new StringBuilder();
sb.append( "\nMultiple BioSequences found matching query:\n" );
if ( query != null ) {
sb.append( "\tQuery: ID=" + query.getId() + " Name=" + query.getName() );
if ( StringUtils.isNotBlank( query.getSequence() ) )
sb.append( " Sequence=" + StringUtils.abbreviate( query.getSequence(), 10 ) );
if ( query.getSequenceDatabaseEntry() != null )
sb.append( " acc=" + query.getSequenceDatabaseEntry().getAccession() );
sb.append( "\n" );
}
for ( Object object : results ) {
BioSequence entity = ( BioSequence ) object;
sb.append( "\tMatch: ID=" + entity.getId() + " Name=" + entity.getName() );
if ( StringUtils.isNotBlank( entity.getSequence() ) )
sb.append( " Sequence=" + StringUtils.abbreviate( entity.getSequence(), 10 ) );
if ( entity.getSequenceDatabaseEntry() != null )
sb.append( " acc=" + entity.getSequenceDatabaseEntry().getAccession() );
sb.append( "\n" );
}
if ( log.isDebugEnabled() ) log.debug( sb.toString() );
}
/**
* @param bioSequences
* @param deep
*/
private void doThaw( final Collection<BioSequence> bioSequences, final boolean deep ) {
if ( bioSequences == null || bioSequences.size() == 0 ) return;
HibernateTemplate template = this.getHibernateTemplate();
Session session = template.getSessionFactory().openSession();
for ( BioSequence bioSequence : bioSequences ) {
session.lock(bioSequence, LockMode.NONE); // re-attach object to session
bioSequence.getType();
ExternalDatabase extDB = bioSequence.getTaxon().getExternalDatabase();
if (extDB != null) {
session.lock(extDB, LockMode.NONE);
extDB.getName();
}
bioSequence.getTaxon().getParentTaxon();
DatabaseEntry dbEntry = bioSequence.getSequenceDatabaseEntry();
if ( dbEntry != null ) {
extDB = dbEntry.getExternalDatabase();
if (extDB != null) {
session.lock(extDB, LockMode.NONE);
extDB.getName();
}
}
}
session.close();
}
// templ.executeWithNativeSession( new org.springframework.orm.hibernate3.HibernateCallback<Object>() {
// public Object doInHibernate( org.hibernate.Session session ) throws org.hibernate.HibernateException {
// FlushMode oldFlushMode = session.getFlushMode();
// CacheMode oldCacheMode = session.getCacheMode();
// session.setCacheMode( CacheMode.IGNORE ); // Don't hit the
// // secondary
// // cache
// session.setFlushMode( FlushMode.MANUAL ); // We're
// // READ-ONLY so
// // this is okay.
// int count = 0;
// long lastTime = 0;
// for ( BioSequence bioSequence : bioSequences ) {
// session.lock( bioSequence, LockMode.NONE );
// Hibernate.initialize( bioSequence );
//
// if ( deep ) {
// bioSequence.getTaxon();
// bioSequence.getTaxon().getExternalDatabase();
// Hibernate.initialize( bioSequence.getBioSequence2GeneProduct() );
// for ( BioSequence2GeneProduct bs2gp : bioSequence.getBioSequence2GeneProduct() ) {
// Hibernate.initialize( bs2gp.getGeneProduct() );
// if ( bs2gp instanceof BlatAssociation ) {
// Hibernate.initialize( ( ( BlatAssociation ) bs2gp ).getBlatResult() );
// }
// }
// }
//
// DatabaseEntry dbEntry = bioSequence.getSequenceDatabaseEntry();
// if ( dbEntry != null ) {
// session.lock( dbEntry, LockMode.NONE );
// Hibernate.initialize( dbEntry );
// session.lock( dbEntry.getExternalDatabase(), LockMode.NONE );
// Hibernate.initialize( dbEntry.getExternalDatabase() );
// session.evict( dbEntry );
// session.evict( dbEntry.getExternalDatabase() );
// }
//
// if ( ++count % 2000 == 0 ) {
// if ( timer.getTime() - lastTime > 10000 ) {
// log.info( "Thawed " + count + " sequences ..." );
// lastTime = timer.getTime();
// }
// session.clear();
// }
// }
//
// session.clear();
// session.setFlushMode( oldFlushMode );
// session.setCacheMode( oldCacheMode );
//
// return null;
// }
// } );
/**
* @param genes
* @param results
*/
private void findByGenesBatch( Collection<Gene> genes, Map<Gene, Collection<BioSequence>> results ) {
final String queryString = "select distinct gene,bs from GeneImpl gene inner join fetch gene.products ggp,"
+ " BioSequenceImpl bs inner join bs.bioSequence2GeneProduct bs2gp inner join bs2gp.geneProduct bsgp"
+ " where ggp=bsgp and gene in (:genes)";
List<Object[]> qr = getHibernateTemplate().findByNamedParam( queryString, "genes", genes );
for ( Object[] oa : qr ) {
Gene g = ( Gene ) oa[0];
BioSequence b = ( BioSequence ) oa[1];
if ( !results.containsKey( g ) ) {
results.put( g, new HashSet<BioSequence>() );
}
results.get( g ).add( b );
}
}
}
| gemma-mda/src/main/java/ubic/gemma/model/genome/biosequence/BioSequenceDaoImpl.java | /*
* The Gemma project.
*
* Copyright (c) 2006 University of British Columbia
*
* 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 ubic.gemma.model.genome.biosequence;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.CacheMode;
import org.hibernate.Criteria;
import org.hibernate.FlushMode;
import org.hibernate.Hibernate;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import ubic.gemma.model.association.BioSequence2GeneProduct;
import ubic.gemma.model.common.description.DatabaseEntry;
import ubic.gemma.model.common.description.ExternalDatabase;
import ubic.gemma.model.genome.Gene;
import ubic.gemma.model.genome.Taxon;
import ubic.gemma.model.genome.sequenceAnalysis.BlatAssociation;
import ubic.gemma.util.BusinessKey;
/**
* @author pavlidis
* @version $Id$
* @see ubic.gemma.model.genome.biosequence.BioSequence
*/
@Repository
public class BioSequenceDaoImpl extends ubic.gemma.model.genome.biosequence.BioSequenceDaoBase {
private static Log log = LogFactory.getLog( BioSequenceDaoImpl.class.getName() );
@Autowired
public BioSequenceDaoImpl( SessionFactory sessionFactory ) {
super.setSessionFactory( sessionFactory );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#find(ubic.gemma
* .model.genome.biosequence.BioSequence)
*/
@SuppressWarnings("unchecked")
@Override
public BioSequence find( BioSequence bioSequence ) {
BusinessKey.checkValidKey( bioSequence );
try {
Criteria queryObject = BusinessKey.createQueryObject( this.getSession( false ), bioSequence );
/*
* this initially matches on name and taxon only.
*/
java.util.List results = queryObject.list();
Object result = null;
if ( results != null ) {
if ( results.size() > 1 ) {
debug( bioSequence, results );
// Try to find the best match. See BusinessKey for more
// explanation of why this is needed.
BioSequence match = null;
for ( BioSequence res : ( Collection<BioSequence> ) results ) {
if ( res.equals( bioSequence ) ) {
if ( match != null ) {
log.warn( "More than one sequence in the database matches " + bioSequence
+ ", returning arbitrary match: " + match );
break;
}
match = res;
}
}
return match;
} else if ( results.size() == 1 ) {
result = results.iterator().next();
}
}
return ( BioSequence ) result;
} catch ( org.hibernate.HibernateException ex ) {
throw super.convertHibernateAccessException( ex );
}
}
/*
* (non-Javadoc)
*
* @seeubic.gemma.model.genome.biosequence.BioSequenceDaoBase#findByAccession (ubic.gemma.model.common.description.
* DatabaseEntry)
*/
@SuppressWarnings("unchecked")
@Override
public BioSequence findByAccession( DatabaseEntry databaseEntry ) {
BusinessKey.checkValidKey( databaseEntry );
String queryString = "";
List<BioSequence> results = null;
if ( databaseEntry.getId() != null ) {
queryString = "select b from BioSequenceImpl b inner join fetch b.sequenceDatabaseEntry d inner join fetch d.externalDatabase e where d=:dbe";
results = this.getHibernateTemplate().findByNamedParam( queryString, "dbe", databaseEntry );
} else {
queryString = "select b from BioSequenceImpl b inner join fetch b.sequenceDatabaseEntry d "
+ "inner join fetch d.externalDatabase e where d.accession = :acc and e.name = :dbname";
results = this.getHibernateTemplate().findByNamedParam( queryString, new String[] { "acc", "dbname" },
new Object[] { databaseEntry.getAccession(), databaseEntry.getExternalDatabase().getName() } );
}
if ( results.size() > 1 ) {
debug( null, results );
log.warn( "More than one instance of '" + BioSequence.class.getName()
+ "' was found when executing query for accession=" + databaseEntry.getAccession() );
// favor the one with name matching the accession.
for ( Object object : results ) {
BioSequence bs = ( BioSequence ) object;
if ( bs.getName().equals( databaseEntry.getAccession() ) ) {
return bs;
}
}
log.error( "No biosequence really matches " + databaseEntry.getAccession() );
return null;
} else if ( results.size() == 1 ) {
return results.iterator().next();
} else {
return null;
}
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#findOrCreate(ubic
* .gemma.model.genome.biosequence.BioSequence )
*/
@Override
public BioSequence findOrCreate( BioSequence bioSequence ) {
BioSequence existingBioSequence = this.find( bioSequence );
if ( existingBioSequence != null ) {
return existingBioSequence;
}
if ( log.isDebugEnabled() ) log.debug( "Creating new: " + bioSequence );
return create( bioSequence );
}
@Override
protected Integer handleCountAll() throws Exception {
final String query = "select count(*) from BioSequenceImpl";
return ( ( Long ) getHibernateTemplate().find( query ).iterator().next() ).intValue();
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#handleGetGenesByName (java.lang.String)
*/
@SuppressWarnings("unchecked")
@Override
protected Map<Gene, Collection<BioSequence>> handleFindByGenes( Collection<Gene> genes ) throws Exception {
if ( genes == null || genes.isEmpty() ) return new HashMap<Gene, Collection<BioSequence>>();
Map<Gene, Collection<BioSequence>> results = new HashMap<Gene, Collection<BioSequence>>();
int batchsize = 500;
if ( genes.size() <= batchsize ) {
findByGenesBatch( genes, results );
return results;
}
Collection<Gene> batch = new HashSet<Gene>();
for ( Gene gene : genes ) {
batch.add( gene );
if ( batch.size() == batchsize ) {
findByGenesBatch( genes, results );
batch.clear();
}
}
if ( !batch.isEmpty() ) {
findByGenesBatch( genes, results );
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected Collection<BioSequence> handleFindByName( String name ) throws Exception {
if ( name == null ) return null;
final String query = "from BioSequenceImpl b where b.name = :name";
return getHibernateTemplate().findByNamedParam( query, "name", name );
}
/*
* (non-Javadoc)
*
* @seeubic.gemma.model.genome.biosequence.BioSequenceDaoBase# handleGetGenesByAccession(java.lang.String)
*/
@SuppressWarnings("unchecked")
@Override
protected Collection handleGetGenesByAccession( String search ) throws Exception {
final String queryString = "select distinct gene from GeneImpl as gene inner join gene.products gp, BioSequence2GeneProductImpl as bs2gp"
+ " inner join bs2gp.bioSequence bs "
+ "inner join bs.sequenceDatabaseEntry de where gp=bs2gp.geneProduct " + " and de.accession = :search ";
return getHibernateTemplate().findByNamedParam( queryString, "search", search );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#handleGetGenesByName (java.lang.String)
*/
@SuppressWarnings("unchecked")
@Override
protected Collection handleGetGenesByName( String search ) throws Exception {
Collection<Gene> genes = null;
final String queryString = "select distinct gene from GeneImpl as gene inner join gene.products gp, BioSequence2GeneProductImpl as bs2gp where gp=bs2gp.geneProduct "
+ " and bs2gp.bioSequence.name like :search ";
try {
org.hibernate.Query queryObject = super.getSession().createQuery( queryString );
queryObject.setString( "search", search );
genes = queryObject.list();
} catch ( org.hibernate.HibernateException ex ) {
throw super.convertHibernateAccessException( ex );
}
return genes;
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#handleLoad(java .util.Collection)
*/
@SuppressWarnings("unchecked")
@Override
protected Collection handleLoad( Collection ids ) throws Exception {
final String queryString = "select distinct bs from BioSequenceImpl bs where bs.id in (:ids)";
return getHibernateTemplate().findByNamedParam( queryString, "ids", ids );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#handleThaw(ubic
* .gemma.model.genome.biosequence.BioSequence )
*/
@Override
protected BioSequence handleThaw( final BioSequence bioSequence ) throws Exception {
if ( bioSequence == null ) return null;
if ( bioSequence.getId() == null ) return bioSequence;
List<?> res = this
.getHibernateTemplate()
.findByNamedParam(
"select b from BioSequenceImpl b "
+ " left join fetch b.taxon tax left join fetch tax.parentTaxon left join fetch b.sequenceDatabaseEntry s "
+ " left join fetch s.externalDatabase"
+ " left join fetch b.bioSequence2GeneProduct bs2gp "
+ " left join fetch bs2gp.geneProduct gp left join fetch gp.gene g"
+ " left join fetch g.aliases left join fetch g.accessions where b.id=:bid", "bid",
bioSequence.getId() );
BioSequence thawedBioSequence = ( BioSequence ) res.iterator().next();
return thawedBioSequence;
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#handleThaw(java .util.Collection)
*/
@Override
protected void handleThaw( final Collection<BioSequence> bioSequences ) throws Exception {
doThaw( bioSequences, true );
}
/*
* (non-Javadoc)
*
* @see ubic.gemma.model.genome.biosequence.BioSequenceDaoBase#handleThaw(java .util.Collection)
*/
@Override
protected void handleThawLite( final Collection<BioSequence> bioSequences ) throws Exception {
doThaw( bioSequences, false );
}
/**
* @param results
*/
private void debug( BioSequence query, List<BioSequence> results ) {
StringBuilder sb = new StringBuilder();
sb.append( "\nMultiple BioSequences found matching query:\n" );
if ( query != null ) {
sb.append( "\tQuery: ID=" + query.getId() + " Name=" + query.getName() );
if ( StringUtils.isNotBlank( query.getSequence() ) )
sb.append( " Sequence=" + StringUtils.abbreviate( query.getSequence(), 10 ) );
if ( query.getSequenceDatabaseEntry() != null )
sb.append( " acc=" + query.getSequenceDatabaseEntry().getAccession() );
sb.append( "\n" );
}
for ( Object object : results ) {
BioSequence entity = ( BioSequence ) object;
sb.append( "\tMatch: ID=" + entity.getId() + " Name=" + entity.getName() );
if ( StringUtils.isNotBlank( entity.getSequence() ) )
sb.append( " Sequence=" + StringUtils.abbreviate( entity.getSequence(), 10 ) );
if ( entity.getSequenceDatabaseEntry() != null )
sb.append( " acc=" + entity.getSequenceDatabaseEntry().getAccession() );
sb.append( "\n" );
}
if ( log.isDebugEnabled() ) log.debug( sb.toString() );
}
/**
* @param bioSequences
* @param deep
*/
private void doThaw( final Collection<BioSequence> bioSequences, final boolean deep ) {
if ( bioSequences == null || bioSequences.size() == 0 ) return;
HibernateTemplate template = this.getHibernateTemplate();
Session session = template.getSessionFactory().openSession();
for ( BioSequence bioSequence : bioSequences ) {
session.lock(bioSequence, LockMode.NONE); // re-attach object to session
bioSequence.getType();
ExternalDatabase extDB = bioSequence.getTaxon().getExternalDatabase();
if (extDB != null) {
extDB.getName();
}
bioSequence.getTaxon().getParentTaxon();
DatabaseEntry dbEntry = bioSequence.getSequenceDatabaseEntry();
if ( dbEntry != null ) {
extDB = dbEntry.getExternalDatabase();
if (extDB != null) extDB.getName();
}
}
session.close();
}
// templ.executeWithNativeSession( new org.springframework.orm.hibernate3.HibernateCallback<Object>() {
// public Object doInHibernate( org.hibernate.Session session ) throws org.hibernate.HibernateException {
// FlushMode oldFlushMode = session.getFlushMode();
// CacheMode oldCacheMode = session.getCacheMode();
// session.setCacheMode( CacheMode.IGNORE ); // Don't hit the
// // secondary
// // cache
// session.setFlushMode( FlushMode.MANUAL ); // We're
// // READ-ONLY so
// // this is okay.
// int count = 0;
// long lastTime = 0;
// for ( BioSequence bioSequence : bioSequences ) {
// session.lock( bioSequence, LockMode.NONE );
// Hibernate.initialize( bioSequence );
//
// if ( deep ) {
// bioSequence.getTaxon();
// bioSequence.getTaxon().getExternalDatabase();
// Hibernate.initialize( bioSequence.getBioSequence2GeneProduct() );
// for ( BioSequence2GeneProduct bs2gp : bioSequence.getBioSequence2GeneProduct() ) {
// Hibernate.initialize( bs2gp.getGeneProduct() );
// if ( bs2gp instanceof BlatAssociation ) {
// Hibernate.initialize( ( ( BlatAssociation ) bs2gp ).getBlatResult() );
// }
// }
// }
//
// DatabaseEntry dbEntry = bioSequence.getSequenceDatabaseEntry();
// if ( dbEntry != null ) {
// session.lock( dbEntry, LockMode.NONE );
// Hibernate.initialize( dbEntry );
// session.lock( dbEntry.getExternalDatabase(), LockMode.NONE );
// Hibernate.initialize( dbEntry.getExternalDatabase() );
// session.evict( dbEntry );
// session.evict( dbEntry.getExternalDatabase() );
// }
//
// if ( ++count % 2000 == 0 ) {
// if ( timer.getTime() - lastTime > 10000 ) {
// log.info( "Thawed " + count + " sequences ..." );
// lastTime = timer.getTime();
// }
// session.clear();
// }
// }
//
// session.clear();
// session.setFlushMode( oldFlushMode );
// session.setCacheMode( oldCacheMode );
//
// return null;
// }
// } );
/**
* @param genes
* @param results
*/
private void findByGenesBatch( Collection<Gene> genes, Map<Gene, Collection<BioSequence>> results ) {
final String queryString = "select distinct gene,bs from GeneImpl gene inner join fetch gene.products ggp,"
+ " BioSequenceImpl bs inner join bs.bioSequence2GeneProduct bs2gp inner join bs2gp.geneProduct bsgp"
+ " where ggp=bsgp and gene in (:genes)";
List<Object[]> qr = getHibernateTemplate().findByNamedParam( queryString, "genes", genes );
for ( Object[] oa : qr ) {
Gene g = ( Gene ) oa[0];
BioSequence b = ( BioSequence ) oa[1];
if ( !results.containsKey( g ) ) {
results.put( g, new HashSet<BioSequence>() );
}
results.get( g ).add( b );
}
}
}
| and some more tweaking...
| gemma-mda/src/main/java/ubic/gemma/model/genome/biosequence/BioSequenceDaoImpl.java | and some more tweaking... | <ide><path>emma-mda/src/main/java/ubic/gemma/model/genome/biosequence/BioSequenceDaoImpl.java
<ide>
<ide> bioSequence.getType();
<ide> ExternalDatabase extDB = bioSequence.getTaxon().getExternalDatabase();
<del> if (extDB != null) {
<add> if (extDB != null) {
<add> session.lock(extDB, LockMode.NONE);
<ide> extDB.getName();
<ide> }
<ide> bioSequence.getTaxon().getParentTaxon();
<ide>
<ide> DatabaseEntry dbEntry = bioSequence.getSequenceDatabaseEntry();
<ide> if ( dbEntry != null ) {
<del> extDB = dbEntry.getExternalDatabase();
<del> if (extDB != null) extDB.getName();
<add> extDB = dbEntry.getExternalDatabase();
<add> if (extDB != null) {
<add> session.lock(extDB, LockMode.NONE);
<add> extDB.getName();
<add> }
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | cc8c32a41fe33a1847e7822609d4a7a42e8bba9d | 0 | BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH | package de.hu_berlin.informatik.ki.nao.server;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.nio.channels.NotYetConnectedException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.codec.binary.Base64;
/**
* This class handles all debug and connection stuff.
* Manager will register itself here and all communication is done through this
* class.
* @author thomas
*/
public class MessageServer
{
/**
* When using this lock you should have understood the meaning of the
* following caller-graph.<br>
* <b>Be warned an don't produce dead-locks!</b>
*
* <pre>
*
* +-------------+
* |MessageServer|
* +-------------+ +-----+
* |^ +-| GUI |
* || | +-----+
* || | | GUI |
* || | +-----+
* v| | ^
* +--------+ <-------+ |
* |ManagerX| -------------+
* +--------+
*
* </pre>
*/
private final Lock LISTENER_LOCK = new ReentrantLock();
public final static String STRING_ENCODING = "ISO-8859-15";
private InetSocketAddress address;
private Socket serverSocket;
private Thread senderThread;
private Thread receiverThread;
private Thread periodicExecutionThread;
private long updateIntervall = 33;
private List<CommandSender> listeners;
private BlockingQueue<SingleExecEntry> commandRequestQueue;
private BlockingQueue<SingleExecEntry> callbackQueue;
private IMessageServerParent parent;
private long receivedBytes;
private long sentBytes;
private Base64 base64 = new Base64();
public MessageServer()
{
this(null);
}
public MessageServer(IMessageServerParent parent)
{
serverSocket = null;
this.parent = parent;
this.receivedBytes = 0;
this.sentBytes = 0;
this.listeners = new LinkedList<CommandSender>();
this.commandRequestQueue = new LinkedBlockingQueue<SingleExecEntry>();
this.callbackQueue = new LinkedBlockingQueue<SingleExecEntry>();
senderThread = new Thread(new Runnable()
{
public void run()
{
try
{
sendLoop();
}
catch (InterruptedException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, "thread was interupted", ex);
}
}
});
}
public void connect(String host, int port) throws IOException
{
if (serverSocket != null && serverSocket.isConnected())
{
serverSocket.close();
}
// define the threads
receiverThread = new Thread(new Runnable()
{
public void run()
{
try
{
receiveLoop();
}
catch (InterruptedException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, "thread was interupted", ex);
}
catch(SocketException ex)
{
// ignore
}
catch (IOException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, "socket read failed", ex);
}
}
});
periodicExecutionThread = new Thread(new Runnable()
{
public void run()
{
periodicExecution();
}
});
address = new InetSocketAddress(host, port);
serverSocket = new Socket();
serverSocket.connect(address, 1000);
if (parent != null)
{
parent.showConnected(true);
}
// clean all old stuff in the pipe
while (!serverSocket.isClosed() && serverSocket.getInputStream().available() > 0)
{
serverSocket.getInputStream().read();
// nothing
}
// start threads
if(!senderThread.isAlive())
{
// start sender only once
senderThread.start();
}
periodicExecutionThread.start();
receiverThread.start();
}//end connect
public void disconnect()
{
if(!isConnected())
{
// nothing to do
return;
}
try
{
// disconnect
serverSocket.close();
serverSocket = null;
// wait until no new commands are inserted
periodicExecutionThread.join();
// clear commands in order to shutdown
commandRequestQueue.clear();
// wait until rest of the thread are settled
receiverThread.join();
// clear queues and send remaining error messages
for (SingleExecEntry entry : callbackQueue)
{
if (entry.sender != null)
{
entry.sender.handleError(-2);
}
}
callbackQueue.clear();
}
catch (InterruptedException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
serverSocket = null;
// notifiy disconnect
if (parent != null)
{
parent.showConnected(false);
} // end if
}
}//end disconnect
public InetSocketAddress getAddress()
{
return address;
}//end getAddress
/** Return whether RC is connected to a robot */
public boolean isConnected()
{
return serverSocket != null && serverSocket.isConnected();
}//end isConnected
/**
* Add a {@link CommandSender} to the repeating schedule.
* A {@link CommandSender} will not be added twice.
* @param commandSender
*/
public void addCommandSender(CommandSender commandSender)
{
LISTENER_LOCK.lock();
try
{
if (!listeners.contains(commandSender))
{
listeners.add(commandSender);
}
}
finally
{
LISTENER_LOCK.unlock();
}
}//end addCommandSender
/**
* Remove a {@link CommandSender} from the repeating schedule.
* @param commandSender
*/
public void removeCommandSender(CommandSender commandSender)
{
LISTENER_LOCK.lock();
try
{
listeners.remove(commandSender);
}
finally
{
LISTENER_LOCK.unlock();
}
}//end removeCommandSender
/**
* Schedule a single command for execution. It is not guarantied when it
* will be executed but the {@link CommandSender} will be notfied using the
* right command as argument.
*
* @param commandSender The command sender responsible for this command.
* @param command Instead of using {@link CommandSender#getCurrentCommand()}
* this command is used.
*
* @throws NotYetConnectedException is thrown if the server is not connected
*/
public void executeSingleCommand(CommandSender commandSender, Command command)
throws NotYetConnectedException
{
if (!isConnected())
{
throw new NotYetConnectedException();
}
SingleExecEntry e = new SingleExecEntry();
e.command = command;
e.sender = commandSender;
try
{
commandRequestQueue.put(e);
}
catch (InterruptedException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
}
}//end executeSingleCommand
// send-receive-periodicExecution //
public void receiveLoop() throws InterruptedException, IOException
{
byte[] buf = new byte[1024*256];
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
while (isConnected())
{
// reader answer
int received = serverSocket.getInputStream().read(buf);
receivedBytes += received;
int offset = 0;
for (int i = 0; i < received; i++)
{
// look for the end of the message
if (buf[i] == 0)
{
byteStream.write(buf, offset, i-offset);
decodeAndHandleMessage(byteStream.toByteArray());
byteStream.reset();
offset = i+1;
}
}//end for
if(offset < received)
{
byteStream.write(buf, offset, received-offset);
}
try
{
Thread.sleep(1);
}
catch(InterruptedException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
}
}//end while
}//end receiveLoop
public void sendLoop() throws InterruptedException
{
while (true)
{
SingleExecEntry entry = commandRequestQueue.poll(1, TimeUnit.SECONDS);
if(entry == null)
{
// fire an empty message to check the connection
try
{
if(isConnected())
{
byte[] bytes = new byte[] {13};
serverSocket.getOutputStream().write(bytes);
}
}
catch (SocketException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
disconnect();
}
catch (IOException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
disconnect();
}
}
else
{
callbackQueue.put(entry);
Command c = entry.command;
StringBuilder buffer = new StringBuilder();
buffer.append("+").append(c.getName());
if (c.getArguments() != null)
{
for (Map.Entry<String, byte[]> e : c.getArguments().entrySet())
{
boolean hasArg = e.getValue() != null;
buffer.append(" ");
if (hasArg)
{
buffer.append("+");
}
buffer.append(e.getKey());
if (hasArg)
{
buffer.append(" ");
buffer.append(new String(Base64.encodeBase64(e.getValue())));
}
}
}
buffer.append("\n");
try
{
if(isConnected())
{
byte[] bytes = buffer.toString().getBytes();
serverSocket.getOutputStream().write(bytes);
sentBytes += bytes.length;
}
}
catch (IOException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
disconnect();
}
}
}
}
private void decodeAndHandleMessage(byte[] bytes) throws InterruptedException
{
SingleExecEntry entry = callbackQueue.take();
//byte[] decoded = Base64.decodeBase64(bytes);
byte[] decoded = base64.decode(bytes);
if (entry != null && entry.sender != null)
{
entry.sender.handleResponse(decoded, entry.command);
}
}//end decodeAndHandleMessage
public void periodicExecution()
{
while (isConnected())
{
try
{
try
{
long startTime = System.currentTimeMillis();
// do not send if the robot is still busy
while(isConnected() && callbackQueue.size() > 0)
{
Thread.yield();
}
sendPeriodicCommands();
long stopTime = System.currentTimeMillis();
long diff = updateIntervall - (stopTime - startTime);
long wait = Math.max(0, diff);
if (wait > 0)
{
Thread.sleep(wait);
}
}
catch (InterruptedException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, "thread was interupted", ex);
}
}
catch (IOException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
}
} // while(isActive)
}//end sendLoop
public void sendPeriodicCommands() throws IOException
{
// periodic execution //
// copy the listeners
LinkedList<CommandSender> copyListener = new LinkedList<CommandSender>();
LISTENER_LOCK.lock();
try
{
copyListener.addAll(listeners);
}
finally
{
LISTENER_LOCK.unlock();
}
// check each command sender and perform a request
for (CommandSender sender : copyListener)
{
try
{
// send command and get generated ID
SingleExecEntry e = new SingleExecEntry();
e.command = sender.getCurrentCommand();
e.sender = sender;
commandRequestQueue.put(e);
}
catch (InterruptedException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE,
"interrupted in periodic command execution", ex);
}
} // end for each listenerF
}//end sendPeriodicCommands
private class SingleExecEntry
{
public CommandSender sender;
public Command command;
}//end SingleExecEntry
public List<CommandSender> getListeners()
{
return listeners;
}//end getListeners
public long getReceivedBytes()
{
return receivedBytes;
}//end getReceivedBytes
public long getSentBytes()
{
return sentBytes;
}//end getSentBytes
public class CommandSenderWithByteCount implements CommandSender
{
CommandSender commandSender;
public CommandSenderWithByteCount(CommandSender commandSender)
{
this.commandSender = commandSender;
}
public Command getCurrentCommand() {
return this.commandSender.getCurrentCommand();
}
public void handleError(int code) {
this.commandSender.handleError(code);
}
public void handleResponse(byte[] result, Command originalCommand) {
this.commandSender.handleResponse(result, originalCommand);
}
}//end class CommandSenderWithByteCount
}//end class MessageServer
| RobotControl/RobotConnector/src/de/hu_berlin/informatik/ki/nao/server/MessageServer.java | package de.hu_berlin.informatik.ki.nao.server;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.nio.channels.NotYetConnectedException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.codec.binary.Base64;
/**
* This class handles all debug and connection stuff.
* Manager will register itself here and all communication is done through this
* class.
* @author thomas
*/
public class MessageServer
{
/**
* When using this lock you should have understood the meaning of the
* following caller-graph.<br>
* <b>Be warned an don't produce dead-locks!</b>
*
* <pre>
*
* +-------------+
* |MessageServer|
* +-------------+ +-----+
* |^ +-| GUI |
* || | +-----+
* || | | GUI |
* || | +-----+
* v| | ^
* +--------+ <-------+ |
* |ManagerX| -------------+
* +--------+
*
* </pre>
*/
private final Lock LISTENER_LOCK = new ReentrantLock();
public final static String STRING_ENCODING = "ISO-8859-15";
private InetSocketAddress address;
private Socket serverSocket;
private Thread senderThread;
private Thread receiverThread;
private Thread periodicExecutionThread;
private long updateIntervall = 60;
private final long graceTime = 10;
private final long maxGraceTime = 500;
private List<CommandSender> listeners;
private BlockingQueue<SingleExecEntry> commandRequestQueue;
private BlockingQueue<SingleExecEntry> callbackQueue;
private IMessageServerParent parent;
private long receivedBytes;
private long sentBytes;
private Base64 base64 = new Base64();
public MessageServer()
{
this(null);
}
public MessageServer(IMessageServerParent parent)
{
serverSocket = null;
this.parent = parent;
this.receivedBytes = 0;
this.sentBytes = 0;
this.listeners = new LinkedList<CommandSender>();
this.commandRequestQueue = new LinkedBlockingQueue<SingleExecEntry>();
this.callbackQueue = new LinkedBlockingQueue<SingleExecEntry>();
senderThread = new Thread(new Runnable()
{
public void run()
{
try
{
sendLoop();
}
catch (InterruptedException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, "thread was interupted", ex);
}
}
});
}
public void connect(String host, int port) throws IOException
{
if (serverSocket != null && serverSocket.isConnected())
{
serverSocket.close();
}
// define the threads
receiverThread = new Thread(new Runnable()
{
public void run()
{
try
{
receiveLoop();
}
catch (InterruptedException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, "thread was interupted", ex);
}
catch(SocketException ex)
{
// ignore
}
catch (IOException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, "socket read failed", ex);
}
}
});
periodicExecutionThread = new Thread(new Runnable()
{
public void run()
{
periodicExecution();
}
});
address = new InetSocketAddress(host, port);
serverSocket = new Socket();
serverSocket.connect(address, 1000);
if (parent != null)
{
parent.showConnected(true);
}
// clean all old stuff in the pipe
while (!serverSocket.isClosed() && serverSocket.getInputStream().available() > 0)
{
serverSocket.getInputStream().read();
// nothing
}
// start threads
if(!senderThread.isAlive())
{
// start sender only once
senderThread.start();
}
periodicExecutionThread.start();
receiverThread.start();
}//end connect
public void disconnect()
{
if(!isConnected())
{
// nothing to do
return;
}
try
{
// disconnect
serverSocket.close();
serverSocket = null;
// wait until no new commands are inserted
periodicExecutionThread.join();
// clear commands in order to shutdown
commandRequestQueue.clear();
// wait until rest of the thread are settled
receiverThread.join();
// clear queues and send remaining error messages
for (SingleExecEntry entry : callbackQueue)
{
if (entry.sender != null)
{
entry.sender.handleError(-2);
}
}
callbackQueue.clear();
}
catch (InterruptedException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
serverSocket = null;
// notifiy disconnect
if (parent != null)
{
parent.showConnected(false);
} // end if
}
}//end disconnect
public InetSocketAddress getAddress()
{
return address;
}//end getAddress
/** Return whether RC is connected to a robot */
public boolean isConnected()
{
return serverSocket != null && serverSocket.isConnected();
}//end isConnected
/**
* Add a {@link CommandSender} to the repeating schedule.
* A {@link CommandSender} will not be added twice.
* @param commandSender
*/
public void addCommandSender(CommandSender commandSender)
{
LISTENER_LOCK.lock();
try
{
if (!listeners.contains(commandSender))
{
listeners.add(commandSender);
}
}
finally
{
LISTENER_LOCK.unlock();
}
}//end addCommandSender
/**
* Remove a {@link CommandSender} from the repeating schedule.
* @param commandSender
*/
public void removeCommandSender(CommandSender commandSender)
{
LISTENER_LOCK.lock();
try
{
listeners.remove(commandSender);
}
finally
{
LISTENER_LOCK.unlock();
}
}//end removeCommandSender
/**
* Schedule a single command for execution. It is not guarantied when it
* will be executed but the {@link CommandSender} will be notfied using the
* right command as argument.
*
* @param commandSender The command sender responsible for this command.
* @param command Instead of using {@link CommandSender#getCurrentCommand()}
* this command is used.
*
* @throws NotYetConnectedException is thrown if the server is not connected
*/
public void executeSingleCommand(CommandSender commandSender, Command command)
throws NotYetConnectedException
{
if (!isConnected())
{
throw new NotYetConnectedException();
}
SingleExecEntry e = new SingleExecEntry();
e.command = command;
e.sender = commandSender;
try
{
commandRequestQueue.put(e);
}
catch (InterruptedException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
}
}//end executeSingleCommand
// send-receive-periodicExecution //
public void receiveLoop() throws InterruptedException, IOException
{
byte[] buf = new byte[1024*256];
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
while (isConnected())
{
// reader answer
int received = serverSocket.getInputStream().read(buf);
receivedBytes += received;
int offset = 0;
for (int i = 0; i < received; i++)
{
// look for the end of the message
if (buf[i] == 0)
{
byteStream.write(buf, offset, i-offset);
decodeAndHandleMessage(byteStream.toByteArray());
byteStream.reset();
offset = i+1;
}
}//end for
if(offset < received)
{
byteStream.write(buf, offset, received-offset);
}
try
{
Thread.sleep(1);
}
catch(InterruptedException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
}
}//end while
}//end receiveLoop
public void sendLoop() throws InterruptedException
{
while (true)
{
SingleExecEntry entry = commandRequestQueue.take();
callbackQueue.put(entry);
Command c = entry.command;
StringBuilder buffer = new StringBuilder();
buffer.append("+").append(c.getName());
if (c.getArguments() != null)
{
for (Map.Entry<String, byte[]> e : c.getArguments().entrySet())
{
boolean hasArg = e.getValue() != null;
buffer.append(" ");
if (hasArg)
{
buffer.append("+");
}
buffer.append(e.getKey());
if (hasArg)
{
buffer.append(" ");
buffer.append(new String(Base64.encodeBase64(e.getValue())));
}
}
}
buffer.append("\n");
try
{
if(isConnected())
{
byte[] bytes = buffer.toString().getBytes();
serverSocket.getOutputStream().write(bytes);
sentBytes += bytes.length;
}
}
catch (IOException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
disconnect();
}
}
}
private void decodeAndHandleMessage(byte[] bytes) throws InterruptedException
{
SingleExecEntry entry = callbackQueue.take();
//byte[] decoded = Base64.decodeBase64(bytes);
byte[] decoded = base64.decode(bytes);
if (entry != null && entry.sender != null)
{
entry.sender.handleResponse(decoded, entry.command);
}
}//end decodeAndHandleMessage
public void periodicExecution()
{
while (isConnected())
{
try
{
try
{
long startTime = System.currentTimeMillis();
// do not send if the robot is already busy
while(isConnected()
&& callbackQueue.size() > 0
&& (System.currentTimeMillis() - startTime) < maxGraceTime)
{
Thread.sleep(graceTime);
}
sendPeriodicCommands();
long stopTime = System.currentTimeMillis();
long diff = updateIntervall - (stopTime - startTime);
long wait = Math.max(0, diff);
if (wait > 0)
{
Thread.sleep(wait);
}
}
catch (InterruptedException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, "thread was interupted", ex);
}
}
catch (IOException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
}
} // while(isActive)
}//end sendLoop
public void sendPeriodicCommands() throws IOException
{
// periodic execution //
// copy the listeners
LinkedList<CommandSender> copyListener = new LinkedList<CommandSender>();
LISTENER_LOCK.lock();
try
{
copyListener.addAll(listeners);
}
finally
{
LISTENER_LOCK.unlock();
}
// check each command sender and perform a request
for (CommandSender sender : copyListener)
{
try
{
// send command and get generated ID
SingleExecEntry e = new SingleExecEntry();
e.command = sender.getCurrentCommand();
e.sender = sender;
commandRequestQueue.put(e);
}
catch (InterruptedException ex)
{
Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE,
"interrupted in periodic command execution", ex);
}
} // end for each listenerF
}//end sendPeriodicCommands
private class SingleExecEntry
{
public CommandSender sender;
public Command command;
}//end SingleExecEntry
public List<CommandSender> getListeners()
{
return listeners;
}//end getListeners
public long getReceivedBytes()
{
return receivedBytes;
}//end getReceivedBytes
public long getSentBytes()
{
return sentBytes;
}//end getSentBytes
public class CommandSenderWithByteCount implements CommandSender
{
CommandSender commandSender;
public CommandSenderWithByteCount(CommandSender commandSender)
{
this.commandSender = commandSender;
}
public Command getCurrentCommand() {
return this.commandSender.getCurrentCommand();
}
public void handleError(int code) {
this.commandSender.handleError(code);
}
public void handleResponse(byte[] result, Command originalCommand) {
this.commandSender.handleResponse(result, originalCommand);
}
}//end class CommandSenderWithByteCount
}//end class MessageServer
| - beeing even more graceful to the robot | RobotControl/RobotConnector/src/de/hu_berlin/informatik/ki/nao/server/MessageServer.java | - beeing even more graceful to the robot | <ide><path>obotControl/RobotConnector/src/de/hu_berlin/informatik/ki/nao/server/MessageServer.java
<ide> import java.util.Map;
<ide> import java.util.concurrent.BlockingQueue;
<ide> import java.util.concurrent.LinkedBlockingQueue;
<add>import java.util.concurrent.TimeUnit;
<ide> import java.util.concurrent.locks.Lock;
<ide> import java.util.concurrent.locks.ReentrantLock;
<ide> import java.util.logging.Level;
<ide> private Thread senderThread;
<ide> private Thread receiverThread;
<ide> private Thread periodicExecutionThread;
<del> private long updateIntervall = 60;
<del> private final long graceTime = 10;
<del> private final long maxGraceTime = 500;
<add> private long updateIntervall = 33;
<ide> private List<CommandSender> listeners;
<ide> private BlockingQueue<SingleExecEntry> commandRequestQueue;
<ide> private BlockingQueue<SingleExecEntry> callbackQueue;
<ide> {
<ide> while (true)
<ide> {
<del> SingleExecEntry entry = commandRequestQueue.take();
<del>
<del> callbackQueue.put(entry);
<del>
<del> Command c = entry.command;
<del>
<del> StringBuilder buffer = new StringBuilder();
<del> buffer.append("+").append(c.getName());
<del> if (c.getArguments() != null)
<del> {
<del> for (Map.Entry<String, byte[]> e : c.getArguments().entrySet())
<del> {
<del> boolean hasArg = e.getValue() != null;
<del> buffer.append(" ");
<del> if (hasArg)
<add> SingleExecEntry entry = commandRequestQueue.poll(1, TimeUnit.SECONDS);
<add> if(entry == null)
<add> {
<add> // fire an empty message to check the connection
<add> try
<add> {
<add> if(isConnected())
<ide> {
<del> buffer.append("+");
<add> byte[] bytes = new byte[] {13};
<add> serverSocket.getOutputStream().write(bytes);
<ide> }
<del> buffer.append(e.getKey());
<del> if (hasArg)
<add> }
<add> catch (SocketException ex)
<add> {
<add> Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
<add> disconnect();
<add> }
<add> catch (IOException ex)
<add> {
<add> Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
<add> disconnect();
<add> }
<add> }
<add> else
<add> {
<add> callbackQueue.put(entry);
<add>
<add> Command c = entry.command;
<add>
<add> StringBuilder buffer = new StringBuilder();
<add> buffer.append("+").append(c.getName());
<add> if (c.getArguments() != null)
<add> {
<add> for (Map.Entry<String, byte[]> e : c.getArguments().entrySet())
<ide> {
<add> boolean hasArg = e.getValue() != null;
<ide> buffer.append(" ");
<del> buffer.append(new String(Base64.encodeBase64(e.getValue())));
<add> if (hasArg)
<add> {
<add> buffer.append("+");
<add> }
<add> buffer.append(e.getKey());
<add> if (hasArg)
<add> {
<add> buffer.append(" ");
<add> buffer.append(new String(Base64.encodeBase64(e.getValue())));
<add> }
<ide> }
<ide> }
<del> }
<del> buffer.append("\n");
<del> try
<del> {
<del> if(isConnected())
<del> {
<del> byte[] bytes = buffer.toString().getBytes();
<del> serverSocket.getOutputStream().write(bytes);
<del> sentBytes += bytes.length;
<del> }
<del> }
<del> catch (IOException ex)
<del> {
<del> Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
<del> disconnect();
<add> buffer.append("\n");
<add> try
<add> {
<add> if(isConnected())
<add> {
<add> byte[] bytes = buffer.toString().getBytes();
<add> serverSocket.getOutputStream().write(bytes);
<add> sentBytes += bytes.length;
<add> }
<add> }
<add> catch (IOException ex)
<add> {
<add> Logger.getLogger(MessageServer.class.getName()).log(Level.SEVERE, null, ex);
<add> disconnect();
<add> }
<ide> }
<ide> }
<ide> }
<ide>
<ide> long startTime = System.currentTimeMillis();
<ide>
<del> // do not send if the robot is already busy
<del> while(isConnected()
<del> && callbackQueue.size() > 0
<del> && (System.currentTimeMillis() - startTime) < maxGraceTime)
<add> // do not send if the robot is still busy
<add> while(isConnected() && callbackQueue.size() > 0)
<ide> {
<del> Thread.sleep(graceTime);
<add> Thread.yield();
<ide> }
<add>
<ide> sendPeriodicCommands();
<ide>
<ide> long stopTime = System.currentTimeMillis(); |
|
Java | lgpl-2.1 | error: pathspec 'cloveretl.engine/test/org/jetel/metadata/DataRecordParsingTypeTest.java' did not match any file(s) known to git
| e150c5e50b3ea3d254cc3f86c0f0d583d31ec57d | 1 | CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine | /*
* jETeL/CloverETL - Java based ETL application framework.
* Copyright (c) Javlin, a.s. ([email protected])
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jetel.metadata;
import org.jetel.exception.JetelRuntimeException;
import org.jetel.test.CloverTestCase;
/**
* @author Kokon ([email protected])
* (c) Javlin, a.s. (www.cloveretl.com)
*
* @created 14. 11. 2014
*/
public class DataRecordParsingTypeTest extends CloverTestCase {
public void testFromString() {
assertEquals(DataRecordParsingType.DELIMITED, DataRecordParsingType.fromString("delimited"));
assertEquals(DataRecordParsingType.DELIMITED, DataRecordParsingType.fromString("Delimited"));
assertEquals(DataRecordParsingType.FIXEDLEN, DataRecordParsingType.fromString("fixed"));
assertEquals(DataRecordParsingType.FIXEDLEN, DataRecordParsingType.fromString("fIXED"));
assertEquals(DataRecordParsingType.MIXED, DataRecordParsingType.fromString("mixed"));
assertEquals(DataRecordParsingType.MIXED, DataRecordParsingType.fromString("MIXED"));
try { DataRecordParsingType.fromString("neco"); assertTrue(false); } catch (JetelRuntimeException e) { /*OK*/ }
try { DataRecordParsingType.fromString(""); assertTrue(false); } catch (JetelRuntimeException e) { /*OK*/ }
try { DataRecordParsingType.fromString(null); assertTrue(false); } catch (JetelRuntimeException e) { /*OK*/ }
}
}
| cloveretl.engine/test/org/jetel/metadata/DataRecordParsingTypeTest.java | MINOR: test for DataRecordParsingType.fromString() method
git-svn-id: 3b972608fd747d4039df1c934c79ac563d582597@16633 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
| cloveretl.engine/test/org/jetel/metadata/DataRecordParsingTypeTest.java | MINOR: test for DataRecordParsingType.fromString() method | <ide><path>loveretl.engine/test/org/jetel/metadata/DataRecordParsingTypeTest.java
<add>/*
<add> * jETeL/CloverETL - Java based ETL application framework.
<add> * Copyright (c) Javlin, a.s. ([email protected])
<add> *
<add> * This library is free software; you can redistribute it and/or
<add> * modify it under the terms of the GNU Lesser General Public
<add> * License as published by the Free Software Foundation; either
<add> * version 2.1 of the License, or (at your option) any later version.
<add> *
<add> * This library is distributed in the hope that it will be useful,
<add> * but WITHOUT ANY WARRANTY; without even the implied warranty of
<add> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
<add> * Lesser General Public License for more details.
<add> *
<add> * You should have received a copy of the GNU Lesser General Public
<add> * License along with this library; if not, write to the Free Software
<add> * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
<add> */
<add>package org.jetel.metadata;
<add>
<add>import org.jetel.exception.JetelRuntimeException;
<add>import org.jetel.test.CloverTestCase;
<add>
<add>/**
<add> * @author Kokon ([email protected])
<add> * (c) Javlin, a.s. (www.cloveretl.com)
<add> *
<add> * @created 14. 11. 2014
<add> */
<add>public class DataRecordParsingTypeTest extends CloverTestCase {
<add>
<add> public void testFromString() {
<add> assertEquals(DataRecordParsingType.DELIMITED, DataRecordParsingType.fromString("delimited"));
<add> assertEquals(DataRecordParsingType.DELIMITED, DataRecordParsingType.fromString("Delimited"));
<add> assertEquals(DataRecordParsingType.FIXEDLEN, DataRecordParsingType.fromString("fixed"));
<add> assertEquals(DataRecordParsingType.FIXEDLEN, DataRecordParsingType.fromString("fIXED"));
<add> assertEquals(DataRecordParsingType.MIXED, DataRecordParsingType.fromString("mixed"));
<add> assertEquals(DataRecordParsingType.MIXED, DataRecordParsingType.fromString("MIXED"));
<add>
<add> try { DataRecordParsingType.fromString("neco"); assertTrue(false); } catch (JetelRuntimeException e) { /*OK*/ }
<add> try { DataRecordParsingType.fromString(""); assertTrue(false); } catch (JetelRuntimeException e) { /*OK*/ }
<add> try { DataRecordParsingType.fromString(null); assertTrue(false); } catch (JetelRuntimeException e) { /*OK*/ }
<add> }
<add>
<add>} |
|
JavaScript | bsd-2-clause | d2e1f071e731793b8f85b7fdb4ccfb635cee5a6c | 0 | zipscene/cluster-master,fasterize/cluster-master,isaacs/cluster-master | // Set up a cluster and set up resizing and such.
var cluster = require("cluster")
, quitting = false
, restarting = false
, path = require("path")
, clusterSize = 0
, os = require("os")
, onmessage
exports = module.exports = clusterMaster
exports.restart = restart
exports.resize = resize
exports.quitHard = quitHard
exports.quit = quit
function clusterMaster (config) {
if (typeof config === "string") config = { exec: config }
if (!config.exec) {
throw new Error("Must define a 'exec' script")
}
if (!cluster.isMaster) {
throw new Error("ClusterMaster answers to no one!\n"+
"(don't run in a cluster worker script)")
}
if (cluster._clusterMaster) {
throw new Error("This cluster has a master already")
}
cluster._clusterMaster = module.exports
onmessage = config.onMessage || config.onmessage
clusterSize = config.size || os.cpus().length
var masterConf = { exec: path.resolve(config.exec) }
if (config.silent) masterConf.silent = true
if (config.env) masterConf.env = config.env
cluster.setupMaster(masterConf)
if (config.signals !== false) {
// sighup/sigint listeners
setupSignals()
}
forkListener()
// start it!
restart()
}
function forkListener () {
cluster.on("fork", function (worker) {
worker.birth = Date.now()
var id = worker.uniqueID
console.error("Worker %j setting up", id)
if (onmessage) worker.on("message", onmessage)
var disconnectTimer
worker.on("exit", function () {
clearTimeout(disconnectTimer)
if (!worker.suicide) {
console.error("Worker %j exited abnormally", id)
// don't respawn right away if it's a very fast failure.
// otherwise server crashes are hard to detect from monitors.
if (Date.now() - worker.birth < 2000) {
console.error("Worker %j died too quickly, not respawning.", id)
return
}
} else {
console.error("Worker %j exited", id)
}
if (Object.keys(cluster.workers).length < clusterSize) {
resize()
}
})
worker.on("disconnect", function () {
console.error("Worker %j disconnect", id)
// give it 1 second to shut down gracefully, or kill
disconnectTimer = setTimeout(function () {
console.error("Worker %j, forcefully killing", id)
worker.process.kill("SIGKILL")
}, 2000)
})
})
}
function restart (cb) {
if (restarting) {
console.error("Already restarting. Cannot restart yet.")
return
}
restarting = true
// graceful restart.
// all the existing workers get killed, and this
// causes new ones to be spawned. If there aren't
// already the intended number, then fork new extras.
var current = Object.keys(cluster.workers)
, reqs = clusterSize - current.length
// if we're resizing, then just kill off a few.
if (reqs !== 0) resize()
// all the current workers, kill and then wait for a
// new one to spawn before moving on.
var i = 0
graceful()
function graceful () {
if (i >= current.length) {
console.error("graceful completion")
restarting = false
return cb && cb()
}
var id = current[i++]
console.error("graceful shutdown %j", id)
var worker = cluster.workers[id]
if (!worker) return graceful()
if (!quitting) {
cluster.once("fork", graceful)
} else {
worker.on("exit", graceful)
}
worker.disconnect()
}
}
function resize (n) {
if (n >= 0) clusterSize = n
var current = Object.keys(cluster.workers)
, c = current.length
, req = clusterSize - c
if (c === clusterSize) return
// make us have the right number of them.
if (req > 0) while (req -- > 0) cluster.fork()
else for (var i = clusterSize; i < c; i ++) {
cluster.workers[current[i]].disconnect()
}
}
function quitHard () {
quitting = true
quit()
}
function quit () {
if (quitting) {
console.error("Forceful shutdown")
// last ditch effort to force-kill all workers.
Object.keys(cluster.workers).forEach(function (id) {
var w = cluster.workers[id]
if (w && w.process) w.process.kill("SIGKILL")
})
process.exit(1)
}
console.error("Graceful shutdown...")
clusterSize = 0
quitting = true
restart(function () {
console.error("Graceful shutdown successful")
process.exit(0)
})
}
function setupSignals () {
process.on("SIGHUP", restart)
process.on("SIGINT", quit)
process.on("SIGKILL", quitHard)
process.on("exit", function () {
if (!quitting) quitHard()
})
}
| cluster-master.js | // Set up a cluster and set up resizing and such.
var cluster = require("cluster")
, quitting = false
, restarting = false
, path = require("path")
, clusterSize = 0
, os = require("os")
, onmessage
exports = module.exports = clusterMaster
exports.restart = restart
exports.resize = resize
exports.quitHard = quitHard
exports.quit = quit
function clusterMaster (config) {
if (typeof config === "string") config = { exec: config }
if (!config.exec) {
throw new Error("Must define a 'exec' script")
}
if (!cluster.isMaster) {
throw new Error("ClusterMaster answers to no one!\n"+
"(don't run in a cluster worker script)")
}
if (cluster._clusterMaster) {
throw new Error("This cluster has a master already")
}
cluster._clusterMaster = module.exports
onmessage = config.onMessage || config.onmessage
clusterSize = config.size || os.cpus().length
var masterConf = { exec: path.resolve(config.exec) }
if (config.silent) masterConf.silent = true
if (config.env) masterConf.env = config.env
cluster.setupMaster(masterConf)
if (config.signals !== false) {
// sighup/sigint listeners
setupSignals()
}
forkListener()
// start it!
restart()
}
function forkListener () {
cluster.on("fork", function (worker) {
var id = worker.uniqueID
console.error("Worker %j setting up", id)
if (onmessage) worker.on("message", onmessage)
var disconnectTimer
worker.on("exit", function () {
if (!worker.suicide) {
console.error("Worker %j exited abnormally", id)
} else {
console.error("Worker %j exited", id)
}
clearTimeout(disconnectTimer)
if (Object.keys(cluster.workers).length < clusterSize) {
resize()
}
})
worker.on("disconnect", function () {
console.error("Worker %j disconnect", id)
// give it 1 second to shut down gracefully, or kill
disconnectTimer = setTimeout(function () {
console.error("Worker %j, forcefully killing", id)
worker.process.kill("SIGKILL")
}, 2000)
})
})
}
function restart (cb) {
if (restarting) {
console.error("Already restarting. Cannot restart yet.")
return
}
restarting = true
// graceful restart.
// all the existing workers get killed, and this
// causes new ones to be spawned. If there aren't
// already the intended number, then fork new extras.
var current = Object.keys(cluster.workers)
, reqs = clusterSize - current.length
// if we're resizing, then just kill off a few.
if (reqs !== 0) resize()
// all the current workers, kill and then wait for a
// new one to spawn before moving on.
var i = 0
graceful()
function graceful () {
if (i >= current.length) {
console.error("graceful completion")
restarting = false
return cb && cb()
}
var id = current[i++]
console.error("graceful shutdown %j", id)
var worker = cluster.workers[id]
if (!worker) return graceful()
if (!quitting) {
cluster.once("fork", graceful)
} else {
worker.on("exit", graceful)
}
worker.disconnect()
}
}
function resize (n) {
if (n >= 0) clusterSize = n
var current = Object.keys(cluster.workers)
, c = current.length
, req = clusterSize - c
if (c === clusterSize) return
// make us have the right number of them.
if (req > 0) while (req -- > 0) cluster.fork()
else for (var i = clusterSize; i < c; i ++) {
cluster.workers[current[i]].disconnect()
}
}
function quitHard () {
quitting = true
quit()
}
function quit () {
if (quitting) {
console.error("Forceful shutdown")
// last ditch effort to force-kill all workers.
Object.keys(cluster.workers).forEach(function (id) {
var w = cluster.workers[id]
if (w && w.process) w.process.kill("SIGKILL")
})
process.exit(1)
}
console.error("Graceful shutdown...")
clusterSize = 0
quitting = true
restart(function () {
console.error("Graceful shutdown successful")
process.exit(0)
})
}
function setupSignals () {
process.on("SIGHUP", restart)
process.on("SIGINT", quit)
process.on("SIGKILL", quitHard)
process.on("exit", function () {
if (!quitting) quitHard()
})
}
| Don't respawn on fast failures
| cluster-master.js | Don't respawn on fast failures | <ide><path>luster-master.js
<ide>
<ide> function forkListener () {
<ide> cluster.on("fork", function (worker) {
<add> worker.birth = Date.now()
<ide> var id = worker.uniqueID
<ide> console.error("Worker %j setting up", id)
<ide> if (onmessage) worker.on("message", onmessage)
<ide> var disconnectTimer
<ide>
<ide> worker.on("exit", function () {
<add> clearTimeout(disconnectTimer)
<add>
<ide> if (!worker.suicide) {
<ide> console.error("Worker %j exited abnormally", id)
<add> // don't respawn right away if it's a very fast failure.
<add> // otherwise server crashes are hard to detect from monitors.
<add> if (Date.now() - worker.birth < 2000) {
<add> console.error("Worker %j died too quickly, not respawning.", id)
<add> return
<add> }
<ide> } else {
<ide> console.error("Worker %j exited", id)
<ide> }
<del> clearTimeout(disconnectTimer)
<add>
<ide> if (Object.keys(cluster.workers).length < clusterSize) {
<ide> resize()
<ide> } |
|
Java | apache-2.0 | a5a4cceb7aa9070181c3df531d11e97775f4ccca | 0 | ascrutae/sky-walking,ascrutae/sky-walking,apache/skywalking,OpenSkywalking/skywalking,apache/skywalking,hanahmily/sky-walking,apache/skywalking,zhangkewei/sky-walking,apache/skywalking,ascrutae/sky-walking,hanahmily/sky-walking,apache/skywalking,apache/skywalking,apache/skywalking,OpenSkywalking/skywalking,ascrutae/sky-walking,zhangkewei/sky-walking | package com.ai.cloud.skywalking.sender;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.logging.Logger;
import com.ai.cloud.io.netty.bootstrap.Bootstrap;
import com.ai.cloud.io.netty.channel.Channel;
import com.ai.cloud.io.netty.channel.ChannelHandlerContext;
import com.ai.cloud.io.netty.channel.ChannelInboundHandlerAdapter;
import com.ai.cloud.io.netty.channel.ChannelInitializer;
import com.ai.cloud.io.netty.channel.ChannelOption;
import com.ai.cloud.io.netty.channel.ChannelPipeline;
import com.ai.cloud.io.netty.channel.EventLoopGroup;
import com.ai.cloud.io.netty.channel.nio.NioEventLoopGroup;
import com.ai.cloud.io.netty.channel.socket.SocketChannel;
import com.ai.cloud.io.netty.channel.socket.nio.NioSocketChannel;
import com.ai.cloud.io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import com.ai.cloud.io.netty.handler.codec.LengthFieldPrepender;
import com.ai.cloud.io.netty.handler.codec.bytes.ByteArrayDecoder;
import com.ai.cloud.io.netty.handler.codec.bytes.ByteArrayEncoder;
public class DataSender extends ChannelInboundHandlerAdapter implements IDataSender {
private static Logger logger = Logger.getLogger(DataSender.class.getName());
private EventLoopGroup group;
private SenderStatus status = SenderStatus.FAILED;
private InetSocketAddress socketAddress;
private Channel channel;
public DataSender(String ip, int port) throws IOException {
this(new InetSocketAddress(ip, port));
}
public DataSender(InetSocketAddress address) throws IOException {
this.socketAddress = address;
status = SenderStatus.READY;
group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
p.addLast("frameEncoder", new LengthFieldPrepender(4));
p.addLast("decoder", new ByteArrayDecoder());
p.addLast("encoder", new ByteArrayEncoder());
p.addLast(new ChannelInboundHandlerAdapter(){
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
channel = ctx.channel();
}
});
}
});
bootstrap.connect(address).sync();
} catch (Exception e) {
status = SenderStatus.FAILED;
}
}
/**
* 返回是否发送成功
*
* @param data
* @return
*/
@Override
public boolean send(String data) {
try {
if (channel != null && channel.isActive()) {
channel.writeAndFlush(data.getBytes());
return true;
}
} catch (Exception e) {
DataSenderFactoryWithBalance.unRegister(this);
}
return false;
}
public InetSocketAddress getServerIp() {
return this.socketAddress;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
close();
}
public void close() {
if (group != null) {
group.shutdownGracefully();
}
}
public enum SenderStatus {
READY, FAILED
}
public SenderStatus getStatus() {
return status;
}
public void setStatus(SenderStatus status) {
this.status = status;
}
}
| skywalking-api/src/main/java/com/ai/cloud/skywalking/sender/DataSender.java | package com.ai.cloud.skywalking.sender;
import com.ai.cloud.io.netty.bootstrap.Bootstrap;
import com.ai.cloud.io.netty.channel.*;
import com.ai.cloud.io.netty.channel.nio.NioEventLoopGroup;
import com.ai.cloud.io.netty.channel.socket.ServerSocketChannel;
import com.ai.cloud.io.netty.channel.socket.nio.NioSocketChannel;
import com.ai.cloud.io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import com.ai.cloud.io.netty.handler.codec.LengthFieldPrepender;
import com.ai.cloud.io.netty.handler.codec.bytes.ByteArrayDecoder;
import com.ai.cloud.io.netty.handler.codec.bytes.ByteArrayEncoder;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.logging.Logger;
public class DataSender extends ChannelInboundHandlerAdapter implements IDataSender {
private static Logger logger = Logger.getLogger(DataSender.class.getName());
private EventLoopGroup group;
private SenderStatus status = SenderStatus.FAILED;
private InetSocketAddress socketAddress;
private ChannelFuture channelFuture;
public DataSender(String ip, int port) throws IOException {
this(new InetSocketAddress(ip, port));
}
public DataSender(InetSocketAddress address) throws IOException {
this.socketAddress = address;
status = SenderStatus.READY;
group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<ServerSocketChannel>() {
@Override
protected void initChannel(ServerSocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
p.addLast("frameEncoder", new LengthFieldPrepender(4));
p.addLast("decoder", new ByteArrayDecoder());
p.addLast("encoder", new ByteArrayEncoder());
}
});
channelFuture = bootstrap.connect(address).sync();
} catch (Exception e) {
status = SenderStatus.FAILED;
}
}
/**
* 返回是否发送成功
*
* @param data
* @return
*/
@Override
public boolean send(String data) {
try {
if (channelFuture != null) {
channelFuture.channel().writeAndFlush(data);
return true;
}
} catch (Exception e) {
DataSenderFactoryWithBalance.unRegister(this);
}
return false;
}
public InetSocketAddress getServerIp() {
return this.socketAddress;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
close();
}
public void close() {
if (group != null) {
group.shutdownGracefully();
}
}
public enum SenderStatus {
READY, FAILED
}
public SenderStatus getStatus() {
return status;
}
public void setStatus(SenderStatus status) {
this.status = status;
}
}
| 1.修改发送代码。
| skywalking-api/src/main/java/com/ai/cloud/skywalking/sender/DataSender.java | 1.修改发送代码。 | <ide><path>kywalking-api/src/main/java/com/ai/cloud/skywalking/sender/DataSender.java
<ide> package com.ai.cloud.skywalking.sender;
<ide>
<add>import java.io.IOException;
<add>import java.net.InetSocketAddress;
<add>import java.util.logging.Logger;
<add>
<ide> import com.ai.cloud.io.netty.bootstrap.Bootstrap;
<del>import com.ai.cloud.io.netty.channel.*;
<add>import com.ai.cloud.io.netty.channel.Channel;
<add>import com.ai.cloud.io.netty.channel.ChannelHandlerContext;
<add>import com.ai.cloud.io.netty.channel.ChannelInboundHandlerAdapter;
<add>import com.ai.cloud.io.netty.channel.ChannelInitializer;
<add>import com.ai.cloud.io.netty.channel.ChannelOption;
<add>import com.ai.cloud.io.netty.channel.ChannelPipeline;
<add>import com.ai.cloud.io.netty.channel.EventLoopGroup;
<ide> import com.ai.cloud.io.netty.channel.nio.NioEventLoopGroup;
<del>import com.ai.cloud.io.netty.channel.socket.ServerSocketChannel;
<add>import com.ai.cloud.io.netty.channel.socket.SocketChannel;
<ide> import com.ai.cloud.io.netty.channel.socket.nio.NioSocketChannel;
<ide> import com.ai.cloud.io.netty.handler.codec.LengthFieldBasedFrameDecoder;
<ide> import com.ai.cloud.io.netty.handler.codec.LengthFieldPrepender;
<ide> import com.ai.cloud.io.netty.handler.codec.bytes.ByteArrayDecoder;
<ide> import com.ai.cloud.io.netty.handler.codec.bytes.ByteArrayEncoder;
<ide>
<del>import java.io.IOException;
<del>import java.net.InetSocketAddress;
<del>import java.util.logging.Logger;
<del>
<ide> public class DataSender extends ChannelInboundHandlerAdapter implements IDataSender {
<ide> private static Logger logger = Logger.getLogger(DataSender.class.getName());
<ide> private EventLoopGroup group;
<ide> private SenderStatus status = SenderStatus.FAILED;
<ide> private InetSocketAddress socketAddress;
<del> private ChannelFuture channelFuture;
<add> private Channel channel;
<ide>
<ide> public DataSender(String ip, int port) throws IOException {
<ide> this(new InetSocketAddress(ip, port));
<ide> bootstrap.group(group)
<ide> .channel(NioSocketChannel.class)
<ide> .option(ChannelOption.TCP_NODELAY, true)
<del> .handler(new ChannelInitializer<ServerSocketChannel>() {
<add> .handler(new ChannelInitializer<SocketChannel>() {
<ide> @Override
<del> protected void initChannel(ServerSocketChannel ch) throws Exception {
<add> protected void initChannel(SocketChannel ch) throws Exception {
<ide> ChannelPipeline p = ch.pipeline();
<ide> p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
<ide> p.addLast("frameEncoder", new LengthFieldPrepender(4));
<ide> p.addLast("decoder", new ByteArrayDecoder());
<ide> p.addLast("encoder", new ByteArrayEncoder());
<add> p.addLast(new ChannelInboundHandlerAdapter(){
<add> public void channelActive(ChannelHandlerContext ctx) throws Exception {
<add> super.channelActive(ctx);
<add> channel = ctx.channel();
<add> }
<add> });
<ide> }
<ide> });
<del> channelFuture = bootstrap.connect(address).sync();
<add> bootstrap.connect(address).sync();
<ide> } catch (Exception e) {
<ide> status = SenderStatus.FAILED;
<ide> }
<ide> @Override
<ide> public boolean send(String data) {
<ide> try {
<del> if (channelFuture != null) {
<del> channelFuture.channel().writeAndFlush(data);
<add> if (channel != null && channel.isActive()) {
<add> channel.writeAndFlush(data.getBytes());
<ide> return true;
<ide> }
<ide> } catch (Exception e) { |
|
JavaScript | mit | a5c1cabfb60443c13a869f16ed053c6e012a1631 | 0 | JonClayton/phase-0,JonClayton/phase-0,JonClayton/phase-0 | /* Design Basic Game Solo Challenge
// This is a solo challenge
Your mission description:
Overall mission: win at checkers
Goals: move ahead. In later versions, jump, be kinged, etc.
Characters: Red team and black team (X and O in the ASCII version)
Objects: Each useable square on board will be an object held within the board array, with properties.
Functions: display board, and ask for/implement move. Later, check for win, make move for computer player.
Pseudocode for MVP
build function for ASCII graphic depiction of 8x8 checkers board with ---- on unplayable spaces and open spaces have a space number along with " " or "X" or "O" to show whether they are open or occupied and by which team
- draw top line
- draw each row
- draw side vertical line
- draw contents of square
- determine whether playable square
- get state of square from board state object
- format square with space number and state
- draw interior vertical line
- repeat to complete row
- draw side line
- draw bottom line
build array of objects to store board state (open, X or O spaces)
- initalize with 32 objects, one for each square, by number (0 index element is a null)
- Property: owner, with squares 1-12 are black (X), squares 13-20 are empty (-), and squares 21-32 are red (O)
- Property: upward moves (to higher numbers)
- Property: downward moves (to lower number)
build function to ask for and implement move for each player
- ask player which piece he wants to move
- look up piece on board
- check color
- based on color, check spaces it could move to
- check whether spaces are open
- if only one, make move
- if two open, ask which one he wants to move to
- if none open, ask for different piece to move
- change board to reflect outcome of move
- change owner of old space to nobody
- change owner of new space to mover
- print board
- later improvements:
- jump moves
- additional jumps on same move if available
- taking turns
- kinging and reversible movement as a result
- visual display of board
- click entry to move and destination
- automatic analysis of which pieces can move and when clicked, where they can move to
- display available moves by flashing piece, and destinations when piece is clicked
- AI so you can play against the computer
- initially, random choice among available moves
- improve AI with following rules
- avoid moving last row
- get kinged when possible
- take jumps when possible
- avoid moving out of unjumpable positions
- avoid moving into jumpable positions
- develop deeper analysis of position
- recursive evaluation of future moves?
- method to recognize better positions?
- other ways to assess value of moves that I haven't thought of yet.
// Initial Code
*/
var hLine = "-------------------------------------------------------------------";
function SquareLineOutput(row,col,line) {
if ((row+col)%2==0) return "-------|";
var space=(8-row)*4+(Math.ceil(col/2))
var spaceString = " " + space.toString();
var owner = board[space].owner
if (space < 10) spaceString = " "+spaceString;
if (line<3) spaceString = owner+owner+owner;
if (line==2 && board[space].king) return " King |";
return owner+owner+owner+owner+spaceString+"|";
}
function PrintBoard() {
console.log(hLine);
for(var row = 1; row < 9; row++) {
for (var line = 1; line < 4; line++) {
var lineString = ("||");
for (var col = 1; col < 9; col++) {
lineString += SquareLineOutput(row,col,line); //add contents of line within square
}
lineString += ("|");
console.log(lineString);
}
console.log(hLine);
}
}
var board = []
function Space (number, owner) {
this.name = "space" + number.toString();
this.owner = owner;
this.upMoves = [];
this.downMoves = [];
this.upJumps = [];
this.downJumps = [];
this.king = false;
}
function InitializeBoard() {
for (space =1; space < 33; space++) {
var owner = " "
if (space < 13) owner = "X";
if (space > 20) owner = "O";
board[space] = new Space (space, owner);
}
board[1].upMoves = [5];
board[2].upMoves = [5,6];
board[3].upMoves = [6,7];
board[4].upMoves = [7,8];
board[5].upMoves = [10,9];
board[6].upMoves = [10,11];
board[7].upMoves = [11,12];
board[8].upMoves = [12];
for (var space = 9; space < 29; space++) {
board[space].upMoves[0] = board[space-8].upMoves[0]+8;
if (board[space-8].upMoves[1]>0) board[space].upMoves[1] = board[space-8].upMoves[1]+8;
}
board[5].downMoves = [2,1];
board[6].downMoves = [2,3];
board[7].downMoves = [3,4];
board[8].downMoves = [4];
board[9].downMoves = [5];
board[10].downMoves = [5,6];
board[11].downMoves = [6,7];
board[12].downMoves = [7,8];
for (var space = 13; space < 33; space++) {
board[space].downMoves[0] = board[space-8].downMoves[0]+8;
if (board[space-8].downMoves[1]>0) board[space].downMoves[1] = board[space-8].downMoves[1]+8;
}
board[1].upJumps = [10];
board[2].upJumps = [9,11];
board[3].upJumps = [10,12];
board[4].upJumps = [11];
board[5].upJumps = [14];
board[6].upJumps = [13,15];
board[7].upJumps = [14,16];
board[8].upJumps = [15];
for (var space = 9; space < 25; space++) {
board[space].upJumps[0] = board[space-8].upJumps[0]+8;
if (board[space-8].upJumps[1]>0) board[space].upJumps[1] = board[space-8].upJumps[1]+8;
}
board[13].downJumps = [6];
board[14].downJumps = [5,7];
board[15].downJumps = [6,8];
board[16].downJumps = [7];
board[9].downJumps = [2];
board[10].downJumps = [1,3];
board[11].downJumps = [2,4];
board[12].downJumps = [3];
for (var space = 17; space < 33; space++) {
board[space].downJumps[0] = board[space-8].downJumps[0]+8;
if (board[space-8].downJumps[1]>0) board[space].downJumps[1] = board[space-8].downJumps[1]+8;
}
}
function UpdateBoardHTML() {
board.forEach (function (space, index) {
var color = false
if (space.owner == "X") color = "red";
if (space.owner == "O") color = "black";
var square = document.getElementById(space.name);
if (color) console.log(square.style.background = color);
else console.log(square.style.background = "");
if (space.king) {
console.log(square.style.height = "4em")
console.log(square.style.width = "4em")
console.log(square.style.border = "0.25em solid gold")
}
else {
console.log(square.style.height = "4.5em")
console.log(square.style.width = "4.5em")
console.log(square.style.border = "0em solid black")
}
})
}
function MoveValidator(start,finish) {
if (board[start].owner == " ") return [false, "There is no checker on that space."];
if (board[finish].owner != " ") return [false, "The target space is occupied."];
var validMove = false;
if (board[start].owner == "X" || board[start].king) {
board[start].upMoves.forEach(function (space) {if (space == finish) validMove=[true, "move"]});
board[start].upJumps.forEach(function (space, index) {
if (space == finish && board[board[start].upMoves[index]].owner!=" " && board[board[start].upMoves[index]].owner!=board[start].owner) validMove=[true, board[start].upMoves[index]]});
}
if (board[start].owner == "O" || board[start].king) {
board[start].downMoves.forEach(function (space) {if (space == finish) validMove=[true, "move"]});
board[start].downJumps.forEach(function (space, index) {
if (space == finish && board[board[start].downMoves[index]].owner!=" " && board[board[start].downMoves[index]].owner!=board[start].owner) validMove=[true,board[start].downMoves[index]]});
}
if (!validMove) return [false, "That checker cannot move there."];
return validMove;
}
function KingMe (space) {
if (space < 5 && board[space].owner == "O") board[space].king = true;
if (space >27 && board[space].owner == "X") board[space].king = true;
}
function WinCheck() {
var winX = true;
var winO = true;
board.forEach(function(square) {
if (square.owner == "X") winO = false;
if (square.owner == "O") winX = false;
if (!winX && !winO) return false
})
if (winX) console.log("X has won the game!!!");
if (winO) console.log("O has won the game!!!");
return true
}
function Move(start, finish) {
var validity = MoveValidator(start,finish)
if (!validity[0]) {
console.log(validity[1]);
return;
}
board[finish].owner = board[start].owner;
board[finish].king = board[start].king;
board[start].owner = " ";
board[start].king = false;
if (!isNaN(validity[1])) {
board[validity[1]].owner=" ";
board[validity[1]].king=false;
}
KingMe(finish);
PrintBoard();
UpdateBoardHTML();
console.log("Move completed", start, " to ", finish);
WinCheck()
}
//test code
InitializeBoard();
UpdateBoardHTML();
Move(13,17);
Move(9,19);
Move(9,21);
Move(10,14);
Move(9,13);
Move(22,18);
Move(13,22);
Move(27,18);
Move(21,17);
Move(30,27);
Move(14,21);
Move(21,30);
Move(23,19);
Move(30,23);
Move(23,14);
Move(17,13);
Move(13,10);
Move(6,13);
Move(29,26);
Move(25,21);
Move(21,18);
Move(14,21);
Move(21,30);
Move(31,27);
Move(24,20);
Move(11,15);
Move(15,24);
Move(24,31);
Move(30,23);
Move(32,28);
Move(23,32);
// Refactored Code
// Reflection
//
//
//
//
//
//
//
// | week-7/design-basic-game-solo-challenge/my_solution.js | /* Design Basic Game Solo Challenge
// This is a solo challenge
Your mission description:
Overall mission: win at checkers
Goals: move ahead. In later versions, jump, be kinged, etc.
Characters: Red team and black team (X and O in the ASCII version)
Objects: Each useable square on board will be an object held within the board array, with properties.
Functions: display board, and ask for/implement move. Later, check for win, make move for computer player.
Pseudocode for MVP
build function for ASCII graphic depiction of 8x8 checkers board with ---- on unplayable spaces and open spaces have a space number along with " " or "X" or "O" to show whether they are open or occupied and by which team
- draw top line
- draw each row
- draw side vertical line
- draw contents of square
- determine whether playable square
- get state of square from board state object
- format square with space number and state
- draw interior vertical line
- repeat to complete row
- draw side line
- draw bottom line
build array of objects to store board state (open, X or O spaces)
- initalize with 32 objects, one for each square, by number (0 index element is a null)
- Property: owner, with squares 1-12 are black (X), squares 13-20 are empty (-), and squares 21-32 are red (O)
- Property: upward moves (to higher numbers)
- Property: downward moves (to lower number)
build function to ask for and implement move for each player
- ask player which piece he wants to move
- look up piece on board
- check color
- based on color, check spaces it could move to
- check whether spaces are open
- if only one, make move
- if two open, ask which one he wants to move to
- if none open, ask for different piece to move
- change board to reflect outcome of move
- change owner of old space to nobody
- change owner of new space to mover
- print board
- later improvements:
- jump moves
- additional jumps on same move if available
- taking turns
- kinging and reversible movement as a result
- visual display of board
- click entry to move and destination
- automatic analysis of which pieces can move and when clicked, where they can move to
- display available moves by flashing piece, and destinations when piece is clicked
- AI so you can play against the computer
- initially, random choice among available moves
- improve AI with following rules
- avoid moving last row
- get kinged when possible
- take jumps when possible
- avoid moving out of unjumpable positions
- avoid moving into jumpable positions
- develop deeper analysis of position
- recursive evaluation of future moves?
- method to recognize better positions?
- other ways to assess value of moves that I haven't thought of yet.
// Initial Code
*/
var hLine = "-------------------------------------------------------------------";
function SquareLineOutput(row,col,line) {
if ((row+col)%2==0) return "-------|";
var space=(8-row)*4+(Math.ceil(col/2))
var spaceString = " " + space.toString();
var owner = board[space].owner
if (space < 10) spaceString = " "+spaceString;
if (line<3) spaceString = owner+owner+owner;
if (line==2 && board[space].king) return " King |";
return owner+owner+owner+owner+spaceString+"|";
}
function PrintBoard() {
console.log(hLine);
for(var row = 1; row < 9; row++) {
for (var line = 1; line < 4; line++) {
var lineString = ("||");
for (var col = 1; col < 9; col++) {
lineString += SquareLineOutput(row,col,line); //add contents of line within square
}
lineString += ("|");
console.log(lineString);
}
console.log(hLine);
}
}
var board = []
function Space (number, owner) {
this.name = "space" + number.toString();
this.owner = owner;
this.upMoves = [];
this.downMoves = [];
this.upJumps = [];
this.downJumps = [];
this.king = false;
}
function InitializeBoard() {
for (space =1; space < 33; space++) {
var owner = " "
if (space < 13) owner = "X";
if (space > 20) owner = "O";
board[space] = new Space (space, owner);
}
board[1].upMoves = [5];
board[2].upMoves = [5,6];
board[3].upMoves = [6,7];
board[4].upMoves = [7,8];
board[5].upMoves = [10,9];
board[6].upMoves = [10,11];
board[7].upMoves = [11,12];
board[8].upMoves = [12];
for (var space = 9; space < 29; space++) {
board[space].upMoves[0] = board[space-8].upMoves[0]+8;
if (board[space-8].upMoves[1]>0) board[space].upMoves[1] = board[space-8].upMoves[1]+8;
}
board[5].downMoves = [2,1];
board[6].downMoves = [2,3];
board[7].downMoves = [3,4];
board[8].downMoves = [4];
board[9].downMoves = [5];
board[10].downMoves = [5,6];
board[11].downMoves = [6,7];
board[12].downMoves = [7,8];
for (var space = 13; space < 33; space++) {
board[space].downMoves[0] = board[space-8].downMoves[0]+8;
if (board[space-8].downMoves[1]>0) board[space].downMoves[1] = board[space-8].downMoves[1]+8;
}
board[1].upJumps = [10];
board[2].upJumps = [9,11];
board[3].upJumps = [10,12];
board[4].upJumps = [11];
board[5].upJumps = [14];
board[6].upJumps = [13,15];
board[7].upJumps = [14,16];
board[8].upJumps = [15];
for (var space = 9; space < 25; space++) {
board[space].upJumps[0] = board[space-8].upJumps[0]+8;
if (board[space-8].upJumps[1]>0) board[space].upJumps[1] = board[space-8].upJumps[1]+8;
}
board[13].downJumps = [6];
board[14].downJumps = [5,7];
board[15].downJumps = [6,8];
board[16].downJumps = [7];
board[9].downJumps = [2];
board[10].downJumps = [1,3];
board[11].downJumps = [2,4];
board[12].downJumps = [3];
for (var space = 17; space < 33; space++) {
board[space].downJumps[0] = board[space-8].downJumps[0]+8;
if (board[space-8].downJumps[1]>0) board[space].downJumps[1] = board[space-8].downJumps[1]+8;
}
}
function MoveValidator(start,finish) {
if (board[start].owner == " ") return [false, "There is no checker on that space."];
if (board[finish].owner != " ") return [false, "The target space is occupied."];
var validMove = false;
if (board[start].owner == "X" || board[start].king) {
board[start].upMoves.forEach(function (space) {if (space == finish) validMove=[true, "move"]});
board[start].upJumps.forEach(function (space, index) {
if (space == finish && board[board[start].upMoves[index]].owner!=" " && board[board[start].upMoves[index]].owner!=board[start].owner) validMove=[true, board[start].upMoves[index]]});
}
if (board[start].owner == "O" || board[start].king) {
board[start].downMoves.forEach(function (space) {if (space == finish) validMove=[true, "move"]});
board[start].downJumps.forEach(function (space, index) {
if (space == finish && board[board[start].downMoves[index]].owner!=" " && board[board[start].downMoves[index]].owner!=board[start].owner) validMove=[true,board[start].downMoves[index]]});
}
if (!validMove) return [false, "That checker cannot move there."];
return validMove;
}
function KingMe (space) {
if (space < 5 && board[space].owner == "O") board[space].king = true;
if (space >27 && board[space].owner == "X") board[space].king = true;
}
function WinCheck() {
var winX = true;
var winO = true;
board.forEach(function(square) {
if (square.owner == "X") winO = false;
if (square.owner == "O") winX = false;
if (!winX && !winO) return false
})
if (winX) console.log("X has won the game!!!");
if (winO) console.log("O has won the game!!!");
return true
}
function Move(start, finish) {
var validity = MoveValidator(start,finish)
if (!validity[0]) {
console.log(validity[1]);
return;
}
board[finish].owner = board[start].owner;
board[finish].king = board[start].king;
board[start].owner = " ";
board[start].king = false;
if (!isNaN(validity[1])) {
board[validity[1]].owner=" ";
board[validity[1]].king=false;
}
KingMe(finish);
PrintBoard();
console.log("Move completed", start, " to ", finish);
WinCheck()
}
//test code
InitializeBoard();
Move(13,17);
Move(9,19);
Move(9,21);
Move(10,14);
Move(9,13);
Move(22,18);
Move(13,22);
Move(27,18);
Move(21,17);
Move(30,27);
Move(14,21);
Move(21,30);
Move(23,19);
Move(30,23);
Move(23,14);
Move(17,13);
Move(13,10);
Move(6,13);
Move(29,26);
Move(25,21);
Move(21,18);
Move(14,21);
Move(21,30);
Move(31,27);
Move(24,20);
Move(11,15);
Move(15,24);
Move(24,31);
Move(30,23);
Move(32,28);
Move(23,32);
// Refactored Code
// Reflection
//
//
//
//
//
//
//
// | Add working web board
| week-7/design-basic-game-solo-challenge/my_solution.js | Add working web board | <ide><path>eek-7/design-basic-game-solo-challenge/my_solution.js
<ide> }
<ide> }
<ide>
<add>function UpdateBoardHTML() {
<add> board.forEach (function (space, index) {
<add> var color = false
<add> if (space.owner == "X") color = "red";
<add> if (space.owner == "O") color = "black";
<add> var square = document.getElementById(space.name);
<add> if (color) console.log(square.style.background = color);
<add> else console.log(square.style.background = "");
<add> if (space.king) {
<add> console.log(square.style.height = "4em")
<add> console.log(square.style.width = "4em")
<add> console.log(square.style.border = "0.25em solid gold")
<add> }
<add> else {
<add> console.log(square.style.height = "4.5em")
<add> console.log(square.style.width = "4.5em")
<add> console.log(square.style.border = "0em solid black")
<add> }
<add> })
<add>}
<add>
<ide> function MoveValidator(start,finish) {
<ide> if (board[start].owner == " ") return [false, "There is no checker on that space."];
<ide> if (board[finish].owner != " ") return [false, "The target space is occupied."];
<ide> }
<ide> KingMe(finish);
<ide> PrintBoard();
<add> UpdateBoardHTML();
<ide> console.log("Move completed", start, " to ", finish);
<ide> WinCheck()
<ide> }
<ide> //test code
<ide>
<ide> InitializeBoard();
<add>UpdateBoardHTML();
<add>
<add>
<ide> Move(13,17);
<ide> Move(9,19);
<ide> Move(9,21); |
|
Java | mit | 792b0c5a675f33a45f62d453e9d8124736723ef8 | 0 | Moudoux/EMC | package me.deftware.client.framework.helper;
import me.deftware.client.framework.item.ItemStack;
import net.minecraft.client.MinecraftClient;
import net.minecraft.screen.GenericContainerScreenHandler;
import java.util.Objects;
/**
* @author Deftware
*/
public class ContainerHelper {
private static GenericContainerScreenHandler getCurrent() {
if (Objects.requireNonNull(MinecraftClient.getInstance().player).currentScreenHandler != null && MinecraftClient.getInstance().player.currentScreenHandler instanceof GenericContainerScreenHandler) {
return (GenericContainerScreenHandler) MinecraftClient.getInstance().player.currentScreenHandler;
}
return null;
}
public static boolean isOpen() {
return getCurrent() != null;
}
public static int getInventorySize() {
return Objects.requireNonNull(getCurrent()).getInventory().size();
}
public static ItemStack getStackInSlot(int id) {
return new ItemStack(Objects.requireNonNull(getCurrent()).getInventory().getStack(id));
}
public static int getContainerID() {
return Objects.requireNonNull(getCurrent()).syncId;
}
public static boolean isEmpty() {
return Objects.requireNonNull(getCurrent()).getInventory().isEmpty();
}
public static int getMaxSlots() {
return Objects.requireNonNull(getCurrent()).slots.size();
}
}
| src/main/java/me/deftware/client/framework/helper/ContainerHelper.java | package me.deftware.client.framework.helper;
import me.deftware.client.framework.item.ItemStack;
import net.minecraft.client.MinecraftClient;
import net.minecraft.screen.GenericContainerScreenHandler;
import java.util.Objects;
/**
* @author Deftware
*/
public class ContainerHelper {
private static GenericContainerScreenHandler getCurrent() {
if (Objects.requireNonNull(MinecraftClient.getInstance().player).currentScreenHandler != null) {
return (GenericContainerScreenHandler) MinecraftClient.getInstance().player.currentScreenHandler;
}
return null;
}
public static int getInventorySize() {
return Objects.requireNonNull(getCurrent()).getInventory().size();
}
public static ItemStack getStackInSlot(int id) {
return new ItemStack(Objects.requireNonNull(getCurrent()).getInventory().getStack(id));
}
public static int getContainerID() {
return Objects.requireNonNull(getCurrent()).syncId;
}
public static boolean isEmpty() {
return Objects.requireNonNull(getCurrent()).getInventory().isEmpty();
}
public static int getMaxSlots() {
return Objects.requireNonNull(getCurrent()).slots.size();
}
}
| Fix class cast exception
| src/main/java/me/deftware/client/framework/helper/ContainerHelper.java | Fix class cast exception | <ide><path>rc/main/java/me/deftware/client/framework/helper/ContainerHelper.java
<ide> public class ContainerHelper {
<ide>
<ide> private static GenericContainerScreenHandler getCurrent() {
<del> if (Objects.requireNonNull(MinecraftClient.getInstance().player).currentScreenHandler != null) {
<add> if (Objects.requireNonNull(MinecraftClient.getInstance().player).currentScreenHandler != null && MinecraftClient.getInstance().player.currentScreenHandler instanceof GenericContainerScreenHandler) {
<ide> return (GenericContainerScreenHandler) MinecraftClient.getInstance().player.currentScreenHandler;
<ide> }
<ide> return null;
<add> }
<add>
<add> public static boolean isOpen() {
<add> return getCurrent() != null;
<ide> }
<ide>
<ide> public static int getInventorySize() { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.